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 * function_descriptors() - get function descriptors for speed
61 * Returns the descriptors or NULL if not set.
63 static struct usb_descriptor_header **
64 function_descriptors(struct usb_function *f,
65 enum usb_device_speed speed)
67 struct usb_descriptor_header **descriptors;
70 case USB_SPEED_SUPER_PLUS:
71 descriptors = f->ssp_descriptors;
74 descriptors = f->ss_descriptors;
77 descriptors = f->hs_descriptors;
80 descriptors = f->fs_descriptors;
87 * next_ep_desc() - advance to the next EP descriptor
88 * @t: currect pointer within descriptor array
90 * Return: next EP descriptor or NULL
92 * Iterate over @t until either EP descriptor found or
93 * NULL (that indicates end of list) encountered
95 static struct usb_descriptor_header**
96 next_ep_desc(struct usb_descriptor_header **t)
99 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
106 * for_each_ep_desc()- iterate over endpoint descriptors in the
108 * @start: pointer within descriptor array.
109 * @ep_desc: endpoint descriptor to use as the loop cursor
111 #define for_each_ep_desc(start, ep_desc) \
112 for (ep_desc = next_ep_desc(start); \
113 ep_desc; ep_desc = next_ep_desc(ep_desc+1))
116 * config_ep_by_speed() - configures the given endpoint
117 * according to gadget speed.
118 * @g: pointer to the gadget
120 * @_ep: the endpoint to configure
122 * Return: error code, 0 on success
124 * This function chooses the right descriptors for a given
125 * endpoint according to gadget speed and saves it in the
126 * endpoint desc field. If the endpoint already has a descriptor
127 * assigned to it - overwrites it with currently corresponding
128 * descriptor. The endpoint maxpacket field is updated according
129 * to the chosen descriptor.
130 * Note: the supplied function should hold all the descriptors
131 * for supported speeds
133 int config_ep_by_speed(struct usb_gadget *g,
134 struct usb_function *f,
137 struct usb_composite_dev *cdev = get_gadget_data(g);
138 struct usb_endpoint_descriptor *chosen_desc = NULL;
139 struct usb_descriptor_header **speed_desc = NULL;
141 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
142 int want_comp_desc = 0;
144 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
146 if (!g || !f || !_ep)
149 /* select desired speed */
151 case USB_SPEED_SUPER:
152 if (gadget_is_superspeed(g)) {
153 speed_desc = f->ss_descriptors;
157 /* else: Fall trough */
159 if (gadget_is_dualspeed(g)) {
160 speed_desc = f->hs_descriptors;
163 /* else: fall through */
165 speed_desc = f->fs_descriptors;
167 /* find descriptors */
168 for_each_ep_desc(speed_desc, d_spd) {
169 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
170 if (chosen_desc->bEndpointAddress == _ep->address)
177 _ep->maxpacket = usb_endpoint_maxp(chosen_desc);
178 _ep->desc = chosen_desc;
179 _ep->comp_desc = NULL;
186 * Companion descriptor should follow EP descriptor
187 * USB 3.0 spec, #9.6.7
189 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
191 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
193 _ep->comp_desc = comp_desc;
194 if (g->speed == USB_SPEED_SUPER) {
195 switch (usb_endpoint_type(_ep->desc)) {
196 case USB_ENDPOINT_XFER_ISOC:
197 /* mult: bits 1:0 of bmAttributes */
198 _ep->mult = comp_desc->bmAttributes & 0x3;
199 case USB_ENDPOINT_XFER_BULK:
200 case USB_ENDPOINT_XFER_INT:
201 _ep->maxburst = comp_desc->bMaxBurst + 1;
204 if (comp_desc->bMaxBurst != 0)
205 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
212 EXPORT_SYMBOL_GPL(config_ep_by_speed);
215 * usb_add_function() - add a function to a configuration
216 * @config: the configuration
217 * @function: the function being added
218 * Context: single threaded during gadget setup
220 * After initialization, each configuration must have one or more
221 * functions added to it. Adding a function involves calling its @bind()
222 * method to allocate resources such as interface and string identifiers
225 * This function returns the value of the function's bind(), which is
226 * zero for success else a negative errno value.
228 int usb_add_function(struct usb_configuration *config,
229 struct usb_function *function)
233 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
234 function->name, function,
235 config->label, config);
237 if (!function->set_alt || !function->disable)
240 function->config = config;
241 list_add_tail(&function->list, &config->functions);
243 if (function->bind_deactivated) {
244 value = usb_function_deactivate(function);
249 /* REVISIT *require* function->bind? */
250 if (function->bind) {
251 value = function->bind(config, function);
253 list_del(&function->list);
254 function->config = NULL;
259 /* We allow configurations that don't work at both speeds.
260 * If we run into a lowspeed Linux system, treat it the same
261 * as full speed ... it's the function drivers that will need
262 * to avoid bulk and ISO transfers.
264 if (!config->fullspeed && function->fs_descriptors)
265 config->fullspeed = true;
266 if (!config->highspeed && function->hs_descriptors)
267 config->highspeed = true;
268 if (!config->superspeed && function->ss_descriptors)
269 config->superspeed = true;
270 if (!config->superspeed_plus && function->ssp_descriptors)
271 config->superspeed_plus = true;
275 DBG(config->cdev, "adding '%s'/%p --> %d\n",
276 function->name, function, value);
279 EXPORT_SYMBOL_GPL(usb_add_function);
281 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
286 bitmap_zero(f->endpoints, 32);
291 EXPORT_SYMBOL_GPL(usb_remove_function);
294 * usb_function_deactivate - prevent function and gadget enumeration
295 * @function: the function that isn't yet ready to respond
297 * Blocks response of the gadget driver to host enumeration by
298 * preventing the data line pullup from being activated. This is
299 * normally called during @bind() processing to change from the
300 * initial "ready to respond" state, or when a required resource
303 * For example, drivers that serve as a passthrough to a userspace
304 * daemon can block enumeration unless that daemon (such as an OBEX,
305 * MTP, or print server) is ready to handle host requests.
307 * Not all systems support software control of their USB peripheral
310 * Returns zero on success, else negative errno.
312 int usb_function_deactivate(struct usb_function *function)
314 struct usb_composite_dev *cdev = function->config->cdev;
318 spin_lock_irqsave(&cdev->lock, flags);
320 if (cdev->deactivations == 0)
321 status = usb_gadget_deactivate(cdev->gadget);
323 cdev->deactivations++;
325 spin_unlock_irqrestore(&cdev->lock, flags);
328 EXPORT_SYMBOL_GPL(usb_function_deactivate);
331 * usb_function_activate - allow function and gadget enumeration
332 * @function: function on which usb_function_activate() was called
334 * Reverses effect of usb_function_deactivate(). If no more functions
335 * are delaying their activation, the gadget driver will respond to
336 * host enumeration procedures.
338 * Returns zero on success, else negative errno.
340 int usb_function_activate(struct usb_function *function)
342 struct usb_composite_dev *cdev = function->config->cdev;
346 spin_lock_irqsave(&cdev->lock, flags);
348 if (WARN_ON(cdev->deactivations == 0))
351 cdev->deactivations--;
352 if (cdev->deactivations == 0)
353 status = usb_gadget_activate(cdev->gadget);
356 spin_unlock_irqrestore(&cdev->lock, flags);
359 EXPORT_SYMBOL_GPL(usb_function_activate);
362 * usb_interface_id() - allocate an unused interface ID
363 * @config: configuration associated with the interface
364 * @function: function handling the interface
365 * Context: single threaded during gadget setup
367 * usb_interface_id() is called from usb_function.bind() callbacks to
368 * allocate new interface IDs. The function driver will then store that
369 * ID in interface, association, CDC union, and other descriptors. It
370 * will also handle any control requests targeted at that interface,
371 * particularly changing its altsetting via set_alt(). There may
372 * also be class-specific or vendor-specific requests to handle.
374 * All interface identifier should be allocated using this routine, to
375 * ensure that for example different functions don't wrongly assign
376 * different meanings to the same identifier. Note that since interface
377 * identifiers are configuration-specific, functions used in more than
378 * one configuration (or more than once in a given configuration) need
379 * multiple versions of the relevant descriptors.
381 * Returns the interface ID which was allocated; or -ENODEV if no
382 * more interface IDs can be allocated.
384 int usb_interface_id(struct usb_configuration *config,
385 struct usb_function *function)
387 unsigned id = config->next_interface_id;
389 if (id < MAX_CONFIG_INTERFACES) {
390 config->interface[id] = function;
391 config->next_interface_id = id + 1;
396 EXPORT_SYMBOL_GPL(usb_interface_id);
398 static u8 encode_bMaxPower(enum usb_device_speed speed,
399 struct usb_configuration *c)
406 val = CONFIG_USB_GADGET_VBUS_DRAW;
410 case USB_SPEED_SUPER:
411 return DIV_ROUND_UP(val, 8);
413 return DIV_ROUND_UP(val, 2);
417 static int config_buf(struct usb_configuration *config,
418 enum usb_device_speed speed, void *buf, u8 type)
420 struct usb_config_descriptor *c = buf;
421 void *next = buf + USB_DT_CONFIG_SIZE;
423 struct usb_function *f;
426 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
427 /* write the config descriptor */
429 c->bLength = USB_DT_CONFIG_SIZE;
430 c->bDescriptorType = type;
431 /* wTotalLength is written later */
432 c->bNumInterfaces = config->next_interface_id;
433 c->bConfigurationValue = config->bConfigurationValue;
434 c->iConfiguration = config->iConfiguration;
435 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
436 c->bMaxPower = encode_bMaxPower(speed, config);
438 /* There may be e.g. OTG descriptors */
439 if (config->descriptors) {
440 status = usb_descriptor_fillbuf(next, len,
441 config->descriptors);
448 /* add each function's descriptors */
449 list_for_each_entry(f, &config->functions, list) {
450 struct usb_descriptor_header **descriptors;
452 descriptors = function_descriptors(f, speed);
455 status = usb_descriptor_fillbuf(next, len,
456 (const struct usb_descriptor_header **) descriptors);
464 c->wTotalLength = cpu_to_le16(len);
468 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
470 struct usb_gadget *gadget = cdev->gadget;
471 struct usb_configuration *c;
472 struct list_head *pos;
473 u8 type = w_value >> 8;
474 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
476 if (gadget->speed == USB_SPEED_SUPER)
477 speed = gadget->speed;
478 else if (gadget_is_dualspeed(gadget)) {
480 if (gadget->speed == USB_SPEED_HIGH)
482 if (type == USB_DT_OTHER_SPEED_CONFIG)
485 speed = USB_SPEED_HIGH;
489 /* This is a lookup by config *INDEX* */
492 pos = &cdev->configs;
493 c = cdev->os_desc_config;
497 while ((pos = pos->next) != &cdev->configs) {
498 c = list_entry(pos, typeof(*c), list);
500 /* skip OS Descriptors config which is handled separately */
501 if (c == cdev->os_desc_config)
505 /* ignore configs that won't work at this speed */
507 case USB_SPEED_SUPER:
521 return config_buf(c, speed, cdev->req->buf, type);
527 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
529 struct usb_gadget *gadget = cdev->gadget;
530 struct usb_configuration *c;
536 if (gadget_is_dualspeed(gadget)) {
537 if (gadget->speed == USB_SPEED_HIGH)
539 if (gadget->speed == USB_SPEED_SUPER)
541 if (gadget->speed == USB_SPEED_SUPER_PLUS)
543 if (type == USB_DT_DEVICE_QUALIFIER)
546 list_for_each_entry(c, &cdev->configs, list) {
547 /* ignore configs that won't work at this speed */
549 if (!c->superspeed_plus)
567 * bos_desc() - prepares the BOS descriptor.
568 * @cdev: pointer to usb_composite device to generate the bos
571 * This function generates the BOS (Binary Device Object)
572 * descriptor and its device capabilities descriptors. The BOS
573 * descriptor should be supported by a SuperSpeed device.
575 static int bos_desc(struct usb_composite_dev *cdev)
577 struct usb_ext_cap_descriptor *usb_ext;
578 struct usb_ss_cap_descriptor *ss_cap;
579 struct usb_dcd_config_params dcd_config_params;
580 struct usb_bos_descriptor *bos = cdev->req->buf;
582 bos->bLength = USB_DT_BOS_SIZE;
583 bos->bDescriptorType = USB_DT_BOS;
585 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
586 bos->bNumDeviceCaps = 0;
589 * A SuperSpeed device shall include the USB2.0 extension descriptor
590 * and shall support LPM when operating in USB2.0 HS mode.
592 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
593 bos->bNumDeviceCaps++;
594 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
595 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
596 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
597 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
598 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
601 * The Superspeed USB Capability descriptor shall be implemented by all
602 * SuperSpeed devices.
604 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
605 bos->bNumDeviceCaps++;
606 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
607 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
608 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
609 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
610 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
611 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
612 USB_FULL_SPEED_OPERATION |
613 USB_HIGH_SPEED_OPERATION |
614 USB_5GBPS_OPERATION);
615 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
617 /* Get Controller configuration */
618 if (cdev->gadget->ops->get_config_params)
619 cdev->gadget->ops->get_config_params(&dcd_config_params);
621 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
622 dcd_config_params.bU2DevExitLat =
623 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
625 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
626 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
628 /* The SuperSpeedPlus USB Device Capability descriptor */
629 if (gadget_is_superspeed_plus(cdev->gadget)) {
630 struct usb_ssp_cap_descriptor *ssp_cap;
632 ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
633 bos->bNumDeviceCaps++;
636 * Report typical values.
639 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
640 ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
641 ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
642 ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
644 /* SSAC = 1 (2 attributes) */
645 ssp_cap->bmAttributes = cpu_to_le32(1);
647 /* Min RX/TX Lane Count = 1 */
648 ssp_cap->wFunctionalitySupport = (1 << 8) | (1 << 12);
651 * bmSublinkSpeedAttr[0]:
654 * LP = 1 (SuperSpeedPlus)
657 ssp_cap->bmSublinkSpeedAttr[0] =
658 (3 << 4) | (1 << 14) | (0xa << 16);
660 * bmSublinkSpeedAttr[1] =
663 * LP = 1 (SuperSpeedPlus)
666 ssp_cap->bmSublinkSpeedAttr[1] =
667 (3 << 4) | (1 << 14) | (0xa << 16) | (1 << 7);
670 return le16_to_cpu(bos->wTotalLength);
673 static void device_qual(struct usb_composite_dev *cdev)
675 struct usb_qualifier_descriptor *qual = cdev->req->buf;
677 qual->bLength = sizeof(*qual);
678 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
679 /* POLICY: same bcdUSB and device type info at both speeds */
680 qual->bcdUSB = cdev->desc.bcdUSB;
681 qual->bDeviceClass = cdev->desc.bDeviceClass;
682 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
683 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
684 /* ASSUME same EP0 fifo size at both speeds */
685 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
686 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
690 /*-------------------------------------------------------------------------*/
692 static void reset_config(struct usb_composite_dev *cdev)
694 struct usb_function *f;
696 DBG(cdev, "reset config\n");
698 list_for_each_entry(f, &cdev->config->functions, list) {
702 bitmap_zero(f->endpoints, 32);
705 cdev->delayed_status = 0;
708 static int set_config(struct usb_composite_dev *cdev,
709 const struct usb_ctrlrequest *ctrl, unsigned number)
711 struct usb_gadget *gadget = cdev->gadget;
712 struct usb_configuration *c = NULL;
713 int result = -EINVAL;
714 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
718 list_for_each_entry(c, &cdev->configs, list) {
719 if (c->bConfigurationValue == number) {
721 * We disable the FDs of the previous
722 * configuration only if the new configuration
733 } else { /* Zero configuration value - need to reset the config */
739 INFO(cdev, "%s config #%d: %s\n",
740 usb_speed_string(gadget->speed),
741 number, c ? c->label : "unconfigured");
746 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
749 /* Initialize all interfaces by setting them to altsetting zero. */
750 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
751 struct usb_function *f = c->interface[tmp];
752 struct usb_descriptor_header **descriptors;
758 * Record which endpoints are used by the function. This is used
759 * to dispatch control requests targeted at that endpoint to the
760 * function's setup callback instead of the current
761 * configuration's setup callback.
763 descriptors = function_descriptors(f, gadget->speed);
765 for (; *descriptors; ++descriptors) {
766 struct usb_endpoint_descriptor *ep;
769 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
772 ep = (struct usb_endpoint_descriptor *)*descriptors;
773 addr = ((ep->bEndpointAddress & 0x80) >> 3)
774 | (ep->bEndpointAddress & 0x0f);
775 set_bit(addr, f->endpoints);
778 result = f->set_alt(f, tmp, 0);
780 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
781 tmp, f->name, f, result);
787 if (result == USB_GADGET_DELAYED_STATUS) {
789 "%s: interface %d (%s) requested delayed status\n",
790 __func__, tmp, f->name);
791 cdev->delayed_status++;
792 DBG(cdev, "delayed_status count %d\n",
793 cdev->delayed_status);
797 /* when we return, be sure our power usage is valid */
798 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
800 usb_gadget_vbus_draw(gadget, power);
801 if (result >= 0 && cdev->delayed_status)
802 result = USB_GADGET_DELAYED_STATUS;
806 int usb_add_config_only(struct usb_composite_dev *cdev,
807 struct usb_configuration *config)
809 struct usb_configuration *c;
811 if (!config->bConfigurationValue)
814 /* Prevent duplicate configuration identifiers */
815 list_for_each_entry(c, &cdev->configs, list) {
816 if (c->bConfigurationValue == config->bConfigurationValue)
821 list_add_tail(&config->list, &cdev->configs);
823 INIT_LIST_HEAD(&config->functions);
824 config->next_interface_id = 0;
825 memset(config->interface, 0, sizeof(config->interface));
829 EXPORT_SYMBOL_GPL(usb_add_config_only);
832 * usb_add_config() - add a configuration to a device.
833 * @cdev: wraps the USB gadget
834 * @config: the configuration, with bConfigurationValue assigned
835 * @bind: the configuration's bind function
836 * Context: single threaded during gadget setup
838 * One of the main tasks of a composite @bind() routine is to
839 * add each of the configurations it supports, using this routine.
841 * This function returns the value of the configuration's @bind(), which
842 * is zero for success else a negative errno value. Binding configurations
843 * assigns global resources including string IDs, and per-configuration
844 * resources such as interface IDs and endpoints.
846 int usb_add_config(struct usb_composite_dev *cdev,
847 struct usb_configuration *config,
848 int (*bind)(struct usb_configuration *))
850 int status = -EINVAL;
855 DBG(cdev, "adding config #%u '%s'/%p\n",
856 config->bConfigurationValue,
857 config->label, config);
859 status = usb_add_config_only(cdev, config);
863 status = bind(config);
865 while (!list_empty(&config->functions)) {
866 struct usb_function *f;
868 f = list_first_entry(&config->functions,
869 struct usb_function, list);
872 DBG(cdev, "unbind function '%s'/%p\n",
874 f->unbind(config, f);
875 /* may free memory for "f" */
878 list_del(&config->list);
883 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
884 config->bConfigurationValue, config,
885 config->superspeed ? " super" : "",
886 config->highspeed ? " high" : "",
888 ? (gadget_is_dualspeed(cdev->gadget)
893 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
894 struct usb_function *f = config->interface[i];
898 DBG(cdev, " interface %d = %s/%p\n",
903 /* set_alt(), or next bind(), sets up ep->claimed as needed */
904 usb_ep_autoconfig_reset(cdev->gadget);
908 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
909 config->bConfigurationValue, status);
912 EXPORT_SYMBOL_GPL(usb_add_config);
914 static void remove_config(struct usb_composite_dev *cdev,
915 struct usb_configuration *config)
917 while (!list_empty(&config->functions)) {
918 struct usb_function *f;
920 f = list_first_entry(&config->functions,
921 struct usb_function, list);
924 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
925 f->unbind(config, f);
926 /* may free memory for "f" */
929 list_del(&config->list);
930 if (config->unbind) {
931 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
932 config->unbind(config);
933 /* may free memory for "c" */
938 * usb_remove_config() - remove a configuration from a device.
939 * @cdev: wraps the USB gadget
940 * @config: the configuration
942 * Drivers must call usb_gadget_disconnect before calling this function
943 * to disconnect the device from the host and make sure the host will not
944 * try to enumerate the device while we are changing the config list.
946 void usb_remove_config(struct usb_composite_dev *cdev,
947 struct usb_configuration *config)
951 spin_lock_irqsave(&cdev->lock, flags);
953 if (cdev->config == config)
956 spin_unlock_irqrestore(&cdev->lock, flags);
958 remove_config(cdev, config);
961 /*-------------------------------------------------------------------------*/
963 /* We support strings in multiple languages ... string descriptor zero
964 * says which languages are supported. The typical case will be that
965 * only one language (probably English) is used, with i18n handled on
969 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
971 const struct usb_gadget_strings *s;
977 language = cpu_to_le16(s->language);
978 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
979 if (*tmp == language)
988 static int lookup_string(
989 struct usb_gadget_strings **sp,
995 struct usb_gadget_strings *s;
1000 if (s->language != language)
1002 value = usb_gadget_get_string(s, id, buf);
1009 static int get_string(struct usb_composite_dev *cdev,
1010 void *buf, u16 language, int id)
1012 struct usb_composite_driver *composite = cdev->driver;
1013 struct usb_gadget_string_container *uc;
1014 struct usb_configuration *c;
1015 struct usb_function *f;
1018 /* Yes, not only is USB's i18n support probably more than most
1019 * folk will ever care about ... also, it's all supported here.
1020 * (Except for UTF8 support for Unicode's "Astral Planes".)
1023 /* 0 == report all available language codes */
1025 struct usb_string_descriptor *s = buf;
1026 struct usb_gadget_strings **sp;
1029 s->bDescriptorType = USB_DT_STRING;
1031 sp = composite->strings;
1033 collect_langs(sp, s->wData);
1035 list_for_each_entry(c, &cdev->configs, list) {
1038 collect_langs(sp, s->wData);
1040 list_for_each_entry(f, &c->functions, list) {
1043 collect_langs(sp, s->wData);
1046 list_for_each_entry(uc, &cdev->gstrings, list) {
1047 struct usb_gadget_strings **sp;
1049 sp = get_containers_gs(uc);
1050 collect_langs(sp, s->wData);
1053 for (len = 0; len <= 126 && s->wData[len]; len++)
1058 s->bLength = 2 * (len + 1);
1062 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1063 struct usb_os_string *b = buf;
1064 b->bLength = sizeof(*b);
1065 b->bDescriptorType = USB_DT_STRING;
1067 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1068 "qwSignature size must be equal to qw_sign");
1069 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1070 b->bMS_VendorCode = cdev->b_vendor_code;
1075 list_for_each_entry(uc, &cdev->gstrings, list) {
1076 struct usb_gadget_strings **sp;
1078 sp = get_containers_gs(uc);
1079 len = lookup_string(sp, buf, language, id);
1084 /* String IDs are device-scoped, so we look up each string
1085 * table we're told about. These lookups are infrequent;
1086 * simpler-is-better here.
1088 if (composite->strings) {
1089 len = lookup_string(composite->strings, buf, language, id);
1093 list_for_each_entry(c, &cdev->configs, list) {
1095 len = lookup_string(c->strings, buf, language, id);
1099 list_for_each_entry(f, &c->functions, list) {
1102 len = lookup_string(f->strings, buf, language, id);
1111 * usb_string_id() - allocate an unused string ID
1112 * @cdev: the device whose string descriptor IDs are being allocated
1113 * Context: single threaded during gadget setup
1115 * @usb_string_id() is called from bind() callbacks to allocate
1116 * string IDs. Drivers for functions, configurations, or gadgets will
1117 * then store that ID in the appropriate descriptors and string table.
1119 * All string identifier should be allocated using this,
1120 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1121 * that for example different functions don't wrongly assign different
1122 * meanings to the same identifier.
1124 int usb_string_id(struct usb_composite_dev *cdev)
1126 if (cdev->next_string_id < 254) {
1127 /* string id 0 is reserved by USB spec for list of
1128 * supported languages */
1129 /* 255 reserved as well? -- mina86 */
1130 cdev->next_string_id++;
1131 return cdev->next_string_id;
1135 EXPORT_SYMBOL_GPL(usb_string_id);
1138 * usb_string_ids() - allocate unused string IDs in batch
1139 * @cdev: the device whose string descriptor IDs are being allocated
1140 * @str: an array of usb_string objects to assign numbers to
1141 * Context: single threaded during gadget setup
1143 * @usb_string_ids() is called from bind() callbacks to allocate
1144 * string IDs. Drivers for functions, configurations, or gadgets will
1145 * then copy IDs from the string table to the appropriate descriptors
1146 * and string table for other languages.
1148 * All string identifier should be allocated using this,
1149 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1150 * example different functions don't wrongly assign different meanings
1151 * to the same identifier.
1153 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1155 int next = cdev->next_string_id;
1157 for (; str->s; ++str) {
1158 if (unlikely(next >= 254))
1163 cdev->next_string_id = next;
1167 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1169 static struct usb_gadget_string_container *copy_gadget_strings(
1170 struct usb_gadget_strings **sp, unsigned n_gstrings,
1173 struct usb_gadget_string_container *uc;
1174 struct usb_gadget_strings **gs_array;
1175 struct usb_gadget_strings *gs;
1176 struct usb_string *s;
1183 mem += sizeof(void *) * (n_gstrings + 1);
1184 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1185 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1186 uc = kmalloc(mem, GFP_KERNEL);
1188 return ERR_PTR(-ENOMEM);
1189 gs_array = get_containers_gs(uc);
1191 stash += sizeof(void *) * (n_gstrings + 1);
1192 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1193 struct usb_string *org_s;
1195 gs_array[n_gs] = stash;
1196 gs = gs_array[n_gs];
1197 stash += sizeof(struct usb_gadget_strings);
1198 gs->language = sp[n_gs]->language;
1199 gs->strings = stash;
1200 org_s = sp[n_gs]->strings;
1202 for (n_s = 0; n_s < n_strings; n_s++) {
1204 stash += sizeof(struct usb_string);
1213 stash += sizeof(struct usb_string);
1216 gs_array[n_gs] = NULL;
1221 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1222 * @cdev: the device whose string descriptor IDs are being allocated
1224 * @sp: an array of usb_gadget_strings to attach.
1225 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1227 * This function will create a deep copy of usb_gadget_strings and usb_string
1228 * and attach it to the cdev. The actual string (usb_string.s) will not be
1229 * copied but only a referenced will be made. The struct usb_gadget_strings
1230 * array may contain multiple languages and should be NULL terminated.
1231 * The ->language pointer of each struct usb_gadget_strings has to contain the
1232 * same amount of entries.
1233 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1234 * usb_string entry of es-ES contains the translation of the first usb_string
1235 * entry of en-US. Therefore both entries become the same id assign.
1237 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1238 struct usb_gadget_strings **sp, unsigned n_strings)
1240 struct usb_gadget_string_container *uc;
1241 struct usb_gadget_strings **n_gs;
1242 unsigned n_gstrings = 0;
1246 for (i = 0; sp[i]; i++)
1250 return ERR_PTR(-EINVAL);
1252 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1254 return ERR_CAST(uc);
1256 n_gs = get_containers_gs(uc);
1257 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1261 for (i = 1; i < n_gstrings; i++) {
1262 struct usb_string *m_s;
1263 struct usb_string *s;
1266 m_s = n_gs[0]->strings;
1267 s = n_gs[i]->strings;
1268 for (n = 0; n < n_strings; n++) {
1274 list_add_tail(&uc->list, &cdev->gstrings);
1275 return n_gs[0]->strings;
1278 return ERR_PTR(ret);
1280 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1283 * usb_string_ids_n() - allocate unused string IDs in batch
1284 * @c: the device whose string descriptor IDs are being allocated
1285 * @n: number of string IDs to allocate
1286 * Context: single threaded during gadget setup
1288 * Returns the first requested ID. This ID and next @n-1 IDs are now
1289 * valid IDs. At least provided that @n is non-zero because if it
1290 * is, returns last requested ID which is now very useful information.
1292 * @usb_string_ids_n() is called from bind() callbacks to allocate
1293 * string IDs. Drivers for functions, configurations, or gadgets will
1294 * then store that ID in the appropriate descriptors and string table.
1296 * All string identifier should be allocated using this,
1297 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1298 * example different functions don't wrongly assign different meanings
1299 * to the same identifier.
1301 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1303 unsigned next = c->next_string_id;
1304 if (unlikely(n > 254 || (unsigned)next + n > 254))
1306 c->next_string_id += n;
1309 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1311 /*-------------------------------------------------------------------------*/
1313 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1315 struct usb_composite_dev *cdev;
1317 if (req->status || req->actual != req->length)
1318 DBG((struct usb_composite_dev *) ep->driver_data,
1319 "setup complete --> %d, %d/%d\n",
1320 req->status, req->actual, req->length);
1323 * REVIST The same ep0 requests are shared with function drivers
1324 * so they don't have to maintain the same ->complete() stubs.
1326 * Because of that, we need to check for the validity of ->context
1327 * here, even though we know we've set it to something useful.
1332 cdev = req->context;
1334 if (cdev->req == req)
1335 cdev->setup_pending = false;
1336 else if (cdev->os_desc_req == req)
1337 cdev->os_desc_pending = false;
1339 WARN(1, "unknown request %p\n", req);
1342 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1343 struct usb_request *req, gfp_t gfp_flags)
1347 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1349 if (cdev->req == req)
1350 cdev->setup_pending = true;
1351 else if (cdev->os_desc_req == req)
1352 cdev->os_desc_pending = true;
1354 WARN(1, "unknown request %p\n", req);
1360 static int count_ext_compat(struct usb_configuration *c)
1365 for (i = 0; i < c->next_interface_id; ++i) {
1366 struct usb_function *f;
1369 f = c->interface[i];
1370 for (j = 0; j < f->os_desc_n; ++j) {
1371 struct usb_os_desc *d;
1373 if (i != f->os_desc_table[j].if_id)
1375 d = f->os_desc_table[j].os_desc;
1376 if (d && d->ext_compat_id)
1384 static void fill_ext_compat(struct usb_configuration *c, u8 *buf)
1389 for (i = 0; i < c->next_interface_id; ++i) {
1390 struct usb_function *f;
1393 f = c->interface[i];
1394 for (j = 0; j < f->os_desc_n; ++j) {
1395 struct usb_os_desc *d;
1397 if (i != f->os_desc_table[j].if_id)
1399 d = f->os_desc_table[j].os_desc;
1400 if (d && d->ext_compat_id) {
1403 memcpy(buf, d->ext_compat_id, 16);
1417 static int count_ext_prop(struct usb_configuration *c, int interface)
1419 struct usb_function *f;
1422 f = c->interface[interface];
1423 for (j = 0; j < f->os_desc_n; ++j) {
1424 struct usb_os_desc *d;
1426 if (interface != f->os_desc_table[j].if_id)
1428 d = f->os_desc_table[j].os_desc;
1429 if (d && d->ext_compat_id)
1430 return d->ext_prop_count;
1435 static int len_ext_prop(struct usb_configuration *c, int interface)
1437 struct usb_function *f;
1438 struct usb_os_desc *d;
1441 res = 10; /* header length */
1442 f = c->interface[interface];
1443 for (j = 0; j < f->os_desc_n; ++j) {
1444 if (interface != f->os_desc_table[j].if_id)
1446 d = f->os_desc_table[j].os_desc;
1448 return min(res + d->ext_prop_len, 4096);
1453 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1455 struct usb_function *f;
1456 struct usb_os_desc *d;
1457 struct usb_os_desc_ext_prop *ext_prop;
1458 int j, count, n, ret;
1461 f = c->interface[interface];
1462 for (j = 0; j < f->os_desc_n; ++j) {
1463 if (interface != f->os_desc_table[j].if_id)
1465 d = f->os_desc_table[j].os_desc;
1467 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1468 /* 4kB minus header length */
1473 count = ext_prop->data_len +
1474 ext_prop->name_len + 14;
1475 if (count > 4086 - n)
1477 usb_ext_prop_put_size(buf, count);
1478 usb_ext_prop_put_type(buf, ext_prop->type);
1479 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1480 ext_prop->name_len);
1483 switch (ext_prop->type) {
1484 case USB_EXT_PROP_UNICODE:
1485 case USB_EXT_PROP_UNICODE_ENV:
1486 case USB_EXT_PROP_UNICODE_LINK:
1487 usb_ext_prop_put_unicode(buf, ret,
1489 ext_prop->data_len);
1491 case USB_EXT_PROP_BINARY:
1492 usb_ext_prop_put_binary(buf, ret,
1494 ext_prop->data_len);
1496 case USB_EXT_PROP_LE32:
1497 /* not implemented */
1498 case USB_EXT_PROP_BE32:
1499 /* not implemented */
1511 * The setup() callback implements all the ep0 functionality that's
1512 * not handled lower down, in hardware or the hardware driver(like
1513 * device and endpoint feature flags, and their status). It's all
1514 * housekeeping for the gadget function we're implementing. Most of
1515 * the work is in config and function specific setup.
1518 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1520 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1521 struct usb_request *req = cdev->req;
1522 int value = -EOPNOTSUPP;
1524 u16 w_index = le16_to_cpu(ctrl->wIndex);
1525 u8 intf = w_index & 0xFF;
1526 u16 w_value = le16_to_cpu(ctrl->wValue);
1527 u16 w_length = le16_to_cpu(ctrl->wLength);
1528 struct usb_function *f = NULL;
1531 /* partial re-init of the response message; the function or the
1532 * gadget might need to intercept e.g. a control-OUT completion
1533 * when we delegate to it.
1536 req->context = cdev;
1537 req->complete = composite_setup_complete;
1539 gadget->ep0->driver_data = cdev;
1542 * Don't let non-standard requests match any of the cases below
1545 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1548 switch (ctrl->bRequest) {
1550 /* we handle all standard USB descriptors */
1551 case USB_REQ_GET_DESCRIPTOR:
1552 if (ctrl->bRequestType != USB_DIR_IN)
1554 switch (w_value >> 8) {
1557 cdev->desc.bNumConfigurations =
1558 count_configs(cdev, USB_DT_DEVICE);
1559 cdev->desc.bMaxPacketSize0 =
1560 cdev->gadget->ep0->maxpacket;
1561 if (gadget_is_superspeed(gadget)) {
1562 if (gadget->speed >= USB_SPEED_SUPER) {
1563 cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1564 cdev->desc.bMaxPacketSize0 = 9;
1566 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1569 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1572 value = min(w_length, (u16) sizeof cdev->desc);
1573 memcpy(req->buf, &cdev->desc, value);
1575 case USB_DT_DEVICE_QUALIFIER:
1576 if (!gadget_is_dualspeed(gadget) ||
1577 gadget->speed >= USB_SPEED_SUPER)
1580 value = min_t(int, w_length,
1581 sizeof(struct usb_qualifier_descriptor));
1583 case USB_DT_OTHER_SPEED_CONFIG:
1584 if (!gadget_is_dualspeed(gadget) ||
1585 gadget->speed >= USB_SPEED_SUPER)
1589 value = config_desc(cdev, w_value);
1591 value = min(w_length, (u16) value);
1594 value = get_string(cdev, req->buf,
1595 w_index, w_value & 0xff);
1597 value = min(w_length, (u16) value);
1600 if (gadget_is_superspeed(gadget)) {
1601 value = bos_desc(cdev);
1602 value = min(w_length, (u16) value);
1606 if (gadget_is_otg(gadget)) {
1607 struct usb_configuration *config;
1608 int otg_desc_len = 0;
1611 config = cdev->config;
1613 config = list_first_entry(
1615 struct usb_configuration, list);
1619 if (gadget->otg_caps &&
1620 (gadget->otg_caps->otg_rev >= 0x0200))
1621 otg_desc_len += sizeof(
1622 struct usb_otg20_descriptor);
1624 otg_desc_len += sizeof(
1625 struct usb_otg_descriptor);
1627 value = min_t(int, w_length, otg_desc_len);
1628 memcpy(req->buf, config->descriptors[0], value);
1634 /* any number of configs can work */
1635 case USB_REQ_SET_CONFIGURATION:
1636 if (ctrl->bRequestType != 0)
1638 if (gadget_is_otg(gadget)) {
1639 if (gadget->a_hnp_support)
1640 DBG(cdev, "HNP available\n");
1641 else if (gadget->a_alt_hnp_support)
1642 DBG(cdev, "HNP on another port\n");
1644 VDBG(cdev, "HNP inactive\n");
1646 spin_lock(&cdev->lock);
1647 value = set_config(cdev, ctrl, w_value);
1648 spin_unlock(&cdev->lock);
1650 case USB_REQ_GET_CONFIGURATION:
1651 if (ctrl->bRequestType != USB_DIR_IN)
1654 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1656 *(u8 *)req->buf = 0;
1657 value = min(w_length, (u16) 1);
1660 /* function drivers must handle get/set altsetting; if there's
1661 * no get() method, we know only altsetting zero works.
1663 case USB_REQ_SET_INTERFACE:
1664 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1666 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1668 f = cdev->config->interface[intf];
1671 if (w_value && !f->set_alt)
1673 value = f->set_alt(f, w_index, w_value);
1674 if (value == USB_GADGET_DELAYED_STATUS) {
1676 "%s: interface %d (%s) requested delayed status\n",
1677 __func__, intf, f->name);
1678 cdev->delayed_status++;
1679 DBG(cdev, "delayed_status count %d\n",
1680 cdev->delayed_status);
1683 case USB_REQ_GET_INTERFACE:
1684 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1686 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1688 f = cdev->config->interface[intf];
1691 /* lots of interfaces only need altsetting zero... */
1692 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1695 *((u8 *)req->buf) = value;
1696 value = min(w_length, (u16) 1);
1700 * USB 3.0 additions:
1701 * Function driver should handle get_status request. If such cb
1702 * wasn't supplied we respond with default value = 0
1703 * Note: function driver should supply such cb only for the first
1704 * interface of the function
1706 case USB_REQ_GET_STATUS:
1707 if (!gadget_is_superspeed(gadget))
1709 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1711 value = 2; /* This is the length of the get_status reply */
1712 put_unaligned_le16(0, req->buf);
1713 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1715 f = cdev->config->interface[intf];
1718 status = f->get_status ? f->get_status(f) : 0;
1721 put_unaligned_le16(status & 0x0000ffff, req->buf);
1724 * Function drivers should handle SetFeature/ClearFeature
1725 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1726 * only for the first interface of the function
1728 case USB_REQ_CLEAR_FEATURE:
1729 case USB_REQ_SET_FEATURE:
1730 if (!gadget_is_superspeed(gadget))
1732 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1735 case USB_INTRF_FUNC_SUSPEND:
1736 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1738 f = cdev->config->interface[intf];
1742 if (f->func_suspend)
1743 value = f->func_suspend(f, w_index >> 8);
1746 "func_suspend() returned error %d\n",
1756 * OS descriptors handling
1758 if (cdev->use_os_string && cdev->os_desc_config &&
1759 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1760 ctrl->bRequest == cdev->b_vendor_code) {
1761 struct usb_request *req;
1762 struct usb_configuration *os_desc_cfg;
1767 req = cdev->os_desc_req;
1768 req->context = cdev;
1769 req->complete = composite_setup_complete;
1771 os_desc_cfg = cdev->os_desc_config;
1772 memset(buf, 0, w_length);
1774 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1775 case USB_RECIP_DEVICE:
1776 if (w_index != 0x4 || (w_value >> 8))
1779 if (w_length == 0x10) {
1780 /* Number of ext compat interfaces */
1781 count = count_ext_compat(os_desc_cfg);
1783 count *= 24; /* 24 B/ext compat desc */
1784 count += 16; /* header */
1785 put_unaligned_le32(count, buf);
1788 /* "extended compatibility ID"s */
1789 count = count_ext_compat(os_desc_cfg);
1791 count *= 24; /* 24 B/ext compat desc */
1792 count += 16; /* header */
1793 put_unaligned_le32(count, buf);
1795 fill_ext_compat(os_desc_cfg, buf);
1799 case USB_RECIP_INTERFACE:
1800 if (w_index != 0x5 || (w_value >> 8))
1802 interface = w_value & 0xFF;
1804 if (w_length == 0x0A) {
1805 count = count_ext_prop(os_desc_cfg,
1807 put_unaligned_le16(count, buf + 8);
1808 count = len_ext_prop(os_desc_cfg,
1810 put_unaligned_le32(count, buf);
1814 count = count_ext_prop(os_desc_cfg,
1816 put_unaligned_le16(count, buf + 8);
1817 count = len_ext_prop(os_desc_cfg,
1819 put_unaligned_le32(count, buf);
1821 value = fill_ext_prop(os_desc_cfg,
1830 req->length = value;
1831 req->context = cdev;
1832 req->zero = value < w_length;
1833 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1835 DBG(cdev, "ep_queue --> %d\n", value);
1837 composite_setup_complete(gadget->ep0, req);
1843 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1844 ctrl->bRequestType, ctrl->bRequest,
1845 w_value, w_index, w_length);
1847 /* functions always handle their interfaces and endpoints...
1848 * punt other recipients (other, WUSB, ...) to the current
1849 * configuration code.
1851 * REVISIT it could make sense to let the composite device
1852 * take such requests too, if that's ever needed: to work
1856 list_for_each_entry(f, &cdev->config->functions, list)
1857 if (f->req_match && f->req_match(f, ctrl))
1862 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1863 case USB_RECIP_INTERFACE:
1864 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1866 f = cdev->config->interface[intf];
1869 case USB_RECIP_ENDPOINT:
1870 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1871 list_for_each_entry(f, &cdev->config->functions, list) {
1872 if (test_bit(endp, f->endpoints))
1875 if (&f->list == &cdev->config->functions)
1881 value = f->setup(f, ctrl);
1883 struct usb_configuration *c;
1889 /* try current config's setup */
1891 value = c->setup(c, ctrl);
1895 /* try the only function in the current config */
1896 if (!list_is_singular(&c->functions))
1898 f = list_first_entry(&c->functions, struct usb_function,
1901 value = f->setup(f, ctrl);
1907 /* respond with data transfer before status phase? */
1908 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1909 req->length = value;
1910 req->context = cdev;
1911 req->zero = value < w_length;
1912 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1914 DBG(cdev, "ep_queue --> %d\n", value);
1916 composite_setup_complete(gadget->ep0, req);
1918 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1920 "%s: Delayed status not supported for w_length != 0",
1925 /* device either stalls (value < 0) or reports success */
1929 void composite_disconnect(struct usb_gadget *gadget)
1931 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1932 unsigned long flags;
1934 /* REVISIT: should we have config and device level
1935 * disconnect callbacks?
1937 spin_lock_irqsave(&cdev->lock, flags);
1940 if (cdev->driver->disconnect)
1941 cdev->driver->disconnect(cdev);
1942 spin_unlock_irqrestore(&cdev->lock, flags);
1945 /*-------------------------------------------------------------------------*/
1947 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
1950 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1951 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1953 return sprintf(buf, "%d\n", cdev->suspended);
1955 static DEVICE_ATTR_RO(suspended);
1957 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1959 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1961 /* composite_disconnect() must already have been called
1962 * by the underlying peripheral controller driver!
1963 * so there's no i/o concurrency that could affect the
1964 * state protected by cdev->lock.
1966 WARN_ON(cdev->config);
1968 while (!list_empty(&cdev->configs)) {
1969 struct usb_configuration *c;
1970 c = list_first_entry(&cdev->configs,
1971 struct usb_configuration, list);
1972 remove_config(cdev, c);
1974 if (cdev->driver->unbind && unbind_driver)
1975 cdev->driver->unbind(cdev);
1977 composite_dev_cleanup(cdev);
1979 kfree(cdev->def_manufacturer);
1981 set_gadget_data(gadget, NULL);
1984 static void composite_unbind(struct usb_gadget *gadget)
1986 __composite_unbind(gadget, true);
1989 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1990 const struct usb_device_descriptor *old)
2000 * these variables may have been set in
2001 * usb_composite_overwrite_options()
2003 idVendor = new->idVendor;
2004 idProduct = new->idProduct;
2005 bcdDevice = new->bcdDevice;
2006 iSerialNumber = new->iSerialNumber;
2007 iManufacturer = new->iManufacturer;
2008 iProduct = new->iProduct;
2012 new->idVendor = idVendor;
2014 new->idProduct = idProduct;
2016 new->bcdDevice = bcdDevice;
2018 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2020 new->iSerialNumber = iSerialNumber;
2022 new->iManufacturer = iManufacturer;
2024 new->iProduct = iProduct;
2027 int composite_dev_prepare(struct usb_composite_driver *composite,
2028 struct usb_composite_dev *cdev)
2030 struct usb_gadget *gadget = cdev->gadget;
2033 /* preallocate control response and buffer */
2034 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2038 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2039 if (!cdev->req->buf)
2042 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2046 cdev->req->complete = composite_setup_complete;
2047 cdev->req->context = cdev;
2048 gadget->ep0->driver_data = cdev;
2050 cdev->driver = composite;
2053 * As per USB compliance update, a device that is actively drawing
2054 * more than 100mA from USB must report itself as bus-powered in
2055 * the GetStatus(DEVICE) call.
2057 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2058 usb_gadget_set_selfpowered(gadget);
2060 /* interface and string IDs start at zero via kzalloc.
2061 * we force endpoints to start unassigned; few controller
2062 * drivers will zero ep->driver_data.
2064 usb_ep_autoconfig_reset(gadget);
2067 kfree(cdev->req->buf);
2069 usb_ep_free_request(gadget->ep0, cdev->req);
2074 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2079 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2080 if (!cdev->os_desc_req) {
2081 ret = PTR_ERR(cdev->os_desc_req);
2085 /* OS feature descriptor length <= 4kB */
2086 cdev->os_desc_req->buf = kmalloc(4096, GFP_KERNEL);
2087 if (!cdev->os_desc_req->buf) {
2088 ret = PTR_ERR(cdev->os_desc_req->buf);
2089 kfree(cdev->os_desc_req);
2092 cdev->os_desc_req->context = cdev;
2093 cdev->os_desc_req->complete = composite_setup_complete;
2098 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2100 struct usb_gadget_string_container *uc, *tmp;
2102 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2103 list_del(&uc->list);
2106 if (cdev->os_desc_req) {
2107 if (cdev->os_desc_pending)
2108 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2110 kfree(cdev->os_desc_req->buf);
2111 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2114 if (cdev->setup_pending)
2115 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2117 kfree(cdev->req->buf);
2118 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2120 cdev->next_string_id = 0;
2121 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2124 static int composite_bind(struct usb_gadget *gadget,
2125 struct usb_gadget_driver *gdriver)
2127 struct usb_composite_dev *cdev;
2128 struct usb_composite_driver *composite = to_cdriver(gdriver);
2129 int status = -ENOMEM;
2131 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2135 spin_lock_init(&cdev->lock);
2136 cdev->gadget = gadget;
2137 set_gadget_data(gadget, cdev);
2138 INIT_LIST_HEAD(&cdev->configs);
2139 INIT_LIST_HEAD(&cdev->gstrings);
2141 status = composite_dev_prepare(composite, cdev);
2145 /* composite gadget needs to assign strings for whole device (like
2146 * serial number), register function drivers, potentially update
2147 * power state and consumption, etc
2149 status = composite->bind(cdev);
2153 if (cdev->use_os_string) {
2154 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2159 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2161 /* has userspace failed to provide a serial number? */
2162 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2163 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2165 INFO(cdev, "%s ready\n", composite->name);
2169 __composite_unbind(gadget, false);
2173 /*-------------------------------------------------------------------------*/
2175 void composite_suspend(struct usb_gadget *gadget)
2177 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2178 struct usb_function *f;
2180 /* REVISIT: should we have config level
2181 * suspend/resume callbacks?
2183 DBG(cdev, "suspend\n");
2185 list_for_each_entry(f, &cdev->config->functions, list) {
2190 if (cdev->driver->suspend)
2191 cdev->driver->suspend(cdev);
2193 cdev->suspended = 1;
2195 usb_gadget_vbus_draw(gadget, 2);
2198 void composite_resume(struct usb_gadget *gadget)
2200 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2201 struct usb_function *f;
2204 /* REVISIT: should we have config level
2205 * suspend/resume callbacks?
2207 DBG(cdev, "resume\n");
2208 if (cdev->driver->resume)
2209 cdev->driver->resume(cdev);
2211 list_for_each_entry(f, &cdev->config->functions, list) {
2216 maxpower = cdev->config->MaxPower;
2218 usb_gadget_vbus_draw(gadget, maxpower ?
2219 maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2222 cdev->suspended = 0;
2225 /*-------------------------------------------------------------------------*/
2227 static const struct usb_gadget_driver composite_driver_template = {
2228 .bind = composite_bind,
2229 .unbind = composite_unbind,
2231 .setup = composite_setup,
2232 .reset = composite_disconnect,
2233 .disconnect = composite_disconnect,
2235 .suspend = composite_suspend,
2236 .resume = composite_resume,
2239 .owner = THIS_MODULE,
2244 * usb_composite_probe() - register a composite driver
2245 * @driver: the driver to register
2247 * Context: single threaded during gadget setup
2249 * This function is used to register drivers using the composite driver
2250 * framework. The return value is zero, or a negative errno value.
2251 * Those values normally come from the driver's @bind method, which does
2252 * all the work of setting up the driver to match the hardware.
2254 * On successful return, the gadget is ready to respond to requests from
2255 * the host, unless one of its components invokes usb_gadget_disconnect()
2256 * while it was binding. That would usually be done in order to wait for
2257 * some userspace participation.
2259 int usb_composite_probe(struct usb_composite_driver *driver)
2261 struct usb_gadget_driver *gadget_driver;
2263 if (!driver || !driver->dev || !driver->bind)
2267 driver->name = "composite";
2269 driver->gadget_driver = composite_driver_template;
2270 gadget_driver = &driver->gadget_driver;
2272 gadget_driver->function = (char *) driver->name;
2273 gadget_driver->driver.name = driver->name;
2274 gadget_driver->max_speed = driver->max_speed;
2276 return usb_gadget_probe_driver(gadget_driver);
2278 EXPORT_SYMBOL_GPL(usb_composite_probe);
2281 * usb_composite_unregister() - unregister a composite driver
2282 * @driver: the driver to unregister
2284 * This function is used to unregister drivers using the composite
2287 void usb_composite_unregister(struct usb_composite_driver *driver)
2289 usb_gadget_unregister_driver(&driver->gadget_driver);
2291 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2294 * usb_composite_setup_continue() - Continue with the control transfer
2295 * @cdev: the composite device who's control transfer was kept waiting
2297 * This function must be called by the USB function driver to continue
2298 * with the control transfer's data/status stage in case it had requested to
2299 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2300 * can request the composite framework to delay the setup request's data/status
2301 * stages by returning USB_GADGET_DELAYED_STATUS.
2303 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2306 struct usb_request *req = cdev->req;
2307 unsigned long flags;
2309 DBG(cdev, "%s\n", __func__);
2310 spin_lock_irqsave(&cdev->lock, flags);
2312 if (cdev->delayed_status == 0) {
2313 WARN(cdev, "%s: Unexpected call\n", __func__);
2315 } else if (--cdev->delayed_status == 0) {
2316 DBG(cdev, "%s: Completing delayed status\n", __func__);
2318 req->context = cdev;
2319 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2321 DBG(cdev, "ep_queue --> %d\n", value);
2323 composite_setup_complete(cdev->gadget->ep0, req);
2327 spin_unlock_irqrestore(&cdev->lock, flags);
2329 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2331 static char *composite_default_mfr(struct usb_gadget *gadget)
2336 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2337 init_utsname()->release, gadget->name);
2339 mfr = kmalloc(len, GFP_KERNEL);
2342 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2343 init_utsname()->release, gadget->name);
2347 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2348 struct usb_composite_overwrite *covr)
2350 struct usb_device_descriptor *desc = &cdev->desc;
2351 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2352 struct usb_string *dev_str = gstr->strings;
2355 desc->idVendor = cpu_to_le16(covr->idVendor);
2357 if (covr->idProduct)
2358 desc->idProduct = cpu_to_le16(covr->idProduct);
2360 if (covr->bcdDevice)
2361 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2363 if (covr->serial_number) {
2364 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2365 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2367 if (covr->manufacturer) {
2368 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2369 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2371 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2372 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2373 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2374 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2377 if (covr->product) {
2378 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2379 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2382 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2384 MODULE_LICENSE("GPL");
2385 MODULE_AUTHOR("David Brownell");