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.
12 /* #define VERBOSE_DEBUG */
14 #include <linux/kallsyms.h>
15 #include <linux/kernel.h>
16 #include <linux/slab.h>
17 #include <linux/module.h>
18 #include <linux/device.h>
19 #include <linux/utsname.h>
21 #include <linux/usb/composite.h>
22 #include <linux/usb/otg.h>
23 #include <asm/unaligned.h>
25 #include "u_os_desc.h"
28 * struct usb_os_string - represents OS String to be reported by a gadget
29 * @bLength: total length of the entire descritor, always 0x12
30 * @bDescriptorType: USB_DT_STRING
31 * @qwSignature: the OS String proper
32 * @bMS_VendorCode: code used by the host for subsequent requests
33 * @bPad: not used, must be zero
35 struct usb_os_string {
38 __u8 qwSignature[OS_STRING_QW_SIGN_LEN];
44 * The code in this file is utility code, used to build a gadget driver
45 * from one or more "function" drivers, one or more "configuration"
46 * objects, and a "usb_composite_driver" by gluing them together along
47 * with the relevant device-wide data.
50 static struct usb_gadget_strings **get_containers_gs(
51 struct usb_gadget_string_container *uc)
53 return (struct usb_gadget_strings **)uc->stash;
57 * next_ep_desc() - advance to the next EP descriptor
58 * @t: currect pointer within descriptor array
60 * Return: next EP descriptor or NULL
62 * Iterate over @t until either EP descriptor found or
63 * NULL (that indicates end of list) encountered
65 static struct usb_descriptor_header**
66 next_ep_desc(struct usb_descriptor_header **t)
69 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
76 * for_each_ep_desc()- iterate over endpoint descriptors in the
78 * @start: pointer within descriptor array.
79 * @ep_desc: endpoint descriptor to use as the loop cursor
81 #define for_each_ep_desc(start, ep_desc) \
82 for (ep_desc = next_ep_desc(start); \
83 ep_desc; ep_desc = next_ep_desc(ep_desc+1))
86 * config_ep_by_speed() - configures the given endpoint
87 * according to gadget speed.
88 * @g: pointer to the gadget
90 * @_ep: the endpoint to configure
92 * Return: error code, 0 on success
94 * This function chooses the right descriptors for a given
95 * endpoint according to gadget speed and saves it in the
96 * endpoint desc field. If the endpoint already has a descriptor
97 * assigned to it - overwrites it with currently corresponding
98 * descriptor. The endpoint maxpacket field is updated according
99 * to the chosen descriptor.
100 * Note: the supplied function should hold all the descriptors
101 * for supported speeds
103 int config_ep_by_speed(struct usb_gadget *g,
104 struct usb_function *f,
107 struct usb_endpoint_descriptor *chosen_desc = NULL;
108 struct usb_descriptor_header **speed_desc = NULL;
110 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
111 int want_comp_desc = 0;
113 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
115 if (!g || !f || !_ep)
118 /* select desired speed */
120 case USB_SPEED_SUPER:
121 if (gadget_is_superspeed(g)) {
122 speed_desc = f->ss_descriptors;
126 /* else: Fall trough */
128 if (gadget_is_dualspeed(g)) {
129 speed_desc = f->hs_descriptors;
132 /* else: fall through */
134 speed_desc = f->fs_descriptors;
136 /* find descriptors */
137 for_each_ep_desc(speed_desc, d_spd) {
138 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
139 if (chosen_desc->bEndpointAddress == _ep->address)
146 _ep->maxpacket = usb_endpoint_maxp(chosen_desc) & 0x7ff;
147 _ep->desc = chosen_desc;
148 _ep->comp_desc = NULL;
152 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
153 usb_endpoint_xfer_int(_ep->desc)))
154 _ep->mult = ((usb_endpoint_maxp(_ep->desc) & 0x1800) >> 11) + 1;
160 * Companion descriptor should follow EP descriptor
161 * USB 3.0 spec, #9.6.7
163 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
165 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
167 _ep->comp_desc = comp_desc;
168 if (g->speed == USB_SPEED_SUPER) {
169 switch (usb_endpoint_type(_ep->desc)) {
170 case USB_ENDPOINT_XFER_ISOC:
171 /* mult: bits 1:0 of bmAttributes */
172 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
173 case USB_ENDPOINT_XFER_BULK:
174 case USB_ENDPOINT_XFER_INT:
175 _ep->maxburst = comp_desc->bMaxBurst + 1;
178 if (comp_desc->bMaxBurst != 0) {
179 struct usb_composite_dev *cdev;
181 cdev = get_gadget_data(g);
182 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
190 EXPORT_SYMBOL_GPL(config_ep_by_speed);
193 * usb_add_function() - add a function to a configuration
194 * @config: the configuration
195 * @function: the function being added
196 * Context: single threaded during gadget setup
198 * After initialization, each configuration must have one or more
199 * functions added to it. Adding a function involves calling its @bind()
200 * method to allocate resources such as interface and string identifiers
203 * This function returns the value of the function's bind(), which is
204 * zero for success else a negative errno value.
206 int usb_add_function(struct usb_configuration *config,
207 struct usb_function *function)
211 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
212 function->name, function,
213 config->label, config);
215 if (!function->set_alt || !function->disable)
218 function->config = config;
219 list_add_tail(&function->list, &config->functions);
221 if (function->bind_deactivated) {
222 value = usb_function_deactivate(function);
227 /* REVISIT *require* function->bind? */
228 if (function->bind) {
229 value = function->bind(config, function);
231 list_del(&function->list);
232 function->config = NULL;
237 /* We allow configurations that don't work at both speeds.
238 * If we run into a lowspeed Linux system, treat it the same
239 * as full speed ... it's the function drivers that will need
240 * to avoid bulk and ISO transfers.
242 if (!config->fullspeed && function->fs_descriptors)
243 config->fullspeed = true;
244 if (!config->highspeed && function->hs_descriptors)
245 config->highspeed = true;
246 if (!config->superspeed && function->ss_descriptors)
247 config->superspeed = true;
251 DBG(config->cdev, "adding '%s'/%p --> %d\n",
252 function->name, function, value);
255 EXPORT_SYMBOL_GPL(usb_add_function);
257 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
262 bitmap_zero(f->endpoints, 32);
267 EXPORT_SYMBOL_GPL(usb_remove_function);
270 * usb_function_deactivate - prevent function and gadget enumeration
271 * @function: the function that isn't yet ready to respond
273 * Blocks response of the gadget driver to host enumeration by
274 * preventing the data line pullup from being activated. This is
275 * normally called during @bind() processing to change from the
276 * initial "ready to respond" state, or when a required resource
279 * For example, drivers that serve as a passthrough to a userspace
280 * daemon can block enumeration unless that daemon (such as an OBEX,
281 * MTP, or print server) is ready to handle host requests.
283 * Not all systems support software control of their USB peripheral
286 * Returns zero on success, else negative errno.
288 int usb_function_deactivate(struct usb_function *function)
290 struct usb_composite_dev *cdev = function->config->cdev;
294 spin_lock_irqsave(&cdev->lock, flags);
296 if (cdev->deactivations == 0) {
297 spin_unlock_irqrestore(&cdev->lock, flags);
298 status = usb_gadget_deactivate(cdev->gadget);
299 spin_lock_irqsave(&cdev->lock, flags);
302 cdev->deactivations++;
304 spin_unlock_irqrestore(&cdev->lock, flags);
307 EXPORT_SYMBOL_GPL(usb_function_deactivate);
310 * usb_function_activate - allow function and gadget enumeration
311 * @function: function on which usb_function_activate() was called
313 * Reverses effect of usb_function_deactivate(). If no more functions
314 * are delaying their activation, the gadget driver will respond to
315 * host enumeration procedures.
317 * Returns zero on success, else negative errno.
319 int usb_function_activate(struct usb_function *function)
321 struct usb_composite_dev *cdev = function->config->cdev;
325 spin_lock_irqsave(&cdev->lock, flags);
327 if (WARN_ON(cdev->deactivations == 0))
330 cdev->deactivations--;
331 if (cdev->deactivations == 0) {
332 spin_unlock_irqrestore(&cdev->lock, flags);
333 status = usb_gadget_activate(cdev->gadget);
334 spin_lock_irqsave(&cdev->lock, flags);
338 spin_unlock_irqrestore(&cdev->lock, flags);
341 EXPORT_SYMBOL_GPL(usb_function_activate);
344 * usb_interface_id() - allocate an unused interface ID
345 * @config: configuration associated with the interface
346 * @function: function handling the interface
347 * Context: single threaded during gadget setup
349 * usb_interface_id() is called from usb_function.bind() callbacks to
350 * allocate new interface IDs. The function driver will then store that
351 * ID in interface, association, CDC union, and other descriptors. It
352 * will also handle any control requests targeted at that interface,
353 * particularly changing its altsetting via set_alt(). There may
354 * also be class-specific or vendor-specific requests to handle.
356 * All interface identifier should be allocated using this routine, to
357 * ensure that for example different functions don't wrongly assign
358 * different meanings to the same identifier. Note that since interface
359 * identifiers are configuration-specific, functions used in more than
360 * one configuration (or more than once in a given configuration) need
361 * multiple versions of the relevant descriptors.
363 * Returns the interface ID which was allocated; or -ENODEV if no
364 * more interface IDs can be allocated.
366 int usb_interface_id(struct usb_configuration *config,
367 struct usb_function *function)
369 unsigned id = config->next_interface_id;
371 if (id < MAX_CONFIG_INTERFACES) {
372 config->interface[id] = function;
373 config->next_interface_id = id + 1;
378 EXPORT_SYMBOL_GPL(usb_interface_id);
380 static u8 encode_bMaxPower(enum usb_device_speed speed,
381 struct usb_configuration *c)
388 val = CONFIG_USB_GADGET_VBUS_DRAW;
392 case USB_SPEED_SUPER:
393 return DIV_ROUND_UP(val, 8);
395 return DIV_ROUND_UP(val, 2);
399 static int config_buf(struct usb_configuration *config,
400 enum usb_device_speed speed, void *buf, u8 type)
402 struct usb_config_descriptor *c = buf;
403 void *next = buf + USB_DT_CONFIG_SIZE;
405 struct usb_function *f;
408 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
409 /* write the config descriptor */
411 c->bLength = USB_DT_CONFIG_SIZE;
412 c->bDescriptorType = type;
413 /* wTotalLength is written later */
414 c->bNumInterfaces = config->next_interface_id;
415 c->bConfigurationValue = config->bConfigurationValue;
416 c->iConfiguration = config->iConfiguration;
417 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
418 c->bMaxPower = encode_bMaxPower(speed, config);
420 /* There may be e.g. OTG descriptors */
421 if (config->descriptors) {
422 status = usb_descriptor_fillbuf(next, len,
423 config->descriptors);
430 /* add each function's descriptors */
431 list_for_each_entry(f, &config->functions, list) {
432 struct usb_descriptor_header **descriptors;
435 case USB_SPEED_SUPER:
436 descriptors = f->ss_descriptors;
439 descriptors = f->hs_descriptors;
442 descriptors = f->fs_descriptors;
447 status = usb_descriptor_fillbuf(next, len,
448 (const struct usb_descriptor_header **) descriptors);
456 c->wTotalLength = cpu_to_le16(len);
460 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
462 struct usb_gadget *gadget = cdev->gadget;
463 struct usb_configuration *c;
464 struct list_head *pos;
465 u8 type = w_value >> 8;
466 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
468 if (gadget->speed == USB_SPEED_SUPER)
469 speed = gadget->speed;
470 else if (gadget_is_dualspeed(gadget)) {
472 if (gadget->speed == USB_SPEED_HIGH)
474 if (type == USB_DT_OTHER_SPEED_CONFIG)
477 speed = USB_SPEED_HIGH;
481 /* This is a lookup by config *INDEX* */
484 pos = &cdev->configs;
485 c = cdev->os_desc_config;
489 while ((pos = pos->next) != &cdev->configs) {
490 c = list_entry(pos, typeof(*c), list);
492 /* skip OS Descriptors config which is handled separately */
493 if (c == cdev->os_desc_config)
497 /* ignore configs that won't work at this speed */
499 case USB_SPEED_SUPER:
513 return config_buf(c, speed, cdev->req->buf, type);
519 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
521 struct usb_gadget *gadget = cdev->gadget;
522 struct usb_configuration *c;
527 if (gadget_is_dualspeed(gadget)) {
528 if (gadget->speed == USB_SPEED_HIGH)
530 if (gadget->speed == USB_SPEED_SUPER)
532 if (type == USB_DT_DEVICE_QUALIFIER)
535 list_for_each_entry(c, &cdev->configs, list) {
536 /* ignore configs that won't work at this speed */
553 * bos_desc() - prepares the BOS descriptor.
554 * @cdev: pointer to usb_composite device to generate the bos
557 * This function generates the BOS (Binary Device Object)
558 * descriptor and its device capabilities descriptors. The BOS
559 * descriptor should be supported by a SuperSpeed device.
561 static int bos_desc(struct usb_composite_dev *cdev)
563 struct usb_ext_cap_descriptor *usb_ext;
564 struct usb_ss_cap_descriptor *ss_cap;
565 struct usb_dcd_config_params dcd_config_params;
566 struct usb_bos_descriptor *bos = cdev->req->buf;
568 bos->bLength = USB_DT_BOS_SIZE;
569 bos->bDescriptorType = USB_DT_BOS;
571 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
572 bos->bNumDeviceCaps = 0;
575 * A SuperSpeed device shall include the USB2.0 extension descriptor
576 * and shall support LPM when operating in USB2.0 HS mode.
578 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
579 bos->bNumDeviceCaps++;
580 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
581 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
582 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
583 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
584 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
587 * The Superspeed USB Capability descriptor shall be implemented by all
588 * SuperSpeed devices.
590 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
591 bos->bNumDeviceCaps++;
592 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
593 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
594 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
595 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
596 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
597 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
598 USB_FULL_SPEED_OPERATION |
599 USB_HIGH_SPEED_OPERATION |
600 USB_5GBPS_OPERATION);
601 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
603 /* Get Controller configuration */
604 if (cdev->gadget->ops->get_config_params)
605 cdev->gadget->ops->get_config_params(&dcd_config_params);
607 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
608 dcd_config_params.bU2DevExitLat =
609 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
611 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
612 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
614 return le16_to_cpu(bos->wTotalLength);
617 static void device_qual(struct usb_composite_dev *cdev)
619 struct usb_qualifier_descriptor *qual = cdev->req->buf;
621 qual->bLength = sizeof(*qual);
622 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
623 /* POLICY: same bcdUSB and device type info at both speeds */
624 qual->bcdUSB = cdev->desc.bcdUSB;
625 qual->bDeviceClass = cdev->desc.bDeviceClass;
626 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
627 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
628 /* ASSUME same EP0 fifo size at both speeds */
629 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
630 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
634 /*-------------------------------------------------------------------------*/
636 static void reset_config(struct usb_composite_dev *cdev)
638 struct usb_function *f;
640 DBG(cdev, "reset config\n");
642 list_for_each_entry(f, &cdev->config->functions, list) {
646 bitmap_zero(f->endpoints, 32);
649 cdev->delayed_status = 0;
652 static int set_config(struct usb_composite_dev *cdev,
653 const struct usb_ctrlrequest *ctrl, unsigned number)
655 struct usb_gadget *gadget = cdev->gadget;
656 struct usb_configuration *c = NULL;
657 int result = -EINVAL;
658 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
662 list_for_each_entry(c, &cdev->configs, list) {
663 if (c->bConfigurationValue == number) {
665 * We disable the FDs of the previous
666 * configuration only if the new configuration
677 } else { /* Zero configuration value - need to reset the config */
683 INFO(cdev, "%s config #%d: %s\n",
684 usb_speed_string(gadget->speed),
685 number, c ? c->label : "unconfigured");
690 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
693 /* Initialize all interfaces by setting them to altsetting zero. */
694 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
695 struct usb_function *f = c->interface[tmp];
696 struct usb_descriptor_header **descriptors;
702 * Record which endpoints are used by the function. This is used
703 * to dispatch control requests targeted at that endpoint to the
704 * function's setup callback instead of the current
705 * configuration's setup callback.
707 switch (gadget->speed) {
708 case USB_SPEED_SUPER:
709 descriptors = f->ss_descriptors;
712 descriptors = f->hs_descriptors;
715 descriptors = f->fs_descriptors;
718 for (; *descriptors; ++descriptors) {
719 struct usb_endpoint_descriptor *ep;
722 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
725 ep = (struct usb_endpoint_descriptor *)*descriptors;
726 addr = ((ep->bEndpointAddress & 0x80) >> 3)
727 | (ep->bEndpointAddress & 0x0f);
728 set_bit(addr, f->endpoints);
731 result = f->set_alt(f, tmp, 0);
733 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
734 tmp, f->name, f, result);
740 if (result == USB_GADGET_DELAYED_STATUS) {
742 "%s: interface %d (%s) requested delayed status\n",
743 __func__, tmp, f->name);
744 cdev->delayed_status++;
745 DBG(cdev, "delayed_status count %d\n",
746 cdev->delayed_status);
750 /* when we return, be sure our power usage is valid */
751 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
753 if (power <= USB_SELF_POWER_VBUS_MAX_DRAW)
754 usb_gadget_set_selfpowered(gadget);
756 usb_gadget_clear_selfpowered(gadget);
758 usb_gadget_vbus_draw(gadget, power);
759 if (result >= 0 && cdev->delayed_status)
760 result = USB_GADGET_DELAYED_STATUS;
764 int usb_add_config_only(struct usb_composite_dev *cdev,
765 struct usb_configuration *config)
767 struct usb_configuration *c;
769 if (!config->bConfigurationValue)
772 /* Prevent duplicate configuration identifiers */
773 list_for_each_entry(c, &cdev->configs, list) {
774 if (c->bConfigurationValue == config->bConfigurationValue)
779 list_add_tail(&config->list, &cdev->configs);
781 INIT_LIST_HEAD(&config->functions);
782 config->next_interface_id = 0;
783 memset(config->interface, 0, sizeof(config->interface));
787 EXPORT_SYMBOL_GPL(usb_add_config_only);
790 * usb_add_config() - add a configuration to a device.
791 * @cdev: wraps the USB gadget
792 * @config: the configuration, with bConfigurationValue assigned
793 * @bind: the configuration's bind function
794 * Context: single threaded during gadget setup
796 * One of the main tasks of a composite @bind() routine is to
797 * add each of the configurations it supports, using this routine.
799 * This function returns the value of the configuration's @bind(), which
800 * is zero for success else a negative errno value. Binding configurations
801 * assigns global resources including string IDs, and per-configuration
802 * resources such as interface IDs and endpoints.
804 int usb_add_config(struct usb_composite_dev *cdev,
805 struct usb_configuration *config,
806 int (*bind)(struct usb_configuration *))
808 int status = -EINVAL;
813 DBG(cdev, "adding config #%u '%s'/%p\n",
814 config->bConfigurationValue,
815 config->label, config);
817 status = usb_add_config_only(cdev, config);
821 status = bind(config);
823 while (!list_empty(&config->functions)) {
824 struct usb_function *f;
826 f = list_first_entry(&config->functions,
827 struct usb_function, list);
830 DBG(cdev, "unbind function '%s'/%p\n",
832 f->unbind(config, f);
833 /* may free memory for "f" */
836 list_del(&config->list);
841 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
842 config->bConfigurationValue, config,
843 config->superspeed ? " super" : "",
844 config->highspeed ? " high" : "",
846 ? (gadget_is_dualspeed(cdev->gadget)
851 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
852 struct usb_function *f = config->interface[i];
856 DBG(cdev, " interface %d = %s/%p\n",
861 /* set_alt(), or next bind(), sets up ep->claimed as needed */
862 usb_ep_autoconfig_reset(cdev->gadget);
866 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
867 config->bConfigurationValue, status);
870 EXPORT_SYMBOL_GPL(usb_add_config);
872 static void remove_config(struct usb_composite_dev *cdev,
873 struct usb_configuration *config)
875 while (!list_empty(&config->functions)) {
876 struct usb_function *f;
878 f = list_first_entry(&config->functions,
879 struct usb_function, list);
882 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
883 f->unbind(config, f);
884 /* may free memory for "f" */
887 list_del(&config->list);
888 if (config->unbind) {
889 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
890 config->unbind(config);
891 /* may free memory for "c" */
896 * usb_remove_config() - remove a configuration from a device.
897 * @cdev: wraps the USB gadget
898 * @config: the configuration
900 * Drivers must call usb_gadget_disconnect before calling this function
901 * to disconnect the device from the host and make sure the host will not
902 * try to enumerate the device while we are changing the config list.
904 void usb_remove_config(struct usb_composite_dev *cdev,
905 struct usb_configuration *config)
909 spin_lock_irqsave(&cdev->lock, flags);
911 if (cdev->config == config)
914 spin_unlock_irqrestore(&cdev->lock, flags);
916 remove_config(cdev, config);
919 /*-------------------------------------------------------------------------*/
921 /* We support strings in multiple languages ... string descriptor zero
922 * says which languages are supported. The typical case will be that
923 * only one language (probably English) is used, with i18n handled on
927 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
929 const struct usb_gadget_strings *s;
935 language = cpu_to_le16(s->language);
936 for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
937 if (*tmp == language)
946 static int lookup_string(
947 struct usb_gadget_strings **sp,
953 struct usb_gadget_strings *s;
958 if (s->language != language)
960 value = usb_gadget_get_string(s, id, buf);
967 static int get_string(struct usb_composite_dev *cdev,
968 void *buf, u16 language, int id)
970 struct usb_composite_driver *composite = cdev->driver;
971 struct usb_gadget_string_container *uc;
972 struct usb_configuration *c;
973 struct usb_function *f;
976 /* Yes, not only is USB's i18n support probably more than most
977 * folk will ever care about ... also, it's all supported here.
978 * (Except for UTF8 support for Unicode's "Astral Planes".)
981 /* 0 == report all available language codes */
983 struct usb_string_descriptor *s = buf;
984 struct usb_gadget_strings **sp;
987 s->bDescriptorType = USB_DT_STRING;
989 sp = composite->strings;
991 collect_langs(sp, s->wData);
993 list_for_each_entry(c, &cdev->configs, list) {
996 collect_langs(sp, s->wData);
998 list_for_each_entry(f, &c->functions, list) {
1001 collect_langs(sp, s->wData);
1004 list_for_each_entry(uc, &cdev->gstrings, list) {
1005 struct usb_gadget_strings **sp;
1007 sp = get_containers_gs(uc);
1008 collect_langs(sp, s->wData);
1011 for (len = 0; len <= USB_MAX_STRING_LEN && s->wData[len]; len++)
1016 s->bLength = 2 * (len + 1);
1020 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1021 struct usb_os_string *b = buf;
1022 b->bLength = sizeof(*b);
1023 b->bDescriptorType = USB_DT_STRING;
1025 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1026 "qwSignature size must be equal to qw_sign");
1027 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1028 b->bMS_VendorCode = cdev->b_vendor_code;
1033 list_for_each_entry(uc, &cdev->gstrings, list) {
1034 struct usb_gadget_strings **sp;
1036 sp = get_containers_gs(uc);
1037 len = lookup_string(sp, buf, language, id);
1042 /* String IDs are device-scoped, so we look up each string
1043 * table we're told about. These lookups are infrequent;
1044 * simpler-is-better here.
1046 if (composite->strings) {
1047 len = lookup_string(composite->strings, buf, language, id);
1051 list_for_each_entry(c, &cdev->configs, list) {
1053 len = lookup_string(c->strings, buf, language, id);
1057 list_for_each_entry(f, &c->functions, list) {
1060 len = lookup_string(f->strings, buf, language, id);
1069 * usb_string_id() - allocate an unused string ID
1070 * @cdev: the device whose string descriptor IDs are being allocated
1071 * Context: single threaded during gadget setup
1073 * @usb_string_id() is called from bind() callbacks to allocate
1074 * string IDs. Drivers for functions, configurations, or gadgets will
1075 * then store that ID in the appropriate descriptors and string table.
1077 * All string identifier should be allocated using this,
1078 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1079 * that for example different functions don't wrongly assign different
1080 * meanings to the same identifier.
1082 int usb_string_id(struct usb_composite_dev *cdev)
1084 if (cdev->next_string_id < 254) {
1085 /* string id 0 is reserved by USB spec for list of
1086 * supported languages */
1087 /* 255 reserved as well? -- mina86 */
1088 cdev->next_string_id++;
1089 return cdev->next_string_id;
1093 EXPORT_SYMBOL_GPL(usb_string_id);
1096 * usb_string_ids() - allocate unused string IDs in batch
1097 * @cdev: the device whose string descriptor IDs are being allocated
1098 * @str: an array of usb_string objects to assign numbers to
1099 * Context: single threaded during gadget setup
1101 * @usb_string_ids() is called from bind() callbacks to allocate
1102 * string IDs. Drivers for functions, configurations, or gadgets will
1103 * then copy IDs from the string table to the appropriate descriptors
1104 * and string table for other languages.
1106 * All string identifier should be allocated using this,
1107 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1108 * example different functions don't wrongly assign different meanings
1109 * to the same identifier.
1111 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1113 int next = cdev->next_string_id;
1115 for (; str->s; ++str) {
1116 if (unlikely(next >= 254))
1121 cdev->next_string_id = next;
1125 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1127 static struct usb_gadget_string_container *copy_gadget_strings(
1128 struct usb_gadget_strings **sp, unsigned n_gstrings,
1131 struct usb_gadget_string_container *uc;
1132 struct usb_gadget_strings **gs_array;
1133 struct usb_gadget_strings *gs;
1134 struct usb_string *s;
1141 mem += sizeof(void *) * (n_gstrings + 1);
1142 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1143 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1144 uc = kmalloc(mem, GFP_KERNEL);
1146 return ERR_PTR(-ENOMEM);
1147 gs_array = get_containers_gs(uc);
1149 stash += sizeof(void *) * (n_gstrings + 1);
1150 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1151 struct usb_string *org_s;
1153 gs_array[n_gs] = stash;
1154 gs = gs_array[n_gs];
1155 stash += sizeof(struct usb_gadget_strings);
1156 gs->language = sp[n_gs]->language;
1157 gs->strings = stash;
1158 org_s = sp[n_gs]->strings;
1160 for (n_s = 0; n_s < n_strings; n_s++) {
1162 stash += sizeof(struct usb_string);
1171 stash += sizeof(struct usb_string);
1174 gs_array[n_gs] = NULL;
1179 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1180 * @cdev: the device whose string descriptor IDs are being allocated
1182 * @sp: an array of usb_gadget_strings to attach.
1183 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1185 * This function will create a deep copy of usb_gadget_strings and usb_string
1186 * and attach it to the cdev. The actual string (usb_string.s) will not be
1187 * copied but only a referenced will be made. The struct usb_gadget_strings
1188 * array may contain multiple languages and should be NULL terminated.
1189 * The ->language pointer of each struct usb_gadget_strings has to contain the
1190 * same amount of entries.
1191 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1192 * usb_string entry of es-ES contains the translation of the first usb_string
1193 * entry of en-US. Therefore both entries become the same id assign.
1195 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1196 struct usb_gadget_strings **sp, unsigned n_strings)
1198 struct usb_gadget_string_container *uc;
1199 struct usb_gadget_strings **n_gs;
1200 unsigned n_gstrings = 0;
1204 for (i = 0; sp[i]; i++)
1208 return ERR_PTR(-EINVAL);
1210 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1212 return ERR_CAST(uc);
1214 n_gs = get_containers_gs(uc);
1215 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1219 for (i = 1; i < n_gstrings; i++) {
1220 struct usb_string *m_s;
1221 struct usb_string *s;
1224 m_s = n_gs[0]->strings;
1225 s = n_gs[i]->strings;
1226 for (n = 0; n < n_strings; n++) {
1232 list_add_tail(&uc->list, &cdev->gstrings);
1233 return n_gs[0]->strings;
1236 return ERR_PTR(ret);
1238 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1241 * usb_string_ids_n() - allocate unused string IDs in batch
1242 * @c: the device whose string descriptor IDs are being allocated
1243 * @n: number of string IDs to allocate
1244 * Context: single threaded during gadget setup
1246 * Returns the first requested ID. This ID and next @n-1 IDs are now
1247 * valid IDs. At least provided that @n is non-zero because if it
1248 * is, returns last requested ID which is now very useful information.
1250 * @usb_string_ids_n() is called from bind() callbacks to allocate
1251 * string IDs. Drivers for functions, configurations, or gadgets will
1252 * then store that ID in the appropriate descriptors and string table.
1254 * All string identifier should be allocated using this,
1255 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1256 * example different functions don't wrongly assign different meanings
1257 * to the same identifier.
1259 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1261 unsigned next = c->next_string_id;
1262 if (unlikely(n > 254 || (unsigned)next + n > 254))
1264 c->next_string_id += n;
1267 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1269 /*-------------------------------------------------------------------------*/
1271 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1273 struct usb_composite_dev *cdev;
1275 if (req->status || req->actual != req->length)
1276 DBG((struct usb_composite_dev *) ep->driver_data,
1277 "setup complete --> %d, %d/%d\n",
1278 req->status, req->actual, req->length);
1281 * REVIST The same ep0 requests are shared with function drivers
1282 * so they don't have to maintain the same ->complete() stubs.
1284 * Because of that, we need to check for the validity of ->context
1285 * here, even though we know we've set it to something useful.
1290 cdev = req->context;
1292 if (cdev->req == req)
1293 cdev->setup_pending = false;
1294 else if (cdev->os_desc_req == req)
1295 cdev->os_desc_pending = false;
1297 WARN(1, "unknown request %p\n", req);
1300 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1301 struct usb_request *req, gfp_t gfp_flags)
1305 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1307 if (cdev->req == req)
1308 cdev->setup_pending = true;
1309 else if (cdev->os_desc_req == req)
1310 cdev->os_desc_pending = true;
1312 WARN(1, "unknown request %p\n", req);
1318 static int count_ext_compat(struct usb_configuration *c)
1323 for (i = 0; i < c->next_interface_id; ++i) {
1324 struct usb_function *f;
1327 f = c->interface[i];
1328 for (j = 0; j < f->os_desc_n; ++j) {
1329 struct usb_os_desc *d;
1331 if (i != f->os_desc_table[j].if_id)
1333 d = f->os_desc_table[j].os_desc;
1334 if (d && d->ext_compat_id)
1342 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1347 for (i = 0; i < c->next_interface_id; ++i) {
1348 struct usb_function *f;
1351 f = c->interface[i];
1352 for (j = 0; j < f->os_desc_n; ++j) {
1353 struct usb_os_desc *d;
1355 if (i != f->os_desc_table[j].if_id)
1357 d = f->os_desc_table[j].os_desc;
1358 if (d && d->ext_compat_id) {
1361 memcpy(buf, d->ext_compat_id, 16);
1369 if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1377 static int count_ext_prop(struct usb_configuration *c, int interface)
1379 struct usb_function *f;
1382 f = c->interface[interface];
1383 for (j = 0; j < f->os_desc_n; ++j) {
1384 struct usb_os_desc *d;
1386 if (interface != f->os_desc_table[j].if_id)
1388 d = f->os_desc_table[j].os_desc;
1389 if (d && d->ext_compat_id)
1390 return d->ext_prop_count;
1395 static int len_ext_prop(struct usb_configuration *c, int interface)
1397 struct usb_function *f;
1398 struct usb_os_desc *d;
1401 res = 10; /* header length */
1402 f = c->interface[interface];
1403 for (j = 0; j < f->os_desc_n; ++j) {
1404 if (interface != f->os_desc_table[j].if_id)
1406 d = f->os_desc_table[j].os_desc;
1408 return min(res + d->ext_prop_len, 4096);
1413 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1415 struct usb_function *f;
1416 struct usb_os_desc *d;
1417 struct usb_os_desc_ext_prop *ext_prop;
1418 int j, count, n, ret;
1420 f = c->interface[interface];
1421 count = 10; /* header length */
1422 for (j = 0; j < f->os_desc_n; ++j) {
1423 if (interface != f->os_desc_table[j].if_id)
1425 d = f->os_desc_table[j].os_desc;
1427 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1428 n = ext_prop->data_len +
1429 ext_prop->name_len + 14;
1430 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1432 usb_ext_prop_put_size(buf, n);
1433 usb_ext_prop_put_type(buf, ext_prop->type);
1434 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1435 ext_prop->name_len);
1438 switch (ext_prop->type) {
1439 case USB_EXT_PROP_UNICODE:
1440 case USB_EXT_PROP_UNICODE_ENV:
1441 case USB_EXT_PROP_UNICODE_LINK:
1442 usb_ext_prop_put_unicode(buf, ret,
1444 ext_prop->data_len);
1446 case USB_EXT_PROP_BINARY:
1447 usb_ext_prop_put_binary(buf, ret,
1449 ext_prop->data_len);
1451 case USB_EXT_PROP_LE32:
1452 /* not implemented */
1453 case USB_EXT_PROP_BE32:
1454 /* not implemented */
1467 * The setup() callback implements all the ep0 functionality that's
1468 * not handled lower down, in hardware or the hardware driver(like
1469 * device and endpoint feature flags, and their status). It's all
1470 * housekeeping for the gadget function we're implementing. Most of
1471 * the work is in config and function specific setup.
1474 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1476 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1477 struct usb_request *req = cdev->req;
1478 int value = -EOPNOTSUPP;
1480 u16 w_index = le16_to_cpu(ctrl->wIndex);
1481 u8 intf = w_index & 0xFF;
1482 u16 w_value = le16_to_cpu(ctrl->wValue);
1483 u16 w_length = le16_to_cpu(ctrl->wLength);
1484 struct usb_function *f = NULL;
1487 /* partial re-init of the response message; the function or the
1488 * gadget might need to intercept e.g. a control-OUT completion
1489 * when we delegate to it.
1492 req->context = cdev;
1493 req->complete = composite_setup_complete;
1495 gadget->ep0->driver_data = cdev;
1498 * Don't let non-standard requests match any of the cases below
1501 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1504 switch (ctrl->bRequest) {
1506 /* we handle all standard USB descriptors */
1507 case USB_REQ_GET_DESCRIPTOR:
1508 if (ctrl->bRequestType != USB_DIR_IN)
1510 switch (w_value >> 8) {
1513 cdev->desc.bNumConfigurations =
1514 count_configs(cdev, USB_DT_DEVICE);
1515 cdev->desc.bMaxPacketSize0 =
1516 cdev->gadget->ep0->maxpacket;
1517 if (gadget_is_superspeed(gadget)) {
1518 if (gadget->speed >= USB_SPEED_SUPER) {
1519 cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1520 cdev->desc.bMaxPacketSize0 = 9;
1522 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1525 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1528 value = min(w_length, (u16) sizeof cdev->desc);
1529 memcpy(req->buf, &cdev->desc, value);
1531 case USB_DT_DEVICE_QUALIFIER:
1532 if (!gadget_is_dualspeed(gadget) ||
1533 gadget->speed >= USB_SPEED_SUPER)
1536 value = min_t(int, w_length,
1537 sizeof(struct usb_qualifier_descriptor));
1539 case USB_DT_OTHER_SPEED_CONFIG:
1540 if (!gadget_is_dualspeed(gadget) ||
1541 gadget->speed >= USB_SPEED_SUPER)
1545 value = config_desc(cdev, w_value);
1547 value = min(w_length, (u16) value);
1550 value = get_string(cdev, req->buf,
1551 w_index, w_value & 0xff);
1553 value = min(w_length, (u16) value);
1556 if (gadget_is_superspeed(gadget)) {
1557 value = bos_desc(cdev);
1558 value = min(w_length, (u16) value);
1562 if (gadget_is_otg(gadget)) {
1563 struct usb_configuration *config;
1564 int otg_desc_len = 0;
1567 config = cdev->config;
1569 config = list_first_entry(
1571 struct usb_configuration, list);
1575 if (gadget->otg_caps &&
1576 (gadget->otg_caps->otg_rev >= 0x0200))
1577 otg_desc_len += sizeof(
1578 struct usb_otg20_descriptor);
1580 otg_desc_len += sizeof(
1581 struct usb_otg_descriptor);
1583 value = min_t(int, w_length, otg_desc_len);
1584 memcpy(req->buf, config->descriptors[0], value);
1590 /* any number of configs can work */
1591 case USB_REQ_SET_CONFIGURATION:
1592 if (ctrl->bRequestType != 0)
1594 if (gadget_is_otg(gadget)) {
1595 if (gadget->a_hnp_support)
1596 DBG(cdev, "HNP available\n");
1597 else if (gadget->a_alt_hnp_support)
1598 DBG(cdev, "HNP on another port\n");
1600 VDBG(cdev, "HNP inactive\n");
1602 spin_lock(&cdev->lock);
1603 value = set_config(cdev, ctrl, w_value);
1604 spin_unlock(&cdev->lock);
1606 case USB_REQ_GET_CONFIGURATION:
1607 if (ctrl->bRequestType != USB_DIR_IN)
1610 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1612 *(u8 *)req->buf = 0;
1613 value = min(w_length, (u16) 1);
1616 /* function drivers must handle get/set altsetting */
1617 case USB_REQ_SET_INTERFACE:
1618 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1620 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1622 f = cdev->config->interface[intf];
1627 * If there's no get_alt() method, we know only altsetting zero
1628 * works. There is no need to check if set_alt() is not NULL
1629 * as we check this in usb_add_function().
1631 if (w_value && !f->get_alt)
1634 spin_lock(&cdev->lock);
1635 value = f->set_alt(f, w_index, w_value);
1636 if (value == USB_GADGET_DELAYED_STATUS) {
1638 "%s: interface %d (%s) requested delayed status\n",
1639 __func__, intf, f->name);
1640 cdev->delayed_status++;
1641 DBG(cdev, "delayed_status count %d\n",
1642 cdev->delayed_status);
1644 spin_unlock(&cdev->lock);
1646 case USB_REQ_GET_INTERFACE:
1647 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1649 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1651 f = cdev->config->interface[intf];
1654 /* lots of interfaces only need altsetting zero... */
1655 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1658 *((u8 *)req->buf) = value;
1659 value = min(w_length, (u16) 1);
1663 * USB 3.0 additions:
1664 * Function driver should handle get_status request. If such cb
1665 * wasn't supplied we respond with default value = 0
1666 * Note: function driver should supply such cb only for the first
1667 * interface of the function
1669 case USB_REQ_GET_STATUS:
1670 if (!gadget_is_superspeed(gadget))
1672 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1674 value = 2; /* This is the length of the get_status reply */
1675 put_unaligned_le16(0, req->buf);
1676 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1678 f = cdev->config->interface[intf];
1681 status = f->get_status ? f->get_status(f) : 0;
1684 put_unaligned_le16(status & 0x0000ffff, req->buf);
1687 * Function drivers should handle SetFeature/ClearFeature
1688 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1689 * only for the first interface of the function
1691 case USB_REQ_CLEAR_FEATURE:
1692 case USB_REQ_SET_FEATURE:
1693 if (!gadget_is_superspeed(gadget))
1695 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1698 case USB_INTRF_FUNC_SUSPEND:
1699 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1701 f = cdev->config->interface[intf];
1705 if (f->func_suspend)
1706 value = f->func_suspend(f, w_index >> 8);
1709 "func_suspend() returned error %d\n",
1719 * OS descriptors handling
1721 if (cdev->use_os_string && cdev->os_desc_config &&
1722 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1723 ctrl->bRequest == cdev->b_vendor_code) {
1724 struct usb_request *req;
1725 struct usb_configuration *os_desc_cfg;
1730 req = cdev->os_desc_req;
1731 req->context = cdev;
1732 req->complete = composite_setup_complete;
1734 os_desc_cfg = cdev->os_desc_config;
1735 w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1736 memset(buf, 0, w_length);
1738 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1739 case USB_RECIP_DEVICE:
1740 if (w_index != 0x4 || (w_value >> 8))
1743 if (w_length == 0x10) {
1744 /* Number of ext compat interfaces */
1745 count = count_ext_compat(os_desc_cfg);
1747 count *= 24; /* 24 B/ext compat desc */
1748 count += 16; /* header */
1749 put_unaligned_le32(count, buf);
1752 /* "extended compatibility ID"s */
1753 count = count_ext_compat(os_desc_cfg);
1755 count *= 24; /* 24 B/ext compat desc */
1756 count += 16; /* header */
1757 put_unaligned_le32(count, buf);
1759 value = fill_ext_compat(os_desc_cfg, buf);
1760 value = min_t(u16, w_length, value);
1763 case USB_RECIP_INTERFACE:
1764 if (w_index != 0x5 || (w_value >> 8))
1766 interface = w_value & 0xFF;
1768 if (w_length == 0x0A) {
1769 count = count_ext_prop(os_desc_cfg,
1771 put_unaligned_le16(count, buf + 8);
1772 count = len_ext_prop(os_desc_cfg,
1774 put_unaligned_le32(count, buf);
1778 count = count_ext_prop(os_desc_cfg,
1780 put_unaligned_le16(count, buf + 8);
1781 count = len_ext_prop(os_desc_cfg,
1783 put_unaligned_le32(count, buf);
1785 value = fill_ext_prop(os_desc_cfg,
1789 value = min_t(u16, w_length, value);
1793 req->length = value;
1794 req->context = cdev;
1795 req->zero = value < w_length;
1796 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1798 DBG(cdev, "ep_queue --> %d\n", value);
1800 composite_setup_complete(gadget->ep0, req);
1806 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1807 ctrl->bRequestType, ctrl->bRequest,
1808 w_value, w_index, w_length);
1810 /* functions always handle their interfaces and endpoints...
1811 * punt other recipients (other, WUSB, ...) to the current
1812 * configuration code.
1814 * REVISIT it could make sense to let the composite device
1815 * take such requests too, if that's ever needed: to work
1819 list_for_each_entry(f, &cdev->config->functions, list)
1820 if (f->req_match && f->req_match(f, ctrl))
1825 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1826 case USB_RECIP_INTERFACE:
1827 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1829 f = cdev->config->interface[intf];
1832 case USB_RECIP_ENDPOINT:
1835 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1836 list_for_each_entry(f, &cdev->config->functions, list) {
1837 if (test_bit(endp, f->endpoints))
1840 if (&f->list == &cdev->config->functions)
1846 value = f->setup(f, ctrl);
1848 struct usb_configuration *c;
1854 /* try current config's setup */
1856 value = c->setup(c, ctrl);
1860 /* try the only function in the current config */
1861 if (!list_is_singular(&c->functions))
1863 f = list_first_entry(&c->functions, struct usb_function,
1866 value = f->setup(f, ctrl);
1872 /* respond with data transfer before status phase? */
1873 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1874 req->length = value;
1875 req->context = cdev;
1876 req->zero = value < w_length;
1877 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1879 DBG(cdev, "ep_queue --> %d\n", value);
1881 composite_setup_complete(gadget->ep0, req);
1883 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1885 "%s: Delayed status not supported for w_length != 0",
1890 /* device either stalls (value < 0) or reports success */
1894 void composite_disconnect(struct usb_gadget *gadget)
1896 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1897 unsigned long flags;
1899 /* REVISIT: should we have config and device level
1900 * disconnect callbacks?
1902 spin_lock_irqsave(&cdev->lock, flags);
1903 cdev->suspended = 0;
1906 if (cdev->driver->disconnect)
1907 cdev->driver->disconnect(cdev);
1908 spin_unlock_irqrestore(&cdev->lock, flags);
1911 /*-------------------------------------------------------------------------*/
1913 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
1916 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1917 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1919 return sprintf(buf, "%d\n", cdev->suspended);
1921 static DEVICE_ATTR_RO(suspended);
1923 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1925 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1926 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
1927 struct usb_string *dev_str = gstr->strings;
1929 /* composite_disconnect() must already have been called
1930 * by the underlying peripheral controller driver!
1931 * so there's no i/o concurrency that could affect the
1932 * state protected by cdev->lock.
1934 WARN_ON(cdev->config);
1936 while (!list_empty(&cdev->configs)) {
1937 struct usb_configuration *c;
1938 c = list_first_entry(&cdev->configs,
1939 struct usb_configuration, list);
1940 remove_config(cdev, c);
1942 if (cdev->driver->unbind && unbind_driver)
1943 cdev->driver->unbind(cdev);
1945 composite_dev_cleanup(cdev);
1947 if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
1948 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
1950 kfree(cdev->def_manufacturer);
1952 set_gadget_data(gadget, NULL);
1955 static void composite_unbind(struct usb_gadget *gadget)
1957 __composite_unbind(gadget, true);
1960 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1961 const struct usb_device_descriptor *old)
1971 * these variables may have been set in
1972 * usb_composite_overwrite_options()
1974 idVendor = new->idVendor;
1975 idProduct = new->idProduct;
1976 bcdDevice = new->bcdDevice;
1977 iSerialNumber = new->iSerialNumber;
1978 iManufacturer = new->iManufacturer;
1979 iProduct = new->iProduct;
1983 new->idVendor = idVendor;
1985 new->idProduct = idProduct;
1987 new->bcdDevice = bcdDevice;
1989 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1991 new->iSerialNumber = iSerialNumber;
1993 new->iManufacturer = iManufacturer;
1995 new->iProduct = iProduct;
1998 int composite_dev_prepare(struct usb_composite_driver *composite,
1999 struct usb_composite_dev *cdev)
2001 struct usb_gadget *gadget = cdev->gadget;
2004 /* preallocate control response and buffer */
2005 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2009 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2010 if (!cdev->req->buf)
2013 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2017 cdev->req->complete = composite_setup_complete;
2018 cdev->req->context = cdev;
2019 gadget->ep0->driver_data = cdev;
2021 cdev->driver = composite;
2024 * As per USB compliance update, a device that is actively drawing
2025 * more than 100mA from USB must report itself as bus-powered in
2026 * the GetStatus(DEVICE) call.
2028 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2029 usb_gadget_set_selfpowered(gadget);
2031 /* interface and string IDs start at zero via kzalloc.
2032 * we force endpoints to start unassigned; few controller
2033 * drivers will zero ep->driver_data.
2035 usb_ep_autoconfig_reset(gadget);
2038 kfree(cdev->req->buf);
2040 usb_ep_free_request(gadget->ep0, cdev->req);
2045 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2050 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2051 if (!cdev->os_desc_req) {
2052 ret = PTR_ERR(cdev->os_desc_req);
2056 cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2058 if (!cdev->os_desc_req->buf) {
2059 ret = PTR_ERR(cdev->os_desc_req->buf);
2060 kfree(cdev->os_desc_req);
2063 cdev->os_desc_req->context = cdev;
2064 cdev->os_desc_req->complete = composite_setup_complete;
2069 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2071 struct usb_gadget_string_container *uc, *tmp;
2073 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2074 list_del(&uc->list);
2077 if (cdev->os_desc_req) {
2078 if (cdev->os_desc_pending)
2079 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2081 kfree(cdev->os_desc_req->buf);
2082 cdev->os_desc_req->buf = NULL;
2083 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2084 cdev->os_desc_req = NULL;
2087 if (cdev->setup_pending)
2088 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2090 kfree(cdev->req->buf);
2091 cdev->req->buf = NULL;
2092 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2095 cdev->next_string_id = 0;
2096 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2099 static int composite_bind(struct usb_gadget *gadget,
2100 struct usb_gadget_driver *gdriver)
2102 struct usb_composite_dev *cdev;
2103 struct usb_composite_driver *composite = to_cdriver(gdriver);
2104 int status = -ENOMEM;
2106 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2110 spin_lock_init(&cdev->lock);
2111 cdev->gadget = gadget;
2112 set_gadget_data(gadget, cdev);
2113 INIT_LIST_HEAD(&cdev->configs);
2114 INIT_LIST_HEAD(&cdev->gstrings);
2116 status = composite_dev_prepare(composite, cdev);
2120 /* composite gadget needs to assign strings for whole device (like
2121 * serial number), register function drivers, potentially update
2122 * power state and consumption, etc
2124 status = composite->bind(cdev);
2128 if (cdev->use_os_string) {
2129 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2134 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2136 /* has userspace failed to provide a serial number? */
2137 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2138 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2140 INFO(cdev, "%s ready\n", composite->name);
2144 __composite_unbind(gadget, false);
2148 /*-------------------------------------------------------------------------*/
2150 void composite_suspend(struct usb_gadget *gadget)
2152 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2153 struct usb_function *f;
2155 /* REVISIT: should we have config level
2156 * suspend/resume callbacks?
2158 DBG(cdev, "suspend\n");
2160 list_for_each_entry(f, &cdev->config->functions, list) {
2165 if (cdev->driver->suspend)
2166 cdev->driver->suspend(cdev);
2168 cdev->suspended = 1;
2170 usb_gadget_set_selfpowered(gadget);
2171 usb_gadget_vbus_draw(gadget, 2);
2174 void composite_resume(struct usb_gadget *gadget)
2176 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2177 struct usb_function *f;
2180 /* REVISIT: should we have config level
2181 * suspend/resume callbacks?
2183 DBG(cdev, "resume\n");
2184 if (cdev->driver->resume)
2185 cdev->driver->resume(cdev);
2187 list_for_each_entry(f, &cdev->config->functions, list) {
2192 maxpower = cdev->config->MaxPower;
2194 if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2195 usb_gadget_clear_selfpowered(gadget);
2197 usb_gadget_vbus_draw(gadget, maxpower ?
2198 maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2201 cdev->suspended = 0;
2204 /*-------------------------------------------------------------------------*/
2206 static const struct usb_gadget_driver composite_driver_template = {
2207 .bind = composite_bind,
2208 .unbind = composite_unbind,
2210 .setup = composite_setup,
2211 .reset = composite_disconnect,
2212 .disconnect = composite_disconnect,
2214 .suspend = composite_suspend,
2215 .resume = composite_resume,
2218 .owner = THIS_MODULE,
2223 * usb_composite_probe() - register a composite driver
2224 * @driver: the driver to register
2226 * Context: single threaded during gadget setup
2228 * This function is used to register drivers using the composite driver
2229 * framework. The return value is zero, or a negative errno value.
2230 * Those values normally come from the driver's @bind method, which does
2231 * all the work of setting up the driver to match the hardware.
2233 * On successful return, the gadget is ready to respond to requests from
2234 * the host, unless one of its components invokes usb_gadget_disconnect()
2235 * while it was binding. That would usually be done in order to wait for
2236 * some userspace participation.
2238 int usb_composite_probe(struct usb_composite_driver *driver)
2240 struct usb_gadget_driver *gadget_driver;
2242 if (!driver || !driver->dev || !driver->bind)
2246 driver->name = "composite";
2248 driver->gadget_driver = composite_driver_template;
2249 gadget_driver = &driver->gadget_driver;
2251 gadget_driver->function = (char *) driver->name;
2252 gadget_driver->driver.name = driver->name;
2253 gadget_driver->max_speed = driver->max_speed;
2255 return usb_gadget_probe_driver(gadget_driver);
2257 EXPORT_SYMBOL_GPL(usb_composite_probe);
2260 * usb_composite_unregister() - unregister a composite driver
2261 * @driver: the driver to unregister
2263 * This function is used to unregister drivers using the composite
2266 void usb_composite_unregister(struct usb_composite_driver *driver)
2268 usb_gadget_unregister_driver(&driver->gadget_driver);
2270 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2273 * usb_composite_setup_continue() - Continue with the control transfer
2274 * @cdev: the composite device who's control transfer was kept waiting
2276 * This function must be called by the USB function driver to continue
2277 * with the control transfer's data/status stage in case it had requested to
2278 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2279 * can request the composite framework to delay the setup request's data/status
2280 * stages by returning USB_GADGET_DELAYED_STATUS.
2282 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2285 struct usb_request *req = cdev->req;
2286 unsigned long flags;
2288 DBG(cdev, "%s\n", __func__);
2289 spin_lock_irqsave(&cdev->lock, flags);
2291 if (cdev->delayed_status == 0) {
2292 WARN(cdev, "%s: Unexpected call\n", __func__);
2294 } else if (--cdev->delayed_status == 0) {
2295 DBG(cdev, "%s: Completing delayed status\n", __func__);
2297 req->context = cdev;
2298 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2300 DBG(cdev, "ep_queue --> %d\n", value);
2302 composite_setup_complete(cdev->gadget->ep0, req);
2306 spin_unlock_irqrestore(&cdev->lock, flags);
2308 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2310 static char *composite_default_mfr(struct usb_gadget *gadget)
2315 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2316 init_utsname()->release, gadget->name);
2318 mfr = kmalloc(len, GFP_KERNEL);
2321 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2322 init_utsname()->release, gadget->name);
2326 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2327 struct usb_composite_overwrite *covr)
2329 struct usb_device_descriptor *desc = &cdev->desc;
2330 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2331 struct usb_string *dev_str = gstr->strings;
2334 desc->idVendor = cpu_to_le16(covr->idVendor);
2336 if (covr->idProduct)
2337 desc->idProduct = cpu_to_le16(covr->idProduct);
2339 if (covr->bcdDevice)
2340 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2342 if (covr->serial_number) {
2343 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2344 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2346 if (covr->manufacturer) {
2347 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2348 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2350 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2351 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2352 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2353 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2356 if (covr->product) {
2357 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2358 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2361 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2363 MODULE_LICENSE("GPL");
2364 MODULE_AUTHOR("David Brownell");