2 * composite.c - infrastructure for Composite USB Gadgets
4 * Copyright (C) 2006-2008 David Brownell
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 /* #define VERBOSE_DEBUG */
23 #include <linux/kallsyms.h>
24 #include <linux/kernel.h>
25 #include <linux/slab.h>
26 #include <linux/device.h>
28 #include <linux/usb/composite.h>
32 * The code in this file is utility code, used to build a gadget driver
33 * from one or more "function" drivers, one or more "configuration"
34 * objects, and a "usb_composite_driver" by gluing them together along
35 * with the relevant device-wide data.
38 /* big enough to hold our biggest descriptor */
39 #define USB_BUFSIZ 1024
41 static struct usb_composite_driver *composite;
43 /* Some systems will need runtime overrides for the product identifers
44 * published in the device descriptor, either numbers or strings or both.
45 * String parameters are in UTF-8 (superset of ASCII's 7 bit characters).
48 static ushort idVendor;
49 module_param(idVendor, ushort, 0);
50 MODULE_PARM_DESC(idVendor, "USB Vendor ID");
52 static ushort idProduct;
53 module_param(idProduct, ushort, 0);
54 MODULE_PARM_DESC(idProduct, "USB Product ID");
56 static ushort bcdDevice;
57 module_param(bcdDevice, ushort, 0);
58 MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
60 static char *iManufacturer;
61 module_param(iManufacturer, charp, 0);
62 MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
64 static char *iProduct;
65 module_param(iProduct, charp, 0);
66 MODULE_PARM_DESC(iProduct, "USB Product string");
68 static char *iSerialNumber;
69 module_param(iSerialNumber, charp, 0);
70 MODULE_PARM_DESC(iSerialNumber, "SerialNumber string");
72 /*-------------------------------------------------------------------------*/
74 static ssize_t enable_show(struct device *dev, struct device_attribute *attr,
77 struct usb_function *f = dev_get_drvdata(dev);
78 return sprintf(buf, "%d\n", !f->disabled);
81 static ssize_t enable_store(
82 struct device *dev, struct device_attribute *attr,
83 const char *buf, size_t size)
85 struct usb_function *f = dev_get_drvdata(dev);
86 struct usb_composite_driver *driver = f->config->cdev->driver;
89 sscanf(buf, "%d", &value);
90 if (driver->enable_function)
91 driver->enable_function(f, value);
93 usb_function_set_enabled(f, value);
98 static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
100 void usb_function_set_enabled(struct usb_function *f, int enabled)
102 f->disabled = !enabled;
103 kobject_uevent(&f->dev->kobj, KOBJ_CHANGE);
107 void usb_composite_force_reset(struct usb_composite_dev *cdev)
111 spin_lock_irqsave(&cdev->lock, flags);
112 /* force reenumeration */
113 if (cdev && cdev->gadget && cdev->gadget->speed != USB_SPEED_UNKNOWN) {
114 spin_unlock_irqrestore(&cdev->lock, flags);
116 usb_gadget_disconnect(cdev->gadget);
118 usb_gadget_connect(cdev->gadget);
120 spin_unlock_irqrestore(&cdev->lock, flags);
125 * usb_add_function() - add a function to a configuration
126 * @config: the configuration
127 * @function: the function being added
128 * Context: single threaded during gadget setup
130 * After initialization, each configuration must have one or more
131 * functions added to it. Adding a function involves calling its @bind()
132 * method to allocate resources such as interface and string identifiers
135 * This function returns the value of the function's bind(), which is
136 * zero for success else a negative errno value.
138 int usb_add_function(struct usb_configuration *config,
139 struct usb_function *function)
141 struct usb_composite_dev *cdev = config->cdev;
145 DBG(cdev, "adding '%s'/%p to config '%s'/%p\n",
146 function->name, function,
147 config->label, config);
149 if (!function->set_alt || !function->disable)
152 index = atomic_inc_return(&cdev->driver->function_count);
153 function->dev = device_create(cdev->driver->class, NULL,
154 MKDEV(0, index), NULL, function->name);
155 if (IS_ERR(function->dev))
156 return PTR_ERR(function->dev);
158 value = device_create_file(function->dev, &dev_attr_enable);
160 device_destroy(cdev->driver->class, MKDEV(0, index));
163 dev_set_drvdata(function->dev, function);
165 function->config = config;
166 list_add_tail(&function->list, &config->functions);
168 /* REVISIT *require* function->bind? */
169 if (function->bind) {
170 value = function->bind(config, function);
172 list_del(&function->list);
173 function->config = NULL;
178 /* We allow configurations that don't work at both speeds.
179 * If we run into a lowspeed Linux system, treat it the same
180 * as full speed ... it's the function drivers that will need
181 * to avoid bulk and ISO transfers.
183 if (!config->fullspeed && function->descriptors)
184 config->fullspeed = true;
185 if (!config->highspeed && function->hs_descriptors)
186 config->highspeed = true;
190 DBG(cdev, "adding '%s'/%p --> %d\n",
191 function->name, function, value);
196 * usb_function_deactivate - prevent function and gadget enumeration
197 * @function: the function that isn't yet ready to respond
199 * Blocks response of the gadget driver to host enumeration by
200 * preventing the data line pullup from being activated. This is
201 * normally called during @bind() processing to change from the
202 * initial "ready to respond" state, or when a required resource
205 * For example, drivers that serve as a passthrough to a userspace
206 * daemon can block enumeration unless that daemon (such as an OBEX,
207 * MTP, or print server) is ready to handle host requests.
209 * Not all systems support software control of their USB peripheral
212 * Returns zero on success, else negative errno.
214 int usb_function_deactivate(struct usb_function *function)
216 struct usb_composite_dev *cdev = function->config->cdev;
220 spin_lock_irqsave(&cdev->lock, flags);
222 if (cdev->deactivations == 0)
223 status = usb_gadget_disconnect(cdev->gadget);
225 cdev->deactivations++;
227 spin_unlock_irqrestore(&cdev->lock, flags);
232 * usb_function_activate - allow function and gadget enumeration
233 * @function: function on which usb_function_activate() was called
235 * Reverses effect of usb_function_deactivate(). If no more functions
236 * are delaying their activation, the gadget driver will respond to
237 * host enumeration procedures.
239 * Returns zero on success, else negative errno.
241 int usb_function_activate(struct usb_function *function)
243 struct usb_composite_dev *cdev = function->config->cdev;
246 spin_lock(&cdev->lock);
248 if (WARN_ON(cdev->deactivations == 0))
251 cdev->deactivations--;
252 if (cdev->deactivations == 0)
253 status = usb_gadget_connect(cdev->gadget);
256 spin_unlock(&cdev->lock);
261 * usb_interface_id() - allocate an unused interface ID
262 * @config: configuration associated with the interface
263 * @function: function handling the interface
264 * Context: single threaded during gadget setup
266 * usb_interface_id() is called from usb_function.bind() callbacks to
267 * allocate new interface IDs. The function driver will then store that
268 * ID in interface, association, CDC union, and other descriptors. It
269 * will also handle any control requests targetted at that interface,
270 * particularly changing its altsetting via set_alt(). There may
271 * also be class-specific or vendor-specific requests to handle.
273 * All interface identifier should be allocated using this routine, to
274 * ensure that for example different functions don't wrongly assign
275 * different meanings to the same identifier. Note that since interface
276 * identifers are configuration-specific, functions used in more than
277 * one configuration (or more than once in a given configuration) need
278 * multiple versions of the relevant descriptors.
280 * Returns the interface ID which was allocated; or -ENODEV if no
281 * more interface IDs can be allocated.
283 int usb_interface_id(struct usb_configuration *config,
284 struct usb_function *function)
286 unsigned id = config->next_interface_id;
288 if (id < MAX_CONFIG_INTERFACES) {
289 config->interface[id] = function;
290 config->next_interface_id = id + 1;
296 static int config_buf(struct usb_configuration *config,
297 enum usb_device_speed speed, void *buf, u8 type)
299 struct usb_config_descriptor *c = buf;
300 struct usb_interface_descriptor *intf;
301 struct usb_interface_assoc_descriptor *iad = NULL;
302 void *next = buf + USB_DT_CONFIG_SIZE;
303 int len = USB_BUFSIZ - USB_DT_CONFIG_SIZE;
304 struct usb_function *f;
306 int interfaceCount = 0;
309 /* write the config descriptor */
311 c->bLength = USB_DT_CONFIG_SIZE;
312 c->bDescriptorType = type;
313 /* wTotalLength and bNumInterfaces are written later */
314 c->bConfigurationValue = config->bConfigurationValue;
315 c->iConfiguration = config->iConfiguration;
316 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
317 c->bMaxPower = config->bMaxPower ? : (CONFIG_USB_GADGET_VBUS_DRAW / 2);
319 /* There may be e.g. OTG descriptors */
320 if (config->descriptors) {
321 status = usb_descriptor_fillbuf(next, len,
322 config->descriptors);
329 /* add each function's descriptors */
330 list_for_each_entry(f, &config->functions, list) {
331 struct usb_descriptor_header **descriptors;
332 struct usb_descriptor_header *descriptor;
334 if (speed == USB_SPEED_HIGH)
335 descriptors = f->hs_descriptors;
337 descriptors = f->descriptors;
338 if (f->disabled || !descriptors || descriptors[0] == NULL)
340 status = usb_descriptor_fillbuf(next, len,
341 (const struct usb_descriptor_header **) descriptors);
345 /* set interface numbers dynamically */
347 while ((descriptor = *descriptors++) != NULL) {
348 intf = (struct usb_interface_descriptor *)dest;
349 if (intf->bDescriptorType == USB_DT_INTERFACE) {
350 /* don't increment bInterfaceNumber for alternate settings */
351 if (intf->bAlternateSetting == 0)
352 intf->bInterfaceNumber = interfaceCount++;
354 intf->bInterfaceNumber = interfaceCount - 1;
356 iad->bFirstInterface =
357 intf->bInterfaceNumber;
360 } else if (intf->bDescriptorType ==
361 USB_DT_INTERFACE_ASSOCIATION) {
362 /* This will be first if it exists. Save
363 * a pointer to it so we can properly set
364 * bFirstInterface when we process the first
367 iad = (struct usb_interface_assoc_descriptor *)
370 dest += intf->bLength;
378 c->wTotalLength = cpu_to_le16(len);
379 c->bNumInterfaces = interfaceCount;
383 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
385 struct usb_gadget *gadget = cdev->gadget;
386 struct usb_configuration *c;
387 u8 type = w_value >> 8;
388 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
390 if (gadget_is_dualspeed(gadget)) {
393 if (gadget->speed == USB_SPEED_HIGH)
395 if (type == USB_DT_OTHER_SPEED_CONFIG)
398 speed = USB_SPEED_HIGH;
402 /* This is a lookup by config *INDEX* */
404 list_for_each_entry(c, &cdev->configs, list) {
405 /* ignore configs that won't work at this speed */
406 if (speed == USB_SPEED_HIGH) {
414 return config_buf(c, speed, cdev->req->buf, type);
420 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
422 struct usb_gadget *gadget = cdev->gadget;
423 struct usb_configuration *c;
427 if (gadget_is_dualspeed(gadget)) {
428 if (gadget->speed == USB_SPEED_HIGH)
430 if (type == USB_DT_DEVICE_QUALIFIER)
433 list_for_each_entry(c, &cdev->configs, list) {
434 /* ignore configs that won't work at this speed */
447 static void device_qual(struct usb_composite_dev *cdev)
449 struct usb_qualifier_descriptor *qual = cdev->req->buf;
451 qual->bLength = sizeof(*qual);
452 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
453 /* POLICY: same bcdUSB and device type info at both speeds */
454 qual->bcdUSB = cdev->desc.bcdUSB;
455 qual->bDeviceClass = cdev->desc.bDeviceClass;
456 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
457 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
458 /* ASSUME same EP0 fifo size at both speeds */
459 qual->bMaxPacketSize0 = cdev->desc.bMaxPacketSize0;
460 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
464 /*-------------------------------------------------------------------------*/
466 static void reset_config(struct usb_composite_dev *cdev)
468 struct usb_function *f;
470 DBG(cdev, "reset config\n");
472 list_for_each_entry(f, &cdev->config->functions, list) {
476 bitmap_zero(f->endpoints, 32);
481 static int set_config(struct usb_composite_dev *cdev,
482 const struct usb_ctrlrequest *ctrl, unsigned number)
484 struct usb_gadget *gadget = cdev->gadget;
485 struct usb_configuration *c = NULL;
486 int result = -EINVAL;
487 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
494 list_for_each_entry(c, &cdev->configs, list) {
495 if (c->bConfigurationValue == number) {
505 INFO(cdev, "%s speed config #%d: %s\n",
507 switch (gadget->speed) {
508 case USB_SPEED_LOW: speed = "low"; break;
509 case USB_SPEED_FULL: speed = "full"; break;
510 case USB_SPEED_HIGH: speed = "high"; break;
511 default: speed = "?"; break;
512 } ; speed; }), number, c ? c->label : "unconfigured");
519 /* Initialize all interfaces by setting them to altsetting zero. */
520 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
521 struct usb_function *f = c->interface[tmp];
522 struct usb_descriptor_header **descriptors;
530 * Record which endpoints are used by the function. This is used
531 * to dispatch control requests targeted at that endpoint to the
532 * function's setup callback instead of the current
533 * configuration's setup callback.
535 if (gadget->speed == USB_SPEED_HIGH)
536 descriptors = f->hs_descriptors;
538 descriptors = f->descriptors;
540 for (; *descriptors; ++descriptors) {
541 struct usb_endpoint_descriptor *ep;
544 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
547 ep = (struct usb_endpoint_descriptor *)*descriptors;
548 addr = ((ep->bEndpointAddress & 0x80) >> 3)
549 | (ep->bEndpointAddress & 0x0f);
550 set_bit(addr, f->endpoints);
553 result = f->set_alt(f, tmp, 0);
555 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
556 tmp, f->name, f, result);
563 /* when we return, be sure our power usage is valid */
564 power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
566 usb_gadget_vbus_draw(gadget, power);
568 schedule_work(&cdev->switch_work);
573 * usb_add_config() - add a configuration to a device.
574 * @cdev: wraps the USB gadget
575 * @config: the configuration, with bConfigurationValue assigned
576 * Context: single threaded during gadget setup
578 * One of the main tasks of a composite driver's bind() routine is to
579 * add each of the configurations it supports, using this routine.
581 * This function returns the value of the configuration's bind(), which
582 * is zero for success else a negative errno value. Binding configurations
583 * assigns global resources including string IDs, and per-configuration
584 * resources such as interface IDs and endpoints.
586 int usb_add_config(struct usb_composite_dev *cdev,
587 struct usb_configuration *config)
589 int status = -EINVAL;
590 struct usb_configuration *c;
592 DBG(cdev, "adding config #%u '%s'/%p\n",
593 config->bConfigurationValue,
594 config->label, config);
596 if (!config->bConfigurationValue || !config->bind)
599 /* Prevent duplicate configuration identifiers */
600 list_for_each_entry(c, &cdev->configs, list) {
601 if (c->bConfigurationValue == config->bConfigurationValue) {
608 list_add_tail(&config->list, &cdev->configs);
610 INIT_LIST_HEAD(&config->functions);
611 config->next_interface_id = 0;
613 status = config->bind(config);
615 list_del(&config->list);
620 DBG(cdev, "cfg %d/%p speeds:%s%s\n",
621 config->bConfigurationValue, config,
622 config->highspeed ? " high" : "",
624 ? (gadget_is_dualspeed(cdev->gadget)
629 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
630 struct usb_function *f = config->interface[i];
634 DBG(cdev, " interface %d = %s/%p\n",
639 /* set_alt(), or next config->bind(), sets up
640 * ep->driver_data as needed.
642 usb_ep_autoconfig_reset(cdev->gadget);
646 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
647 config->bConfigurationValue, status);
651 /*-------------------------------------------------------------------------*/
653 /* We support strings in multiple languages ... string descriptor zero
654 * says which languages are supported. The typical case will be that
655 * only one language (probably English) is used, with I18N handled on
659 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
661 const struct usb_gadget_strings *s;
667 language = cpu_to_le16(s->language);
668 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
669 if (*tmp == language)
678 static int lookup_string(
679 struct usb_gadget_strings **sp,
685 struct usb_gadget_strings *s;
690 if (s->language != language)
692 value = usb_gadget_get_string(s, id, buf);
699 static int get_string(struct usb_composite_dev *cdev,
700 void *buf, u16 language, int id)
702 struct usb_configuration *c;
703 struct usb_function *f;
706 /* Yes, not only is USB's I18N support probably more than most
707 * folk will ever care about ... also, it's all supported here.
708 * (Except for UTF8 support for Unicode's "Astral Planes".)
711 /* 0 == report all available language codes */
713 struct usb_string_descriptor *s = buf;
714 struct usb_gadget_strings **sp;
717 s->bDescriptorType = USB_DT_STRING;
719 sp = composite->strings;
721 collect_langs(sp, s->wData);
723 list_for_each_entry(c, &cdev->configs, list) {
726 collect_langs(sp, s->wData);
728 list_for_each_entry(f, &c->functions, list) {
731 collect_langs(sp, s->wData);
735 for (len = 0; len <= 126 && s->wData[len]; len++)
740 s->bLength = 2 * (len + 1);
744 /* Otherwise, look up and return a specified string. String IDs
745 * are device-scoped, so we look up each string table we're told
746 * about. These lookups are infrequent; simpler-is-better here.
748 if (composite->strings) {
749 len = lookup_string(composite->strings, buf, language, id);
753 list_for_each_entry(c, &cdev->configs, list) {
755 len = lookup_string(c->strings, buf, language, id);
759 list_for_each_entry(f, &c->functions, list) {
762 len = lookup_string(f->strings, buf, language, id);
771 * usb_string_id() - allocate an unused string ID
772 * @cdev: the device whose string descriptor IDs are being allocated
773 * Context: single threaded during gadget setup
775 * @usb_string_id() is called from bind() callbacks to allocate
776 * string IDs. Drivers for functions, configurations, or gadgets will
777 * then store that ID in the appropriate descriptors and string table.
779 * All string identifier should be allocated using this,
780 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
781 * that for example different functions don't wrongly assign different
782 * meanings to the same identifier.
784 int usb_string_id(struct usb_composite_dev *cdev)
786 if (cdev->next_string_id < 254) {
787 /* string id 0 is reserved by USB spec for list of
788 * supported languages */
789 /* 255 reserved as well? -- mina86 */
790 cdev->next_string_id++;
791 return cdev->next_string_id;
797 * usb_string_ids() - allocate unused string IDs in batch
798 * @cdev: the device whose string descriptor IDs are being allocated
799 * @str: an array of usb_string objects to assign numbers to
800 * Context: single threaded during gadget setup
802 * @usb_string_ids() is called from bind() callbacks to allocate
803 * string IDs. Drivers for functions, configurations, or gadgets will
804 * then copy IDs from the string table to the appropriate descriptors
805 * and string table for other languages.
807 * All string identifier should be allocated using this,
808 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
809 * example different functions don't wrongly assign different meanings
810 * to the same identifier.
812 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
814 int next = cdev->next_string_id;
816 for (; str->s; ++str) {
817 if (unlikely(next >= 254))
822 cdev->next_string_id = next;
828 * usb_string_ids_n() - allocate unused string IDs in batch
829 * @c: the device whose string descriptor IDs are being allocated
830 * @n: number of string IDs to allocate
831 * Context: single threaded during gadget setup
833 * Returns the first requested ID. This ID and next @n-1 IDs are now
834 * valid IDs. At least provided that @n is non-zero because if it
835 * is, returns last requested ID which is now very useful information.
837 * @usb_string_ids_n() is called from bind() callbacks to allocate
838 * string IDs. Drivers for functions, configurations, or gadgets will
839 * then store that ID in the appropriate descriptors and string table.
841 * All string identifier should be allocated using this,
842 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
843 * example different functions don't wrongly assign different meanings
844 * to the same identifier.
846 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
848 unsigned next = c->next_string_id;
849 if (unlikely(n > 254 || (unsigned)next + n > 254))
851 c->next_string_id += n;
856 /*-------------------------------------------------------------------------*/
858 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
860 if (req->status || req->actual != req->length)
861 DBG((struct usb_composite_dev *) ep->driver_data,
862 "setup complete --> %d, %d/%d\n",
863 req->status, req->actual, req->length);
867 * The setup() callback implements all the ep0 functionality that's
868 * not handled lower down, in hardware or the hardware driver(like
869 * device and endpoint feature flags, and their status). It's all
870 * housekeeping for the gadget function we're implementing. Most of
871 * the work is in config and function specific setup.
874 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
876 struct usb_composite_dev *cdev = get_gadget_data(gadget);
877 struct usb_request *req = cdev->req;
878 int value = -EOPNOTSUPP;
879 u16 w_index = le16_to_cpu(ctrl->wIndex);
880 u8 intf = w_index & 0xFF;
881 u16 w_value = le16_to_cpu(ctrl->wValue);
882 u16 w_length = le16_to_cpu(ctrl->wLength);
883 struct usb_function *f = NULL;
887 spin_lock_irqsave(&cdev->lock, flags);
888 if (!cdev->connected) {
890 schedule_work(&cdev->switch_work);
892 spin_unlock_irqrestore(&cdev->lock, flags);
894 /* partial re-init of the response message; the function or the
895 * gadget might need to intercept e.g. a control-OUT completion
896 * when we delegate to it.
899 req->complete = composite_setup_complete;
900 req->length = USB_BUFSIZ;
901 gadget->ep0->driver_data = cdev;
903 switch (ctrl->bRequest) {
905 /* we handle all standard USB descriptors */
906 case USB_REQ_GET_DESCRIPTOR:
907 if (ctrl->bRequestType != USB_DIR_IN)
909 switch (w_value >> 8) {
912 cdev->desc.bNumConfigurations =
913 count_configs(cdev, USB_DT_DEVICE);
914 value = min(w_length, (u16) sizeof cdev->desc);
915 memcpy(req->buf, &cdev->desc, value);
917 case USB_DT_DEVICE_QUALIFIER:
918 if (!gadget_is_dualspeed(gadget))
921 value = min_t(int, w_length,
922 sizeof(struct usb_qualifier_descriptor));
924 case USB_DT_OTHER_SPEED_CONFIG:
925 if (!gadget_is_dualspeed(gadget))
929 value = config_desc(cdev, w_value);
931 value = min(w_length, (u16) value);
934 value = get_string(cdev, req->buf,
935 w_index, w_value & 0xff);
937 /* Allow functions to handle USB_DT_STRING.
938 * This is required for MTP.
941 struct usb_configuration *cfg;
942 list_for_each_entry(cfg, &cdev->configs, list) {
943 if (cfg && cfg->setup) {
944 value = cfg->setup(cfg, ctrl);
952 value = min(w_length, (u16) value);
957 /* any number of configs can work */
958 case USB_REQ_SET_CONFIGURATION:
959 if (ctrl->bRequestType != 0)
961 if (gadget_is_otg(gadget)) {
962 if (gadget->a_hnp_support)
963 DBG(cdev, "HNP available\n");
964 else if (gadget->a_alt_hnp_support)
965 DBG(cdev, "HNP on another port\n");
967 VDBG(cdev, "HNP inactive\n");
969 spin_lock(&cdev->lock);
970 value = set_config(cdev, ctrl, w_value);
971 spin_unlock(&cdev->lock);
973 case USB_REQ_GET_CONFIGURATION:
974 if (ctrl->bRequestType != USB_DIR_IN)
977 *(u8 *)req->buf = cdev->config->bConfigurationValue;
978 value = min(w_length, (u16) 1);
983 /* function drivers must handle get/set altsetting; if there's
984 * no get() method, we know only altsetting zero works.
986 case USB_REQ_SET_INTERFACE:
987 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
989 if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
991 f = cdev->config->interface[intf];
994 if (w_value && !f->set_alt)
996 value = f->set_alt(f, w_index, w_value);
998 case USB_REQ_GET_INTERFACE:
999 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1001 if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
1003 f = cdev->config->interface[intf];
1006 /* lots of interfaces only need altsetting zero... */
1007 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1010 *((u8 *)req->buf) = value;
1011 value = min(w_length, (u16) 1);
1016 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1017 ctrl->bRequestType, ctrl->bRequest,
1018 w_value, w_index, w_length);
1020 /* functions always handle their interfaces and endpoints...
1021 * punt other recipients (other, WUSB, ...) to the current
1022 * configuration code.
1024 * REVISIT it could make sense to let the composite device
1025 * take such requests too, if that's ever needed: to work
1028 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1029 case USB_RECIP_INTERFACE:
1031 f = cdev->config->interface[intf];
1034 case USB_RECIP_ENDPOINT:
1035 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1036 list_for_each_entry(f, &cdev->config->functions, list) {
1037 if (test_bit(endp, f->endpoints))
1040 if (&f->list == &cdev->config->functions)
1046 value = f->setup(f, ctrl);
1048 struct usb_configuration *c;
1052 value = c->setup(c, ctrl);
1055 /* If the vendor request is not processed (value < 0),
1056 * call all device registered configure setup callbacks
1058 * This is used to handle the following cases:
1059 * - vendor request is for the device and arrives before
1061 * - Some devices are required to handle vendor request before
1062 * setconfiguration such as MTP, USBNET.
1066 struct usb_configuration *cfg;
1068 list_for_each_entry(cfg, &cdev->configs, list) {
1069 if (cfg && cfg->setup)
1070 value = cfg->setup(cfg, ctrl);
1077 /* respond with data transfer before status phase? */
1079 req->length = value;
1080 req->zero = value < w_length;
1081 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1083 DBG(cdev, "ep_queue --> %d\n", value);
1085 composite_setup_complete(gadget->ep0, req);
1090 /* device either stalls (value < 0) or reports success */
1094 static void composite_disconnect(struct usb_gadget *gadget)
1096 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1097 unsigned long flags;
1099 /* REVISIT: should we have config and device level
1100 * disconnect callbacks?
1102 spin_lock_irqsave(&cdev->lock, flags);
1106 if (composite->disconnect)
1107 composite->disconnect(cdev);
1109 cdev->connected = 0;
1110 schedule_work(&cdev->switch_work);
1111 spin_unlock_irqrestore(&cdev->lock, flags);
1114 /*-------------------------------------------------------------------------*/
1116 static ssize_t composite_show_suspended(struct device *dev,
1117 struct device_attribute *attr,
1120 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1121 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1123 return sprintf(buf, "%d\n", cdev->suspended);
1126 static DEVICE_ATTR(suspended, 0444, composite_show_suspended, NULL);
1129 composite_unbind(struct usb_gadget *gadget)
1131 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1133 /* composite_disconnect() must already have been called
1134 * by the underlying peripheral controller driver!
1135 * so there's no i/o concurrency that could affect the
1136 * state protected by cdev->lock.
1138 WARN_ON(cdev->config);
1140 while (!list_empty(&cdev->configs)) {
1141 struct usb_configuration *c;
1143 c = list_first_entry(&cdev->configs,
1144 struct usb_configuration, list);
1145 while (!list_empty(&c->functions)) {
1146 struct usb_function *f;
1148 f = list_first_entry(&c->functions,
1149 struct usb_function, list);
1152 DBG(cdev, "unbind function '%s'/%p\n",
1155 /* may free memory for "f" */
1160 DBG(cdev, "unbind config '%s'/%p\n", c->label, c);
1162 /* may free memory for "c" */
1165 if (composite->unbind)
1166 composite->unbind(cdev);
1169 kfree(cdev->req->buf);
1170 usb_ep_free_request(gadget->ep0, cdev->req);
1173 switch_dev_unregister(&cdev->sw_connected);
1174 switch_dev_unregister(&cdev->sw_config);
1176 set_gadget_data(gadget, NULL);
1177 device_remove_file(&gadget->dev, &dev_attr_suspended);
1182 string_override_one(struct usb_gadget_strings *tab, u8 id, const char *s)
1184 struct usb_string *str = tab->strings;
1186 for (str = tab->strings; str->s; str++) {
1187 if (str->id == id) {
1195 string_override(struct usb_gadget_strings **tab, u8 id, const char *s)
1198 string_override_one(*tab, id, s);
1204 composite_switch_work(struct work_struct *data)
1206 struct usb_composite_dev *cdev =
1207 container_of(data, struct usb_composite_dev, switch_work);
1208 struct usb_configuration *config = cdev->config;
1210 unsigned long flags;
1212 spin_lock_irqsave(&cdev->lock, flags);
1213 if (cdev->connected != cdev->sw_connected.state) {
1214 connected = cdev->connected;
1215 spin_unlock_irqrestore(&cdev->lock, flags);
1216 switch_set_state(&cdev->sw_connected, connected);
1218 spin_unlock_irqrestore(&cdev->lock, flags);
1222 switch_set_state(&cdev->sw_config, config->bConfigurationValue);
1224 switch_set_state(&cdev->sw_config, 0);
1227 static int composite_bind(struct usb_gadget *gadget)
1229 struct usb_composite_dev *cdev;
1230 int status = -ENOMEM;
1232 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
1236 spin_lock_init(&cdev->lock);
1237 cdev->gadget = gadget;
1238 set_gadget_data(gadget, cdev);
1239 INIT_LIST_HEAD(&cdev->configs);
1241 /* preallocate control response and buffer */
1242 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1245 cdev->req->buf = kmalloc(USB_BUFSIZ, GFP_KERNEL);
1246 if (!cdev->req->buf)
1248 cdev->req->complete = composite_setup_complete;
1249 gadget->ep0->driver_data = cdev;
1251 cdev->bufsiz = USB_BUFSIZ;
1252 cdev->driver = composite;
1254 usb_gadget_set_selfpowered(gadget);
1256 /* interface and string IDs start at zero via kzalloc.
1257 * we force endpoints to start unassigned; few controller
1258 * drivers will zero ep->driver_data.
1260 usb_ep_autoconfig_reset(cdev->gadget);
1262 /* composite gadget needs to assign strings for whole device (like
1263 * serial number), register function drivers, potentially update
1264 * power state and consumption, etc
1266 status = composite->bind(cdev);
1270 cdev->sw_connected.name = "usb_connected";
1271 status = switch_dev_register(&cdev->sw_connected);
1274 cdev->sw_config.name = "usb_configuration";
1275 status = switch_dev_register(&cdev->sw_config);
1278 INIT_WORK(&cdev->switch_work, composite_switch_work);
1280 cdev->desc = *composite->dev;
1281 cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1283 /* standardized runtime overrides for device ID data */
1285 cdev->desc.idVendor = cpu_to_le16(idVendor);
1287 cdev->desc.idProduct = cpu_to_le16(idProduct);
1289 cdev->desc.bcdDevice = cpu_to_le16(bcdDevice);
1291 /* strings can't be assigned before bind() allocates the
1292 * releavnt identifiers
1294 if (cdev->desc.iManufacturer && iManufacturer)
1295 string_override(composite->strings,
1296 cdev->desc.iManufacturer, iManufacturer);
1297 if (cdev->desc.iProduct && iProduct)
1298 string_override(composite->strings,
1299 cdev->desc.iProduct, iProduct);
1300 if (cdev->desc.iSerialNumber && iSerialNumber)
1301 string_override(composite->strings,
1302 cdev->desc.iSerialNumber, iSerialNumber);
1304 status = device_create_file(&gadget->dev, &dev_attr_suspended);
1308 INFO(cdev, "%s ready\n", composite->name);
1312 composite_unbind(gadget);
1316 /*-------------------------------------------------------------------------*/
1319 composite_suspend(struct usb_gadget *gadget)
1321 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1322 struct usb_function *f;
1324 /* REVISIT: should we have config level
1325 * suspend/resume callbacks?
1327 DBG(cdev, "suspend\n");
1329 list_for_each_entry(f, &cdev->config->functions, list) {
1334 if (composite->suspend)
1335 composite->suspend(cdev);
1337 cdev->suspended = 1;
1341 composite_resume(struct usb_gadget *gadget)
1343 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1344 struct usb_function *f;
1346 /* REVISIT: should we have config level
1347 * suspend/resume callbacks?
1349 DBG(cdev, "resume\n");
1350 if (composite->resume)
1351 composite->resume(cdev);
1353 list_for_each_entry(f, &cdev->config->functions, list) {
1359 cdev->suspended = 0;
1363 composite_uevent(struct device *dev, struct kobj_uevent_env *env)
1365 struct usb_function *f = dev_get_drvdata(dev);
1368 /* this happens when the device is first created */
1372 if (add_uevent_var(env, "FUNCTION=%s", f->name))
1374 if (add_uevent_var(env, "ENABLED=%d", !f->disabled))
1379 /*-------------------------------------------------------------------------*/
1381 static struct usb_gadget_driver composite_driver = {
1382 .speed = USB_SPEED_HIGH,
1384 .bind = composite_bind,
1385 .unbind = composite_unbind,
1387 .setup = composite_setup,
1388 .disconnect = composite_disconnect,
1390 .suspend = composite_suspend,
1391 .resume = composite_resume,
1394 .owner = THIS_MODULE,
1399 * usb_composite_register() - register a composite driver
1400 * @driver: the driver to register
1401 * Context: single threaded during gadget setup
1403 * This function is used to register drivers using the composite driver
1404 * framework. The return value is zero, or a negative errno value.
1405 * Those values normally come from the driver's @bind method, which does
1406 * all the work of setting up the driver to match the hardware.
1408 * On successful return, the gadget is ready to respond to requests from
1409 * the host, unless one of its components invokes usb_gadget_disconnect()
1410 * while it was binding. That would usually be done in order to wait for
1411 * some userspace participation.
1413 int usb_composite_register(struct usb_composite_driver *driver)
1415 if (!driver || !driver->dev || !driver->bind || composite)
1419 driver->name = "composite";
1420 composite_driver.function = (char *) driver->name;
1421 composite_driver.driver.name = driver->name;
1424 driver->class = class_create(THIS_MODULE, "usb_composite");
1425 if (IS_ERR(driver->class))
1426 return PTR_ERR(driver->class);
1427 driver->class->dev_uevent = composite_uevent;
1429 return usb_gadget_register_driver(&composite_driver);
1433 * usb_composite_unregister() - unregister a composite driver
1434 * @driver: the driver to unregister
1436 * This function is used to unregister drivers using the composite
1439 void usb_composite_unregister(struct usb_composite_driver *driver)
1441 if (composite != driver)
1443 usb_gadget_unregister_driver(&composite_driver);