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>
27 #include <linux/utsname.h>
29 #include <linux/usb/composite.h>
33 * The code in this file is utility code, used to build a gadget driver
34 * from one or more "function" drivers, one or more "configuration"
35 * objects, and a "usb_composite_driver" by gluing them together along
36 * with the relevant device-wide data.
39 /* big enough to hold our biggest descriptor */
40 #define USB_BUFSIZ 1024
42 static struct usb_composite_driver *composite;
43 static int (*composite_gadget_bind)(struct usb_composite_dev *cdev);
45 /* Some systems will need runtime overrides for the product identifiers
46 * published in the device descriptor, either numbers or strings or both.
47 * String parameters are in UTF-8 (superset of ASCII's 7 bit characters).
50 static ushort idVendor;
51 module_param(idVendor, ushort, 0);
52 MODULE_PARM_DESC(idVendor, "USB Vendor ID");
54 static ushort idProduct;
55 module_param(idProduct, ushort, 0);
56 MODULE_PARM_DESC(idProduct, "USB Product ID");
58 static ushort bcdDevice;
59 module_param(bcdDevice, ushort, 0);
60 MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
62 static char *iManufacturer;
63 module_param(iManufacturer, charp, 0);
64 MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
66 static char *iProduct;
67 module_param(iProduct, charp, 0);
68 MODULE_PARM_DESC(iProduct, "USB Product string");
70 static char *iSerialNumber;
71 module_param(iSerialNumber, charp, 0);
72 MODULE_PARM_DESC(iSerialNumber, "SerialNumber string");
74 static char composite_manufacturer[50];
76 /*-------------------------------------------------------------------------*/
78 static ssize_t enable_show(struct device *dev, struct device_attribute *attr,
81 struct usb_function *f = dev_get_drvdata(dev);
82 return sprintf(buf, "%d\n", !f->disabled);
85 static ssize_t enable_store(
86 struct device *dev, struct device_attribute *attr,
87 const char *buf, size_t size)
89 struct usb_function *f = dev_get_drvdata(dev);
90 struct usb_composite_driver *driver = f->config->cdev->driver;
93 sscanf(buf, "%d", &value);
94 if (driver->enable_function)
95 driver->enable_function(f, value);
97 usb_function_set_enabled(f, value);
102 static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
104 void usb_function_set_enabled(struct usb_function *f, int enabled)
106 f->disabled = !enabled;
107 kobject_uevent(&f->dev->kobj, KOBJ_CHANGE);
111 * usb_add_function() - add a function to a configuration
112 * @config: the configuration
113 * @function: the function being added
114 * Context: single threaded during gadget setup
116 * After initialization, each configuration must have one or more
117 * functions added to it. Adding a function involves calling its @bind()
118 * method to allocate resources such as interface and string identifiers
121 * This function returns the value of the function's bind(), which is
122 * zero for success else a negative errno value.
124 int usb_add_function(struct usb_configuration *config,
125 struct usb_function *function)
127 struct usb_composite_dev *cdev = config->cdev;
131 DBG(cdev, "adding '%s'/%p to config '%s'/%p\n",
132 function->name, function,
133 config->label, config);
135 if (!function->set_alt || !function->disable)
138 index = atomic_inc_return(&cdev->driver->function_count);
139 function->dev = device_create(cdev->driver->class, NULL,
140 MKDEV(0, index), NULL, function->name);
141 if (IS_ERR(function->dev))
142 return PTR_ERR(function->dev);
144 value = device_create_file(function->dev, &dev_attr_enable);
146 device_destroy(cdev->driver->class, MKDEV(0, index));
149 dev_set_drvdata(function->dev, function);
151 function->config = config;
152 list_add_tail(&function->list, &config->functions);
154 /* REVISIT *require* function->bind? */
155 if (function->bind) {
156 value = function->bind(config, function);
158 list_del(&function->list);
159 function->config = NULL;
164 /* We allow configurations that don't work at both speeds.
165 * If we run into a lowspeed Linux system, treat it the same
166 * as full speed ... it's the function drivers that will need
167 * to avoid bulk and ISO transfers.
169 if (!config->fullspeed && function->descriptors)
170 config->fullspeed = true;
171 if (!config->highspeed && function->hs_descriptors)
172 config->highspeed = true;
176 DBG(cdev, "adding '%s'/%p --> %d\n",
177 function->name, function, value);
182 * usb_function_deactivate - prevent function and gadget enumeration
183 * @function: the function that isn't yet ready to respond
185 * Blocks response of the gadget driver to host enumeration by
186 * preventing the data line pullup from being activated. This is
187 * normally called during @bind() processing to change from the
188 * initial "ready to respond" state, or when a required resource
191 * For example, drivers that serve as a passthrough to a userspace
192 * daemon can block enumeration unless that daemon (such as an OBEX,
193 * MTP, or print server) is ready to handle host requests.
195 * Not all systems support software control of their USB peripheral
198 * Returns zero on success, else negative errno.
200 int usb_function_deactivate(struct usb_function *function)
202 struct usb_composite_dev *cdev = function->config->cdev;
206 spin_lock_irqsave(&cdev->lock, flags);
208 if (cdev->deactivations == 0)
209 status = usb_gadget_disconnect(cdev->gadget);
211 cdev->deactivations++;
213 spin_unlock_irqrestore(&cdev->lock, flags);
218 * usb_function_activate - allow function and gadget enumeration
219 * @function: function on which usb_function_activate() was called
221 * Reverses effect of usb_function_deactivate(). If no more functions
222 * are delaying their activation, the gadget driver will respond to
223 * host enumeration procedures.
225 * Returns zero on success, else negative errno.
227 int usb_function_activate(struct usb_function *function)
229 struct usb_composite_dev *cdev = function->config->cdev;
232 spin_lock(&cdev->lock);
234 if (WARN_ON(cdev->deactivations == 0))
237 cdev->deactivations--;
238 if (cdev->deactivations == 0)
239 status = usb_gadget_connect(cdev->gadget);
242 spin_unlock(&cdev->lock);
247 * usb_interface_id() - allocate an unused interface ID
248 * @config: configuration associated with the interface
249 * @function: function handling the interface
250 * Context: single threaded during gadget setup
252 * usb_interface_id() is called from usb_function.bind() callbacks to
253 * allocate new interface IDs. The function driver will then store that
254 * ID in interface, association, CDC union, and other descriptors. It
255 * will also handle any control requests targeted at that interface,
256 * particularly changing its altsetting via set_alt(). There may
257 * also be class-specific or vendor-specific requests to handle.
259 * All interface identifier should be allocated using this routine, to
260 * ensure that for example different functions don't wrongly assign
261 * different meanings to the same identifier. Note that since interface
262 * identifiers are configuration-specific, functions used in more than
263 * one configuration (or more than once in a given configuration) need
264 * multiple versions of the relevant descriptors.
266 * Returns the interface ID which was allocated; or -ENODEV if no
267 * more interface IDs can be allocated.
269 int usb_interface_id(struct usb_configuration *config,
270 struct usb_function *function)
272 unsigned id = config->next_interface_id;
274 if (id < MAX_CONFIG_INTERFACES) {
275 config->interface[id] = function;
276 config->next_interface_id = id + 1;
282 static int config_buf(struct usb_configuration *config,
283 enum usb_device_speed speed, void *buf, u8 type)
285 struct usb_config_descriptor *c = buf;
286 struct usb_interface_descriptor *intf;
287 void *next = buf + USB_DT_CONFIG_SIZE;
288 int len = USB_BUFSIZ - USB_DT_CONFIG_SIZE;
289 struct usb_function *f;
291 int interfaceCount = 0;
294 /* write the config descriptor */
296 c->bLength = USB_DT_CONFIG_SIZE;
297 c->bDescriptorType = type;
298 /* wTotalLength and bNumInterfaces are written later */
299 c->bConfigurationValue = config->bConfigurationValue;
300 c->iConfiguration = config->iConfiguration;
301 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
302 c->bMaxPower = config->bMaxPower ? : (CONFIG_USB_GADGET_VBUS_DRAW / 2);
304 /* There may be e.g. OTG descriptors */
305 if (config->descriptors) {
306 status = usb_descriptor_fillbuf(next, len,
307 config->descriptors);
314 /* add each function's descriptors */
315 list_for_each_entry(f, &config->functions, list) {
316 struct usb_descriptor_header **descriptors;
317 struct usb_descriptor_header *descriptor;
319 if (speed == USB_SPEED_HIGH)
320 descriptors = f->hs_descriptors;
322 descriptors = f->descriptors;
323 if (f->disabled || !descriptors || descriptors[0] == NULL)
325 status = usb_descriptor_fillbuf(next, len,
326 (const struct usb_descriptor_header **) descriptors);
330 /* set interface numbers dynamically */
332 while ((descriptor = *descriptors++) != NULL) {
333 intf = (struct usb_interface_descriptor *)dest;
334 if (intf->bDescriptorType == USB_DT_INTERFACE) {
335 /* don't increment bInterfaceNumber for alternate settings */
336 if (intf->bAlternateSetting == 0)
337 intf->bInterfaceNumber = interfaceCount++;
339 intf->bInterfaceNumber = interfaceCount - 1;
341 dest += intf->bLength;
349 c->wTotalLength = cpu_to_le16(len);
350 c->bNumInterfaces = interfaceCount;
354 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
356 struct usb_gadget *gadget = cdev->gadget;
357 struct usb_configuration *c;
358 u8 type = w_value >> 8;
359 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
361 if (gadget_is_dualspeed(gadget)) {
364 if (gadget->speed == USB_SPEED_HIGH)
366 if (type == USB_DT_OTHER_SPEED_CONFIG)
369 speed = USB_SPEED_HIGH;
373 /* This is a lookup by config *INDEX* */
375 list_for_each_entry(c, &cdev->configs, list) {
376 /* ignore configs that won't work at this speed */
377 if (speed == USB_SPEED_HIGH) {
385 return config_buf(c, speed, cdev->req->buf, type);
391 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
393 struct usb_gadget *gadget = cdev->gadget;
394 struct usb_configuration *c;
398 if (gadget_is_dualspeed(gadget)) {
399 if (gadget->speed == USB_SPEED_HIGH)
401 if (type == USB_DT_DEVICE_QUALIFIER)
404 list_for_each_entry(c, &cdev->configs, list) {
405 /* ignore configs that won't work at this speed */
418 static void device_qual(struct usb_composite_dev *cdev)
420 struct usb_qualifier_descriptor *qual = cdev->req->buf;
422 qual->bLength = sizeof(*qual);
423 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
424 /* POLICY: same bcdUSB and device type info at both speeds */
425 qual->bcdUSB = cdev->desc.bcdUSB;
426 qual->bDeviceClass = cdev->desc.bDeviceClass;
427 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
428 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
429 /* ASSUME same EP0 fifo size at both speeds */
430 qual->bMaxPacketSize0 = cdev->desc.bMaxPacketSize0;
431 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
435 /*-------------------------------------------------------------------------*/
437 static void reset_config(struct usb_composite_dev *cdev)
439 struct usb_function *f;
441 DBG(cdev, "reset config\n");
443 list_for_each_entry(f, &cdev->config->functions, list) {
447 bitmap_zero(f->endpoints, 32);
452 static int set_config(struct usb_composite_dev *cdev,
453 const struct usb_ctrlrequest *ctrl, unsigned number)
455 struct usb_gadget *gadget = cdev->gadget;
456 struct usb_configuration *c = NULL;
457 int result = -EINVAL;
458 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
465 list_for_each_entry(c, &cdev->configs, list) {
466 if (c->bConfigurationValue == number) {
476 INFO(cdev, "%s speed config #%d: %s\n",
478 switch (gadget->speed) {
479 case USB_SPEED_LOW: speed = "low"; break;
480 case USB_SPEED_FULL: speed = "full"; break;
481 case USB_SPEED_HIGH: speed = "high"; break;
482 default: speed = "?"; break;
483 } ; speed; }), number, c ? c->label : "unconfigured");
490 /* Initialize all interfaces by setting them to altsetting zero. */
491 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
492 struct usb_function *f = c->interface[tmp];
493 struct usb_descriptor_header **descriptors;
501 * Record which endpoints are used by the function. This is used
502 * to dispatch control requests targeted at that endpoint to the
503 * function's setup callback instead of the current
504 * configuration's setup callback.
506 if (gadget->speed == USB_SPEED_HIGH)
507 descriptors = f->hs_descriptors;
509 descriptors = f->descriptors;
511 for (; *descriptors; ++descriptors) {
512 struct usb_endpoint_descriptor *ep;
515 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
518 ep = (struct usb_endpoint_descriptor *)*descriptors;
519 addr = ((ep->bEndpointAddress & 0x80) >> 3)
520 | (ep->bEndpointAddress & 0x0f);
521 set_bit(addr, f->endpoints);
524 result = f->set_alt(f, tmp, 0);
526 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
527 tmp, f->name, f, result);
533 if (result == USB_GADGET_DELAYED_STATUS) {
535 "%s: interface %d (%s) requested delayed status\n",
536 __func__, tmp, f->name);
537 cdev->delayed_status++;
538 DBG(cdev, "delayed_status count %d\n",
539 cdev->delayed_status);
543 /* when we return, be sure our power usage is valid */
544 power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
546 usb_gadget_vbus_draw(gadget, power);
548 switch_set_state(&cdev->sdev, number);
550 if (result >= 0 && cdev->delayed_status)
551 result = USB_GADGET_DELAYED_STATUS;
556 * usb_add_config() - add a configuration to a device.
557 * @cdev: wraps the USB gadget
558 * @config: the configuration, with bConfigurationValue assigned
559 * @bind: the configuration's bind function
560 * Context: single threaded during gadget setup
562 * One of the main tasks of a composite @bind() routine is to
563 * add each of the configurations it supports, using this routine.
565 * This function returns the value of the configuration's @bind(), which
566 * is zero for success else a negative errno value. Binding configurations
567 * assigns global resources including string IDs, and per-configuration
568 * resources such as interface IDs and endpoints.
570 int usb_add_config(struct usb_composite_dev *cdev,
571 struct usb_configuration *config,
572 int (*bind)(struct usb_configuration *))
574 int status = -EINVAL;
575 struct usb_configuration *c;
577 DBG(cdev, "adding config #%u '%s'/%p\n",
578 config->bConfigurationValue,
579 config->label, config);
581 if (!config->bConfigurationValue || !bind)
584 /* Prevent duplicate configuration identifiers */
585 list_for_each_entry(c, &cdev->configs, list) {
586 if (c->bConfigurationValue == config->bConfigurationValue) {
593 list_add_tail(&config->list, &cdev->configs);
595 INIT_LIST_HEAD(&config->functions);
596 config->next_interface_id = 0;
598 status = bind(config);
600 list_del(&config->list);
605 DBG(cdev, "cfg %d/%p speeds:%s%s\n",
606 config->bConfigurationValue, config,
607 config->highspeed ? " high" : "",
609 ? (gadget_is_dualspeed(cdev->gadget)
614 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
615 struct usb_function *f = config->interface[i];
619 DBG(cdev, " interface %d = %s/%p\n",
624 /* set_alt(), or next bind(), sets up
625 * ep->driver_data as needed.
627 usb_ep_autoconfig_reset(cdev->gadget);
631 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
632 config->bConfigurationValue, status);
636 /*-------------------------------------------------------------------------*/
638 /* We support strings in multiple languages ... string descriptor zero
639 * says which languages are supported. The typical case will be that
640 * only one language (probably English) is used, with I18N handled on
644 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
646 const struct usb_gadget_strings *s;
652 language = cpu_to_le16(s->language);
653 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
654 if (*tmp == language)
663 static int lookup_string(
664 struct usb_gadget_strings **sp,
670 struct usb_gadget_strings *s;
675 if (s->language != language)
677 value = usb_gadget_get_string(s, id, buf);
684 static int get_string(struct usb_composite_dev *cdev,
685 void *buf, u16 language, int id)
687 struct usb_configuration *c;
688 struct usb_function *f;
692 /* Yes, not only is USB's I18N support probably more than most
693 * folk will ever care about ... also, it's all supported here.
694 * (Except for UTF8 support for Unicode's "Astral Planes".)
697 /* 0 == report all available language codes */
699 struct usb_string_descriptor *s = buf;
700 struct usb_gadget_strings **sp;
703 s->bDescriptorType = USB_DT_STRING;
705 sp = composite->strings;
707 collect_langs(sp, s->wData);
709 list_for_each_entry(c, &cdev->configs, list) {
712 collect_langs(sp, s->wData);
714 list_for_each_entry(f, &c->functions, list) {
717 collect_langs(sp, s->wData);
721 for (len = 0; len <= 126 && s->wData[len]; len++)
726 s->bLength = 2 * (len + 1);
730 /* Otherwise, look up and return a specified string. First
731 * check if the string has not been overridden.
733 if (cdev->manufacturer_override == id)
734 str = iManufacturer ?: composite->iManufacturer ?:
735 composite_manufacturer;
736 else if (cdev->product_override == id)
737 str = iProduct ?: composite->iProduct;
738 else if (cdev->serial_override == id)
743 struct usb_gadget_strings strings = {
744 .language = language,
745 .strings = &(struct usb_string) { 0xff, str }
747 return usb_gadget_get_string(&strings, 0xff, buf);
750 /* String IDs are device-scoped, so we look up each string
751 * table we're told about. These lookups are infrequent;
752 * simpler-is-better here.
754 if (composite->strings) {
755 len = lookup_string(composite->strings, buf, language, id);
759 list_for_each_entry(c, &cdev->configs, list) {
761 len = lookup_string(c->strings, buf, language, id);
765 list_for_each_entry(f, &c->functions, list) {
768 len = lookup_string(f->strings, buf, language, id);
777 * usb_string_id() - allocate an unused string ID
778 * @cdev: the device whose string descriptor IDs are being allocated
779 * Context: single threaded during gadget setup
781 * @usb_string_id() is called from bind() callbacks to allocate
782 * string IDs. Drivers for functions, configurations, or gadgets will
783 * then store that ID in the appropriate descriptors and string table.
785 * All string identifier should be allocated using this,
786 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
787 * that for example different functions don't wrongly assign different
788 * meanings to the same identifier.
790 int usb_string_id(struct usb_composite_dev *cdev)
792 if (cdev->next_string_id < 254) {
793 /* string id 0 is reserved by USB spec for list of
794 * supported languages */
795 /* 255 reserved as well? -- mina86 */
796 cdev->next_string_id++;
797 return cdev->next_string_id;
803 * usb_string_ids() - allocate unused string IDs in batch
804 * @cdev: the device whose string descriptor IDs are being allocated
805 * @str: an array of usb_string objects to assign numbers to
806 * Context: single threaded during gadget setup
808 * @usb_string_ids() is called from bind() callbacks to allocate
809 * string IDs. Drivers for functions, configurations, or gadgets will
810 * then copy IDs from the string table to the appropriate descriptors
811 * and string table for other languages.
813 * All string identifier should be allocated using this,
814 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
815 * example different functions don't wrongly assign different meanings
816 * to the same identifier.
818 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
820 int next = cdev->next_string_id;
822 for (; str->s; ++str) {
823 if (unlikely(next >= 254))
828 cdev->next_string_id = next;
834 * usb_string_ids_n() - allocate unused string IDs in batch
835 * @c: the device whose string descriptor IDs are being allocated
836 * @n: number of string IDs to allocate
837 * Context: single threaded during gadget setup
839 * Returns the first requested ID. This ID and next @n-1 IDs are now
840 * valid IDs. At least provided that @n is non-zero because if it
841 * is, returns last requested ID which is now very useful information.
843 * @usb_string_ids_n() is called from bind() callbacks to allocate
844 * string IDs. Drivers for functions, configurations, or gadgets will
845 * then store that ID in the appropriate descriptors and string table.
847 * All string identifier should be allocated using this,
848 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
849 * example different functions don't wrongly assign different meanings
850 * to the same identifier.
852 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
854 unsigned next = c->next_string_id;
855 if (unlikely(n > 254 || (unsigned)next + n > 254))
857 c->next_string_id += n;
862 /*-------------------------------------------------------------------------*/
864 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
866 if (req->status || req->actual != req->length)
867 DBG((struct usb_composite_dev *) ep->driver_data,
868 "setup complete --> %d, %d/%d\n",
869 req->status, req->actual, req->length);
873 * The setup() callback implements all the ep0 functionality that's
874 * not handled lower down, in hardware or the hardware driver(like
875 * device and endpoint feature flags, and their status). It's all
876 * housekeeping for the gadget function we're implementing. Most of
877 * the work is in config and function specific setup.
880 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
882 struct usb_composite_dev *cdev = get_gadget_data(gadget);
883 struct usb_request *req = cdev->req;
884 int value = -EOPNOTSUPP;
885 u16 w_index = le16_to_cpu(ctrl->wIndex);
886 u8 intf = w_index & 0xFF;
887 u16 w_value = le16_to_cpu(ctrl->wValue);
888 u16 w_length = le16_to_cpu(ctrl->wLength);
889 struct usb_function *f = NULL;
892 /* partial re-init of the response message; the function or the
893 * gadget might need to intercept e.g. a control-OUT completion
894 * when we delegate to it.
897 req->complete = composite_setup_complete;
899 gadget->ep0->driver_data = cdev;
901 switch (ctrl->bRequest) {
903 /* we handle all standard USB descriptors */
904 case USB_REQ_GET_DESCRIPTOR:
905 if (ctrl->bRequestType != USB_DIR_IN)
907 switch (w_value >> 8) {
910 cdev->desc.bNumConfigurations =
911 count_configs(cdev, USB_DT_DEVICE);
912 value = min(w_length, (u16) sizeof cdev->desc);
913 memcpy(req->buf, &cdev->desc, value);
915 case USB_DT_DEVICE_QUALIFIER:
916 if (!gadget_is_dualspeed(gadget))
919 value = min_t(int, w_length,
920 sizeof(struct usb_qualifier_descriptor));
922 case USB_DT_OTHER_SPEED_CONFIG:
923 if (!gadget_is_dualspeed(gadget))
927 value = config_desc(cdev, w_value);
929 value = min(w_length, (u16) value);
932 value = get_string(cdev, req->buf,
933 w_index, w_value & 0xff);
935 value = min(w_length, (u16) value);
940 /* any number of configs can work */
941 case USB_REQ_SET_CONFIGURATION:
942 if (ctrl->bRequestType != 0)
944 if (gadget_is_otg(gadget)) {
945 if (gadget->a_hnp_support)
946 DBG(cdev, "HNP available\n");
947 else if (gadget->a_alt_hnp_support)
948 DBG(cdev, "HNP on another port\n");
950 VDBG(cdev, "HNP inactive\n");
952 spin_lock(&cdev->lock);
953 value = set_config(cdev, ctrl, w_value);
954 spin_unlock(&cdev->lock);
956 case USB_REQ_GET_CONFIGURATION:
957 if (ctrl->bRequestType != USB_DIR_IN)
960 *(u8 *)req->buf = cdev->config->bConfigurationValue;
961 value = min(w_length, (u16) 1);
967 /* function drivers must handle get/set altsetting; if there's
968 * no get() method, we know only altsetting zero works.
970 case USB_REQ_SET_INTERFACE:
971 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
973 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
975 f = cdev->config->interface[intf];
978 if (w_value && !f->set_alt)
980 value = f->set_alt(f, w_index, w_value);
981 if (value == USB_GADGET_DELAYED_STATUS) {
983 "%s: interface %d (%s) requested delayed status\n",
984 __func__, intf, f->name);
985 cdev->delayed_status++;
986 DBG(cdev, "delayed_status count %d\n",
987 cdev->delayed_status);
990 case USB_REQ_GET_INTERFACE:
991 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
993 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
995 f = cdev->config->interface[intf];
998 /* lots of interfaces only need altsetting zero... */
999 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1002 *((u8 *)req->buf) = value;
1003 value = min(w_length, (u16) 1);
1008 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1009 ctrl->bRequestType, ctrl->bRequest,
1010 w_value, w_index, w_length);
1012 /* functions always handle their interfaces and endpoints...
1013 * punt other recipients (other, WUSB, ...) to the current
1014 * configuration code.
1016 * REVISIT it could make sense to let the composite device
1017 * take such requests too, if that's ever needed: to work
1020 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1021 case USB_RECIP_INTERFACE:
1022 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1024 f = cdev->config->interface[intf];
1027 case USB_RECIP_ENDPOINT:
1028 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1029 list_for_each_entry(f, &cdev->config->functions, list) {
1030 if (test_bit(endp, f->endpoints))
1033 if (&f->list == &cdev->config->functions)
1039 value = f->setup(f, ctrl);
1041 struct usb_configuration *c;
1045 value = c->setup(c, ctrl);
1048 /* If the vendor request is not processed (value < 0),
1049 * call all device registered configure setup callbacks
1051 * This is used to handle the following cases:
1052 * - vendor request is for the device and arrives before
1054 * - Some devices are required to handle vendor request before
1055 * setconfiguration such as MTP, USBNET.
1059 struct usb_configuration *cfg;
1061 list_for_each_entry(cfg, &cdev->configs, list) {
1062 if (cfg && cfg->setup)
1063 value = cfg->setup(cfg, ctrl);
1070 /* respond with data transfer before status phase? */
1071 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1072 req->length = value;
1073 req->zero = value < w_length;
1074 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1076 DBG(cdev, "ep_queue --> %d\n", value);
1078 composite_setup_complete(gadget->ep0, req);
1080 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1082 "%s: Delayed status not supported for w_length != 0",
1087 /* device either stalls (value < 0) or reports success */
1091 static void composite_disconnect(struct usb_gadget *gadget)
1093 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1094 unsigned long flags;
1096 /* REVISIT: should we have config and device level
1097 * disconnect callbacks?
1099 spin_lock_irqsave(&cdev->lock, flags);
1102 if (composite->disconnect)
1103 composite->disconnect(cdev);
1104 spin_unlock_irqrestore(&cdev->lock, flags);
1106 switch_set_state(&cdev->sdev, 0);
1109 /*-------------------------------------------------------------------------*/
1111 static ssize_t composite_show_suspended(struct device *dev,
1112 struct device_attribute *attr,
1115 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1116 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1118 return sprintf(buf, "%d\n", cdev->suspended);
1121 static DEVICE_ATTR(suspended, 0444, composite_show_suspended, NULL);
1124 composite_unbind(struct usb_gadget *gadget)
1126 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1128 /* composite_disconnect() must already have been called
1129 * by the underlying peripheral controller driver!
1130 * so there's no i/o concurrency that could affect the
1131 * state protected by cdev->lock.
1133 WARN_ON(cdev->config);
1135 while (!list_empty(&cdev->configs)) {
1136 struct usb_configuration *c;
1138 c = list_first_entry(&cdev->configs,
1139 struct usb_configuration, list);
1140 while (!list_empty(&c->functions)) {
1141 struct usb_function *f;
1143 f = list_first_entry(&c->functions,
1144 struct usb_function, list);
1147 DBG(cdev, "unbind function '%s'/%p\n",
1150 /* may free memory for "f" */
1155 DBG(cdev, "unbind config '%s'/%p\n", c->label, c);
1157 /* may free memory for "c" */
1160 if (composite->unbind)
1161 composite->unbind(cdev);
1164 kfree(cdev->req->buf);
1165 usb_ep_free_request(gadget->ep0, cdev->req);
1167 switch_dev_unregister(&cdev->sdev);
1168 device_remove_file(&gadget->dev, &dev_attr_suspended);
1170 set_gadget_data(gadget, NULL);
1174 static u8 override_id(struct usb_composite_dev *cdev, u8 *desc)
1177 int ret = usb_string_id(cdev);
1178 if (unlikely(ret < 0))
1179 WARNING(cdev, "failed to override string ID\n");
1187 static int composite_bind(struct usb_gadget *gadget)
1189 struct usb_composite_dev *cdev;
1190 int status = -ENOMEM;
1192 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
1196 spin_lock_init(&cdev->lock);
1197 cdev->gadget = gadget;
1198 set_gadget_data(gadget, cdev);
1199 INIT_LIST_HEAD(&cdev->configs);
1201 /* preallocate control response and buffer */
1202 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1205 cdev->req->buf = kmalloc(USB_BUFSIZ, GFP_KERNEL);
1206 if (!cdev->req->buf)
1208 cdev->req->complete = composite_setup_complete;
1209 gadget->ep0->driver_data = cdev;
1211 cdev->bufsiz = USB_BUFSIZ;
1212 cdev->driver = composite;
1215 * As per USB compliance update, a device that is actively drawing
1216 * more than 100mA from USB must report itself as bus-powered in
1217 * the GetStatus(DEVICE) call.
1219 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
1220 usb_gadget_set_selfpowered(gadget);
1222 /* interface and string IDs start at zero via kzalloc.
1223 * we force endpoints to start unassigned; few controller
1224 * drivers will zero ep->driver_data.
1226 usb_ep_autoconfig_reset(cdev->gadget);
1228 /* composite gadget needs to assign strings for whole device (like
1229 * serial number), register function drivers, potentially update
1230 * power state and consumption, etc
1232 status = composite_gadget_bind(cdev);
1236 cdev->sdev.name = "usb_configuration";
1237 status = switch_dev_register(&cdev->sdev);
1241 cdev->desc = *composite->dev;
1242 cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1244 /* standardized runtime overrides for device ID data */
1246 cdev->desc.idVendor = cpu_to_le16(idVendor);
1248 cdev->desc.idProduct = cpu_to_le16(idProduct);
1250 cdev->desc.bcdDevice = cpu_to_le16(bcdDevice);
1252 /* string overrides */
1253 if (iManufacturer || !cdev->desc.iManufacturer) {
1254 if (!iManufacturer && !composite->iManufacturer &&
1255 !*composite_manufacturer)
1256 snprintf(composite_manufacturer,
1257 sizeof composite_manufacturer,
1259 init_utsname()->sysname,
1260 init_utsname()->release,
1263 cdev->manufacturer_override =
1264 override_id(cdev, &cdev->desc.iManufacturer);
1267 if (iProduct || (!cdev->desc.iProduct && composite->iProduct))
1268 cdev->product_override =
1269 override_id(cdev, &cdev->desc.iProduct);
1272 cdev->serial_override =
1273 override_id(cdev, &cdev->desc.iSerialNumber);
1275 /* has userspace failed to provide a serial number? */
1276 if (composite->needs_serial && !cdev->desc.iSerialNumber)
1277 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
1280 status = device_create_file(&gadget->dev, &dev_attr_suspended);
1284 INFO(cdev, "%s ready\n", composite->name);
1288 composite_unbind(gadget);
1292 /*-------------------------------------------------------------------------*/
1295 composite_suspend(struct usb_gadget *gadget)
1297 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1298 struct usb_function *f;
1300 /* REVISIT: should we have config level
1301 * suspend/resume callbacks?
1303 DBG(cdev, "suspend\n");
1305 list_for_each_entry(f, &cdev->config->functions, list) {
1310 if (composite->suspend)
1311 composite->suspend(cdev);
1313 cdev->suspended = 1;
1315 usb_gadget_vbus_draw(gadget, 2);
1319 composite_resume(struct usb_gadget *gadget)
1321 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1322 struct usb_function *f;
1325 /* REVISIT: should we have config level
1326 * suspend/resume callbacks?
1328 DBG(cdev, "resume\n");
1329 if (composite->resume)
1330 composite->resume(cdev);
1332 list_for_each_entry(f, &cdev->config->functions, list) {
1337 maxpower = cdev->config->bMaxPower;
1339 usb_gadget_vbus_draw(gadget, maxpower ?
1340 (2 * maxpower) : CONFIG_USB_GADGET_VBUS_DRAW);
1343 cdev->suspended = 0;
1347 composite_uevent(struct device *dev, struct kobj_uevent_env *env)
1349 struct usb_function *f = dev_get_drvdata(dev);
1352 /* this happens when the device is first created */
1356 if (add_uevent_var(env, "FUNCTION=%s", f->name))
1358 if (add_uevent_var(env, "ENABLED=%d", !f->disabled))
1363 /*-------------------------------------------------------------------------*/
1365 static struct usb_gadget_driver composite_driver = {
1366 .speed = USB_SPEED_HIGH,
1368 .unbind = composite_unbind,
1370 .setup = composite_setup,
1371 .disconnect = composite_disconnect,
1373 .suspend = composite_suspend,
1374 .resume = composite_resume,
1377 .owner = THIS_MODULE,
1382 * usb_composite_probe() - register a composite driver
1383 * @driver: the driver to register
1384 * @bind: the callback used to allocate resources that are shared across the
1385 * whole device, such as string IDs, and add its configurations using
1386 * @usb_add_config(). This may fail by returning a negative errno
1387 * value; it should return zero on successful initialization.
1388 * Context: single threaded during gadget setup
1390 * This function is used to register drivers using the composite driver
1391 * framework. The return value is zero, or a negative errno value.
1392 * Those values normally come from the driver's @bind method, which does
1393 * all the work of setting up the driver to match the hardware.
1395 * On successful return, the gadget is ready to respond to requests from
1396 * the host, unless one of its components invokes usb_gadget_disconnect()
1397 * while it was binding. That would usually be done in order to wait for
1398 * some userspace participation.
1400 int usb_composite_probe(struct usb_composite_driver *driver,
1401 int (*bind)(struct usb_composite_dev *cdev))
1403 if (!driver || !driver->dev || !bind || composite)
1407 driver->name = "composite";
1408 if (!driver->iProduct)
1409 driver->iProduct = driver->name;
1410 composite_driver.function = (char *) driver->name;
1411 composite_driver.driver.name = driver->name;
1413 composite_gadget_bind = bind;
1415 driver->class = class_create(THIS_MODULE, "usb_composite");
1416 if (IS_ERR(driver->class))
1417 return PTR_ERR(driver->class);
1418 driver->class->dev_uevent = composite_uevent;
1420 return usb_gadget_probe_driver(&composite_driver, composite_bind);
1424 * usb_composite_unregister() - unregister a composite driver
1425 * @driver: the driver to unregister
1427 * This function is used to unregister drivers using the composite
1430 void usb_composite_unregister(struct usb_composite_driver *driver)
1432 if (composite != driver)
1434 usb_gadget_unregister_driver(&composite_driver);
1438 * usb_composite_setup_continue() - Continue with the control transfer
1439 * @cdev: the composite device who's control transfer was kept waiting
1441 * This function must be called by the USB function driver to continue
1442 * with the control transfer's data/status stage in case it had requested to
1443 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
1444 * can request the composite framework to delay the setup request's data/status
1445 * stages by returning USB_GADGET_DELAYED_STATUS.
1447 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
1450 struct usb_request *req = cdev->req;
1451 unsigned long flags;
1453 DBG(cdev, "%s\n", __func__);
1454 spin_lock_irqsave(&cdev->lock, flags);
1456 if (cdev->delayed_status == 0) {
1457 WARN(cdev, "%s: Unexpected call\n", __func__);
1459 } else if (--cdev->delayed_status == 0) {
1460 DBG(cdev, "%s: Completing delayed status\n", __func__);
1462 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1464 DBG(cdev, "ep_queue --> %d\n", value);
1466 composite_setup_complete(cdev->gadget->ep0, req);
1470 spin_unlock_irqrestore(&cdev->lock, flags);