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 * NOTE: we try to help gadget drivers which might not be setting
71 * max_speed appropriately.
75 case USB_SPEED_SUPER_PLUS:
76 descriptors = f->ssp_descriptors;
81 descriptors = f->ss_descriptors;
86 descriptors = f->hs_descriptors;
91 descriptors = f->fs_descriptors;
95 * if we can't find any descriptors at all, then this gadget deserves to
96 * Oops with a NULL pointer dereference
103 * next_desc() - advance to the next desc_type descriptor
104 * @t: currect pointer within descriptor array
105 * @desc_type: descriptor type
107 * Return: next desc_type descriptor or NULL
109 * Iterate over @t until either desc_type descriptor found or
110 * NULL (that indicates end of list) encountered
112 static struct usb_descriptor_header**
113 next_desc(struct usb_descriptor_header **t, u8 desc_type)
116 if ((*t)->bDescriptorType == desc_type)
123 * for_each_desc() - iterate over desc_type descriptors in the
125 * @start: pointer within descriptor array.
126 * @iter_desc: desc_type descriptor to use as the loop cursor
127 * @desc_type: wanted descriptr type
129 #define for_each_desc(start, iter_desc, desc_type) \
130 for (iter_desc = next_desc(start, desc_type); \
131 iter_desc; iter_desc = next_desc(iter_desc + 1, desc_type))
134 * config_ep_by_speed_and_alt() - configures the given endpoint
135 * according to gadget speed.
136 * @g: pointer to the gadget
138 * @_ep: the endpoint to configure
139 * @alt: alternate setting number
141 * Return: error code, 0 on success
143 * This function chooses the right descriptors for a given
144 * endpoint according to gadget speed and saves it in the
145 * endpoint desc field. If the endpoint already has a descriptor
146 * assigned to it - overwrites it with currently corresponding
147 * descriptor. The endpoint maxpacket field is updated according
148 * to the chosen descriptor.
149 * Note: the supplied function should hold all the descriptors
150 * for supported speeds
152 int config_ep_by_speed_and_alt(struct usb_gadget *g,
153 struct usb_function *f,
157 struct usb_endpoint_descriptor *chosen_desc = NULL;
158 struct usb_interface_descriptor *int_desc = NULL;
159 struct usb_descriptor_header **speed_desc = NULL;
161 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
162 int want_comp_desc = 0;
164 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
166 if (!g || !f || !_ep)
169 /* select desired speed */
171 case USB_SPEED_SUPER_PLUS:
172 if (gadget_is_superspeed_plus(g)) {
173 speed_desc = f->ssp_descriptors;
177 /* else: Fall trough */
178 case USB_SPEED_SUPER:
179 if (gadget_is_superspeed(g)) {
180 speed_desc = f->ss_descriptors;
184 /* else: Fall trough */
186 if (gadget_is_dualspeed(g)) {
187 speed_desc = f->hs_descriptors;
190 /* else: fall through */
192 speed_desc = f->fs_descriptors;
195 /* find correct alternate setting descriptor */
196 for_each_desc(speed_desc, d_spd, USB_DT_INTERFACE) {
197 int_desc = (struct usb_interface_descriptor *)*d_spd;
199 if (int_desc->bAlternateSetting == alt) {
207 /* find descriptors */
208 for_each_desc(speed_desc, d_spd, USB_DT_ENDPOINT) {
209 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
210 if (chosen_desc->bEndpointAddress == _ep->address)
217 _ep->maxpacket = usb_endpoint_maxp(chosen_desc);
218 _ep->desc = chosen_desc;
219 _ep->comp_desc = NULL;
223 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
224 usb_endpoint_xfer_int(_ep->desc)))
225 _ep->mult = usb_endpoint_maxp_mult(_ep->desc);
231 * Companion descriptor should follow EP descriptor
232 * USB 3.0 spec, #9.6.7
234 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
236 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
238 _ep->comp_desc = comp_desc;
239 if (g->speed >= USB_SPEED_SUPER) {
240 switch (usb_endpoint_type(_ep->desc)) {
241 case USB_ENDPOINT_XFER_ISOC:
242 /* mult: bits 1:0 of bmAttributes */
243 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
244 case USB_ENDPOINT_XFER_BULK:
245 case USB_ENDPOINT_XFER_INT:
246 _ep->maxburst = comp_desc->bMaxBurst + 1;
249 if (comp_desc->bMaxBurst != 0) {
250 struct usb_composite_dev *cdev;
252 cdev = get_gadget_data(g);
253 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
261 EXPORT_SYMBOL_GPL(config_ep_by_speed_and_alt);
264 * config_ep_by_speed() - configures the given endpoint
265 * according to gadget speed.
266 * @g: pointer to the gadget
268 * @_ep: the endpoint to configure
270 * Return: error code, 0 on success
272 * This function chooses the right descriptors for a given
273 * endpoint according to gadget speed and saves it in the
274 * endpoint desc field. If the endpoint already has a descriptor
275 * assigned to it - overwrites it with currently corresponding
276 * descriptor. The endpoint maxpacket field is updated according
277 * to the chosen descriptor.
278 * Note: the supplied function should hold all the descriptors
279 * for supported speeds
281 int config_ep_by_speed(struct usb_gadget *g,
282 struct usb_function *f,
285 return config_ep_by_speed_and_alt(g, f, _ep, 0);
287 EXPORT_SYMBOL_GPL(config_ep_by_speed);
290 * usb_add_function() - add a function to a configuration
291 * @config: the configuration
292 * @function: the function being added
293 * Context: single threaded during gadget setup
295 * After initialization, each configuration must have one or more
296 * functions added to it. Adding a function involves calling its @bind()
297 * method to allocate resources such as interface and string identifiers
300 * This function returns the value of the function's bind(), which is
301 * zero for success else a negative errno value.
303 int usb_add_function(struct usb_configuration *config,
304 struct usb_function *function)
308 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
309 function->name, function,
310 config->label, config);
312 if (!function->set_alt || !function->disable)
315 function->config = config;
316 list_add_tail(&function->list, &config->functions);
318 if (function->bind_deactivated) {
319 value = usb_function_deactivate(function);
324 /* REVISIT *require* function->bind? */
325 if (function->bind) {
326 value = function->bind(config, function);
328 list_del(&function->list);
329 function->config = NULL;
334 /* We allow configurations that don't work at both speeds.
335 * If we run into a lowspeed Linux system, treat it the same
336 * as full speed ... it's the function drivers that will need
337 * to avoid bulk and ISO transfers.
339 if (!config->fullspeed && function->fs_descriptors)
340 config->fullspeed = true;
341 if (!config->highspeed && function->hs_descriptors)
342 config->highspeed = true;
343 if (!config->superspeed && function->ss_descriptors)
344 config->superspeed = true;
345 if (!config->superspeed_plus && function->ssp_descriptors)
346 config->superspeed_plus = true;
350 DBG(config->cdev, "adding '%s'/%p --> %d\n",
351 function->name, function, value);
354 EXPORT_SYMBOL_GPL(usb_add_function);
356 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
361 bitmap_zero(f->endpoints, 32);
366 if (f->bind_deactivated)
367 usb_function_activate(f);
369 EXPORT_SYMBOL_GPL(usb_remove_function);
372 * usb_function_deactivate - prevent function and gadget enumeration
373 * @function: the function that isn't yet ready to respond
375 * Blocks response of the gadget driver to host enumeration by
376 * preventing the data line pullup from being activated. This is
377 * normally called during @bind() processing to change from the
378 * initial "ready to respond" state, or when a required resource
381 * For example, drivers that serve as a passthrough to a userspace
382 * daemon can block enumeration unless that daemon (such as an OBEX,
383 * MTP, or print server) is ready to handle host requests.
385 * Not all systems support software control of their USB peripheral
388 * Returns zero on success, else negative errno.
390 int usb_function_deactivate(struct usb_function *function)
392 struct usb_composite_dev *cdev = function->config->cdev;
396 spin_lock_irqsave(&cdev->lock, flags);
398 if (cdev->deactivations == 0) {
399 spin_unlock_irqrestore(&cdev->lock, flags);
400 status = usb_gadget_deactivate(cdev->gadget);
401 spin_lock_irqsave(&cdev->lock, flags);
404 cdev->deactivations++;
406 spin_unlock_irqrestore(&cdev->lock, flags);
409 EXPORT_SYMBOL_GPL(usb_function_deactivate);
412 * usb_function_activate - allow function and gadget enumeration
413 * @function: function on which usb_function_activate() was called
415 * Reverses effect of usb_function_deactivate(). If no more functions
416 * are delaying their activation, the gadget driver will respond to
417 * host enumeration procedures.
419 * Returns zero on success, else negative errno.
421 int usb_function_activate(struct usb_function *function)
423 struct usb_composite_dev *cdev = function->config->cdev;
427 spin_lock_irqsave(&cdev->lock, flags);
429 if (WARN_ON(cdev->deactivations == 0))
432 cdev->deactivations--;
433 if (cdev->deactivations == 0) {
434 spin_unlock_irqrestore(&cdev->lock, flags);
435 status = usb_gadget_activate(cdev->gadget);
436 spin_lock_irqsave(&cdev->lock, flags);
440 spin_unlock_irqrestore(&cdev->lock, flags);
443 EXPORT_SYMBOL_GPL(usb_function_activate);
446 * usb_interface_id() - allocate an unused interface ID
447 * @config: configuration associated with the interface
448 * @function: function handling the interface
449 * Context: single threaded during gadget setup
451 * usb_interface_id() is called from usb_function.bind() callbacks to
452 * allocate new interface IDs. The function driver will then store that
453 * ID in interface, association, CDC union, and other descriptors. It
454 * will also handle any control requests targeted at that interface,
455 * particularly changing its altsetting via set_alt(). There may
456 * also be class-specific or vendor-specific requests to handle.
458 * All interface identifier should be allocated using this routine, to
459 * ensure that for example different functions don't wrongly assign
460 * different meanings to the same identifier. Note that since interface
461 * identifiers are configuration-specific, functions used in more than
462 * one configuration (or more than once in a given configuration) need
463 * multiple versions of the relevant descriptors.
465 * Returns the interface ID which was allocated; or -ENODEV if no
466 * more interface IDs can be allocated.
468 int usb_interface_id(struct usb_configuration *config,
469 struct usb_function *function)
471 unsigned id = config->next_interface_id;
473 if (id < MAX_CONFIG_INTERFACES) {
474 config->interface[id] = function;
475 config->next_interface_id = id + 1;
480 EXPORT_SYMBOL_GPL(usb_interface_id);
482 static u8 encode_bMaxPower(enum usb_device_speed speed,
483 struct usb_configuration *c)
487 if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
490 val = CONFIG_USB_GADGET_VBUS_DRAW;
493 if (speed < USB_SPEED_SUPER)
494 return min(val, 500U) / 2;
497 * USB 3.x supports up to 900mA, but since 900 isn't divisible
498 * by 8 the integral division will effectively cap to 896mA.
500 return min(val, 900U) / 8;
503 static int config_buf(struct usb_configuration *config,
504 enum usb_device_speed speed, void *buf, u8 type)
506 struct usb_config_descriptor *c = buf;
507 void *next = buf + USB_DT_CONFIG_SIZE;
509 struct usb_function *f;
512 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
513 /* write the config descriptor */
515 c->bLength = USB_DT_CONFIG_SIZE;
516 c->bDescriptorType = type;
517 /* wTotalLength is written later */
518 c->bNumInterfaces = config->next_interface_id;
519 c->bConfigurationValue = config->bConfigurationValue;
520 c->iConfiguration = config->iConfiguration;
521 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
522 c->bMaxPower = encode_bMaxPower(speed, config);
524 /* There may be e.g. OTG descriptors */
525 if (config->descriptors) {
526 status = usb_descriptor_fillbuf(next, len,
527 config->descriptors);
534 /* add each function's descriptors */
535 list_for_each_entry(f, &config->functions, list) {
536 struct usb_descriptor_header **descriptors;
538 descriptors = function_descriptors(f, speed);
541 status = usb_descriptor_fillbuf(next, len,
542 (const struct usb_descriptor_header **) descriptors);
550 c->wTotalLength = cpu_to_le16(len);
554 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
556 struct usb_gadget *gadget = cdev->gadget;
557 struct usb_configuration *c;
558 struct list_head *pos;
559 u8 type = w_value >> 8;
560 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
562 if (gadget->speed >= USB_SPEED_SUPER)
563 speed = gadget->speed;
564 else if (gadget_is_dualspeed(gadget)) {
566 if (gadget->speed == USB_SPEED_HIGH)
568 if (type == USB_DT_OTHER_SPEED_CONFIG)
571 speed = USB_SPEED_HIGH;
575 /* This is a lookup by config *INDEX* */
578 pos = &cdev->configs;
579 c = cdev->os_desc_config;
583 while ((pos = pos->next) != &cdev->configs) {
584 c = list_entry(pos, typeof(*c), list);
586 /* skip OS Descriptors config which is handled separately */
587 if (c == cdev->os_desc_config)
591 /* ignore configs that won't work at this speed */
593 case USB_SPEED_SUPER_PLUS:
594 if (!c->superspeed_plus)
597 case USB_SPEED_SUPER:
611 return config_buf(c, speed, cdev->req->buf, type);
617 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
619 struct usb_gadget *gadget = cdev->gadget;
620 struct usb_configuration *c;
626 if (gadget_is_dualspeed(gadget)) {
627 if (gadget->speed == USB_SPEED_HIGH)
629 if (gadget->speed == USB_SPEED_SUPER)
631 if (gadget->speed == USB_SPEED_SUPER_PLUS)
633 if (type == USB_DT_DEVICE_QUALIFIER)
636 list_for_each_entry(c, &cdev->configs, list) {
637 /* ignore configs that won't work at this speed */
639 if (!c->superspeed_plus)
657 * bos_desc() - prepares the BOS descriptor.
658 * @cdev: pointer to usb_composite device to generate the bos
661 * This function generates the BOS (Binary Device Object)
662 * descriptor and its device capabilities descriptors. The BOS
663 * descriptor should be supported by a SuperSpeed device.
665 static int bos_desc(struct usb_composite_dev *cdev)
667 struct usb_ext_cap_descriptor *usb_ext;
668 struct usb_dcd_config_params dcd_config_params;
669 struct usb_bos_descriptor *bos = cdev->req->buf;
671 bos->bLength = USB_DT_BOS_SIZE;
672 bos->bDescriptorType = USB_DT_BOS;
674 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
675 bos->bNumDeviceCaps = 0;
678 * A SuperSpeed device shall include the USB2.0 extension descriptor
679 * and shall support LPM when operating in USB2.0 HS mode.
681 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
682 bos->bNumDeviceCaps++;
683 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
684 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
685 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
686 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
687 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
690 * The Superspeed USB Capability descriptor shall be implemented by all
691 * SuperSpeed devices.
693 if (gadget_is_superspeed(cdev->gadget)) {
694 struct usb_ss_cap_descriptor *ss_cap;
696 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
697 bos->bNumDeviceCaps++;
698 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
699 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
700 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
701 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
702 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
703 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
704 USB_FULL_SPEED_OPERATION |
705 USB_HIGH_SPEED_OPERATION |
706 USB_5GBPS_OPERATION);
707 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
709 /* Get Controller configuration */
710 if (cdev->gadget->ops->get_config_params) {
711 cdev->gadget->ops->get_config_params(
714 dcd_config_params.bU1devExitLat =
715 USB_DEFAULT_U1_DEV_EXIT_LAT;
716 dcd_config_params.bU2DevExitLat =
717 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
719 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
720 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
723 /* The SuperSpeedPlus USB Device Capability descriptor */
724 if (gadget_is_superspeed_plus(cdev->gadget)) {
725 struct usb_ssp_cap_descriptor *ssp_cap;
727 ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
728 bos->bNumDeviceCaps++;
731 * Report typical values.
734 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
735 ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
736 ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
737 ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
738 ssp_cap->bReserved = 0;
739 ssp_cap->wReserved = 0;
741 /* SSAC = 1 (2 attributes) */
742 ssp_cap->bmAttributes = cpu_to_le32(1);
744 /* Min RX/TX Lane Count = 1 */
745 ssp_cap->wFunctionalitySupport =
746 cpu_to_le16((1 << 8) | (1 << 12));
749 * bmSublinkSpeedAttr[0]:
752 * LP = 1 (SuperSpeedPlus)
755 ssp_cap->bmSublinkSpeedAttr[0] =
756 cpu_to_le32((3 << 4) | (1 << 14) | (0xa << 16));
758 * bmSublinkSpeedAttr[1] =
761 * LP = 1 (SuperSpeedPlus)
764 ssp_cap->bmSublinkSpeedAttr[1] =
765 cpu_to_le32((3 << 4) | (1 << 14) |
766 (0xa << 16) | (1 << 7));
769 return le16_to_cpu(bos->wTotalLength);
772 static void device_qual(struct usb_composite_dev *cdev)
774 struct usb_qualifier_descriptor *qual = cdev->req->buf;
776 qual->bLength = sizeof(*qual);
777 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
778 /* POLICY: same bcdUSB and device type info at both speeds */
779 qual->bcdUSB = cdev->desc.bcdUSB;
780 qual->bDeviceClass = cdev->desc.bDeviceClass;
781 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
782 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
783 /* ASSUME same EP0 fifo size at both speeds */
784 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
785 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
789 /*-------------------------------------------------------------------------*/
791 static void reset_config(struct usb_composite_dev *cdev)
793 struct usb_function *f;
795 DBG(cdev, "reset config\n");
797 list_for_each_entry(f, &cdev->config->functions, list) {
801 bitmap_zero(f->endpoints, 32);
804 cdev->delayed_status = 0;
807 static int set_config(struct usb_composite_dev *cdev,
808 const struct usb_ctrlrequest *ctrl, unsigned number)
810 struct usb_gadget *gadget = cdev->gadget;
811 struct usb_configuration *c = NULL;
812 int result = -EINVAL;
813 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
817 list_for_each_entry(c, &cdev->configs, list) {
818 if (c->bConfigurationValue == number) {
820 * We disable the FDs of the previous
821 * configuration only if the new configuration
832 } else { /* Zero configuration value - need to reset the config */
838 INFO(cdev, "%s config #%d: %s\n",
839 usb_speed_string(gadget->speed),
840 number, c ? c->label : "unconfigured");
845 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
848 /* Initialize all interfaces by setting them to altsetting zero. */
849 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
850 struct usb_function *f = c->interface[tmp];
851 struct usb_descriptor_header **descriptors;
857 * Record which endpoints are used by the function. This is used
858 * to dispatch control requests targeted at that endpoint to the
859 * function's setup callback instead of the current
860 * configuration's setup callback.
862 descriptors = function_descriptors(f, gadget->speed);
864 for (; *descriptors; ++descriptors) {
865 struct usb_endpoint_descriptor *ep;
868 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
871 ep = (struct usb_endpoint_descriptor *)*descriptors;
872 addr = ((ep->bEndpointAddress & 0x80) >> 3)
873 | (ep->bEndpointAddress & 0x0f);
874 set_bit(addr, f->endpoints);
877 result = f->set_alt(f, tmp, 0);
879 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
880 tmp, f->name, f, result);
886 if (result == USB_GADGET_DELAYED_STATUS) {
888 "%s: interface %d (%s) requested delayed status\n",
889 __func__, tmp, f->name);
890 cdev->delayed_status++;
891 DBG(cdev, "delayed_status count %d\n",
892 cdev->delayed_status);
896 /* when we return, be sure our power usage is valid */
897 if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
900 power = CONFIG_USB_GADGET_VBUS_DRAW;
902 if (gadget->speed < USB_SPEED_SUPER)
903 power = min(power, 500U);
905 power = min(power, 900U);
907 if (power <= USB_SELF_POWER_VBUS_MAX_DRAW)
908 usb_gadget_set_selfpowered(gadget);
910 usb_gadget_clear_selfpowered(gadget);
912 usb_gadget_vbus_draw(gadget, power);
913 if (result >= 0 && cdev->delayed_status)
914 result = USB_GADGET_DELAYED_STATUS;
918 int usb_add_config_only(struct usb_composite_dev *cdev,
919 struct usb_configuration *config)
921 struct usb_configuration *c;
923 if (!config->bConfigurationValue)
926 /* Prevent duplicate configuration identifiers */
927 list_for_each_entry(c, &cdev->configs, list) {
928 if (c->bConfigurationValue == config->bConfigurationValue)
933 list_add_tail(&config->list, &cdev->configs);
935 INIT_LIST_HEAD(&config->functions);
936 config->next_interface_id = 0;
937 memset(config->interface, 0, sizeof(config->interface));
941 EXPORT_SYMBOL_GPL(usb_add_config_only);
944 * usb_add_config() - add a configuration to a device.
945 * @cdev: wraps the USB gadget
946 * @config: the configuration, with bConfigurationValue assigned
947 * @bind: the configuration's bind function
948 * Context: single threaded during gadget setup
950 * One of the main tasks of a composite @bind() routine is to
951 * add each of the configurations it supports, using this routine.
953 * This function returns the value of the configuration's @bind(), which
954 * is zero for success else a negative errno value. Binding configurations
955 * assigns global resources including string IDs, and per-configuration
956 * resources such as interface IDs and endpoints.
958 int usb_add_config(struct usb_composite_dev *cdev,
959 struct usb_configuration *config,
960 int (*bind)(struct usb_configuration *))
962 int status = -EINVAL;
967 DBG(cdev, "adding config #%u '%s'/%p\n",
968 config->bConfigurationValue,
969 config->label, config);
971 status = usb_add_config_only(cdev, config);
975 status = bind(config);
977 while (!list_empty(&config->functions)) {
978 struct usb_function *f;
980 f = list_first_entry(&config->functions,
981 struct usb_function, list);
984 DBG(cdev, "unbind function '%s'/%p\n",
986 f->unbind(config, f);
987 /* may free memory for "f" */
990 list_del(&config->list);
995 DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
996 config->bConfigurationValue, config,
997 config->superspeed_plus ? " superplus" : "",
998 config->superspeed ? " super" : "",
999 config->highspeed ? " high" : "",
1001 ? (gadget_is_dualspeed(cdev->gadget)
1006 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
1007 struct usb_function *f = config->interface[i];
1011 DBG(cdev, " interface %d = %s/%p\n",
1016 /* set_alt(), or next bind(), sets up ep->claimed as needed */
1017 usb_ep_autoconfig_reset(cdev->gadget);
1021 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1022 config->bConfigurationValue, status);
1025 EXPORT_SYMBOL_GPL(usb_add_config);
1027 static void remove_config(struct usb_composite_dev *cdev,
1028 struct usb_configuration *config)
1030 while (!list_empty(&config->functions)) {
1031 struct usb_function *f;
1033 f = list_first_entry(&config->functions,
1034 struct usb_function, list);
1036 usb_remove_function(config, f);
1038 list_del(&config->list);
1039 if (config->unbind) {
1040 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
1041 config->unbind(config);
1042 /* may free memory for "c" */
1047 * usb_remove_config() - remove a configuration from a device.
1048 * @cdev: wraps the USB gadget
1049 * @config: the configuration
1051 * Drivers must call usb_gadget_disconnect before calling this function
1052 * to disconnect the device from the host and make sure the host will not
1053 * try to enumerate the device while we are changing the config list.
1055 void usb_remove_config(struct usb_composite_dev *cdev,
1056 struct usb_configuration *config)
1058 unsigned long flags;
1060 spin_lock_irqsave(&cdev->lock, flags);
1062 if (cdev->config == config)
1065 spin_unlock_irqrestore(&cdev->lock, flags);
1067 remove_config(cdev, config);
1070 /*-------------------------------------------------------------------------*/
1072 /* We support strings in multiple languages ... string descriptor zero
1073 * says which languages are supported. The typical case will be that
1074 * only one language (probably English) is used, with i18n handled on
1078 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1080 const struct usb_gadget_strings *s;
1086 language = cpu_to_le16(s->language);
1087 for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
1088 if (*tmp == language)
1097 static int lookup_string(
1098 struct usb_gadget_strings **sp,
1104 struct usb_gadget_strings *s;
1109 if (s->language != language)
1111 value = usb_gadget_get_string(s, id, buf);
1118 static int get_string(struct usb_composite_dev *cdev,
1119 void *buf, u16 language, int id)
1121 struct usb_composite_driver *composite = cdev->driver;
1122 struct usb_gadget_string_container *uc;
1123 struct usb_configuration *c;
1124 struct usb_function *f;
1127 /* Yes, not only is USB's i18n support probably more than most
1128 * folk will ever care about ... also, it's all supported here.
1129 * (Except for UTF8 support for Unicode's "Astral Planes".)
1132 /* 0 == report all available language codes */
1134 struct usb_string_descriptor *s = buf;
1135 struct usb_gadget_strings **sp;
1138 s->bDescriptorType = USB_DT_STRING;
1140 sp = composite->strings;
1142 collect_langs(sp, s->wData);
1144 list_for_each_entry(c, &cdev->configs, list) {
1147 collect_langs(sp, s->wData);
1149 list_for_each_entry(f, &c->functions, list) {
1152 collect_langs(sp, s->wData);
1155 list_for_each_entry(uc, &cdev->gstrings, list) {
1156 struct usb_gadget_strings **sp;
1158 sp = get_containers_gs(uc);
1159 collect_langs(sp, s->wData);
1162 for (len = 0; len <= USB_MAX_STRING_LEN && s->wData[len]; len++)
1167 s->bLength = 2 * (len + 1);
1171 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1172 struct usb_os_string *b = buf;
1173 b->bLength = sizeof(*b);
1174 b->bDescriptorType = USB_DT_STRING;
1176 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1177 "qwSignature size must be equal to qw_sign");
1178 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1179 b->bMS_VendorCode = cdev->b_vendor_code;
1184 list_for_each_entry(uc, &cdev->gstrings, list) {
1185 struct usb_gadget_strings **sp;
1187 sp = get_containers_gs(uc);
1188 len = lookup_string(sp, buf, language, id);
1193 /* String IDs are device-scoped, so we look up each string
1194 * table we're told about. These lookups are infrequent;
1195 * simpler-is-better here.
1197 if (composite->strings) {
1198 len = lookup_string(composite->strings, buf, language, id);
1202 list_for_each_entry(c, &cdev->configs, list) {
1204 len = lookup_string(c->strings, buf, language, id);
1208 list_for_each_entry(f, &c->functions, list) {
1211 len = lookup_string(f->strings, buf, language, id);
1220 * usb_string_id() - allocate an unused string ID
1221 * @cdev: the device whose string descriptor IDs are being allocated
1222 * Context: single threaded during gadget setup
1224 * @usb_string_id() is called from bind() callbacks to allocate
1225 * string IDs. Drivers for functions, configurations, or gadgets will
1226 * then store that ID in the appropriate descriptors and string table.
1228 * All string identifier should be allocated using this,
1229 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1230 * that for example different functions don't wrongly assign different
1231 * meanings to the same identifier.
1233 int usb_string_id(struct usb_composite_dev *cdev)
1235 if (cdev->next_string_id < 254) {
1236 /* string id 0 is reserved by USB spec for list of
1237 * supported languages */
1238 /* 255 reserved as well? -- mina86 */
1239 cdev->next_string_id++;
1240 return cdev->next_string_id;
1244 EXPORT_SYMBOL_GPL(usb_string_id);
1247 * usb_string_ids() - allocate unused string IDs in batch
1248 * @cdev: the device whose string descriptor IDs are being allocated
1249 * @str: an array of usb_string objects to assign numbers to
1250 * Context: single threaded during gadget setup
1252 * @usb_string_ids() is called from bind() callbacks to allocate
1253 * string IDs. Drivers for functions, configurations, or gadgets will
1254 * then copy IDs from the string table to the appropriate descriptors
1255 * and string table for other languages.
1257 * All string identifier should be allocated using this,
1258 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1259 * example different functions don't wrongly assign different meanings
1260 * to the same identifier.
1262 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1264 int next = cdev->next_string_id;
1266 for (; str->s; ++str) {
1267 if (unlikely(next >= 254))
1272 cdev->next_string_id = next;
1276 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1278 static struct usb_gadget_string_container *copy_gadget_strings(
1279 struct usb_gadget_strings **sp, unsigned n_gstrings,
1282 struct usb_gadget_string_container *uc;
1283 struct usb_gadget_strings **gs_array;
1284 struct usb_gadget_strings *gs;
1285 struct usb_string *s;
1292 mem += sizeof(void *) * (n_gstrings + 1);
1293 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1294 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1295 uc = kmalloc(mem, GFP_KERNEL);
1297 return ERR_PTR(-ENOMEM);
1298 gs_array = get_containers_gs(uc);
1300 stash += sizeof(void *) * (n_gstrings + 1);
1301 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1302 struct usb_string *org_s;
1304 gs_array[n_gs] = stash;
1305 gs = gs_array[n_gs];
1306 stash += sizeof(struct usb_gadget_strings);
1307 gs->language = sp[n_gs]->language;
1308 gs->strings = stash;
1309 org_s = sp[n_gs]->strings;
1311 for (n_s = 0; n_s < n_strings; n_s++) {
1313 stash += sizeof(struct usb_string);
1322 stash += sizeof(struct usb_string);
1325 gs_array[n_gs] = NULL;
1330 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1331 * @cdev: the device whose string descriptor IDs are being allocated
1333 * @sp: an array of usb_gadget_strings to attach.
1334 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1336 * This function will create a deep copy of usb_gadget_strings and usb_string
1337 * and attach it to the cdev. The actual string (usb_string.s) will not be
1338 * copied but only a referenced will be made. The struct usb_gadget_strings
1339 * array may contain multiple languages and should be NULL terminated.
1340 * The ->language pointer of each struct usb_gadget_strings has to contain the
1341 * same amount of entries.
1342 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1343 * usb_string entry of es-ES contains the translation of the first usb_string
1344 * entry of en-US. Therefore both entries become the same id assign.
1346 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1347 struct usb_gadget_strings **sp, unsigned n_strings)
1349 struct usb_gadget_string_container *uc;
1350 struct usb_gadget_strings **n_gs;
1351 unsigned n_gstrings = 0;
1355 for (i = 0; sp[i]; i++)
1359 return ERR_PTR(-EINVAL);
1361 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1363 return ERR_CAST(uc);
1365 n_gs = get_containers_gs(uc);
1366 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1370 for (i = 1; i < n_gstrings; i++) {
1371 struct usb_string *m_s;
1372 struct usb_string *s;
1375 m_s = n_gs[0]->strings;
1376 s = n_gs[i]->strings;
1377 for (n = 0; n < n_strings; n++) {
1383 list_add_tail(&uc->list, &cdev->gstrings);
1384 return n_gs[0]->strings;
1387 return ERR_PTR(ret);
1389 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1392 * usb_string_ids_n() - allocate unused string IDs in batch
1393 * @c: the device whose string descriptor IDs are being allocated
1394 * @n: number of string IDs to allocate
1395 * Context: single threaded during gadget setup
1397 * Returns the first requested ID. This ID and next @n-1 IDs are now
1398 * valid IDs. At least provided that @n is non-zero because if it
1399 * is, returns last requested ID which is now very useful information.
1401 * @usb_string_ids_n() is called from bind() callbacks to allocate
1402 * string IDs. Drivers for functions, configurations, or gadgets will
1403 * then store that ID in the appropriate descriptors and string table.
1405 * All string identifier should be allocated using this,
1406 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1407 * example different functions don't wrongly assign different meanings
1408 * to the same identifier.
1410 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1412 unsigned next = c->next_string_id;
1413 if (unlikely(n > 254 || (unsigned)next + n > 254))
1415 c->next_string_id += n;
1418 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1420 /*-------------------------------------------------------------------------*/
1422 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1424 struct usb_composite_dev *cdev;
1426 if (req->status || req->actual != req->length)
1427 DBG((struct usb_composite_dev *) ep->driver_data,
1428 "setup complete --> %d, %d/%d\n",
1429 req->status, req->actual, req->length);
1432 * REVIST The same ep0 requests are shared with function drivers
1433 * so they don't have to maintain the same ->complete() stubs.
1435 * Because of that, we need to check for the validity of ->context
1436 * here, even though we know we've set it to something useful.
1441 cdev = req->context;
1443 if (cdev->req == req)
1444 cdev->setup_pending = false;
1445 else if (cdev->os_desc_req == req)
1446 cdev->os_desc_pending = false;
1448 WARN(1, "unknown request %p\n", req);
1451 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1452 struct usb_request *req, gfp_t gfp_flags)
1456 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1458 if (cdev->req == req)
1459 cdev->setup_pending = true;
1460 else if (cdev->os_desc_req == req)
1461 cdev->os_desc_pending = true;
1463 WARN(1, "unknown request %p\n", req);
1469 static int count_ext_compat(struct usb_configuration *c)
1474 for (i = 0; i < c->next_interface_id; ++i) {
1475 struct usb_function *f;
1478 f = c->interface[i];
1479 for (j = 0; j < f->os_desc_n; ++j) {
1480 struct usb_os_desc *d;
1482 if (i != f->os_desc_table[j].if_id)
1484 d = f->os_desc_table[j].os_desc;
1485 if (d && d->ext_compat_id)
1493 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1498 for (i = 0; i < c->next_interface_id; ++i) {
1499 struct usb_function *f;
1502 f = c->interface[i];
1503 for (j = 0; j < f->os_desc_n; ++j) {
1504 struct usb_os_desc *d;
1506 if (i != f->os_desc_table[j].if_id)
1508 d = f->os_desc_table[j].os_desc;
1509 if (d && d->ext_compat_id) {
1512 memcpy(buf, d->ext_compat_id, 16);
1520 if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1528 static int count_ext_prop(struct usb_configuration *c, int interface)
1530 struct usb_function *f;
1533 f = c->interface[interface];
1534 for (j = 0; j < f->os_desc_n; ++j) {
1535 struct usb_os_desc *d;
1537 if (interface != f->os_desc_table[j].if_id)
1539 d = f->os_desc_table[j].os_desc;
1540 if (d && d->ext_compat_id)
1541 return d->ext_prop_count;
1546 static int len_ext_prop(struct usb_configuration *c, int interface)
1548 struct usb_function *f;
1549 struct usb_os_desc *d;
1552 res = 10; /* header length */
1553 f = c->interface[interface];
1554 for (j = 0; j < f->os_desc_n; ++j) {
1555 if (interface != f->os_desc_table[j].if_id)
1557 d = f->os_desc_table[j].os_desc;
1559 return min(res + d->ext_prop_len, 4096);
1564 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1566 struct usb_function *f;
1567 struct usb_os_desc *d;
1568 struct usb_os_desc_ext_prop *ext_prop;
1569 int j, count, n, ret;
1571 f = c->interface[interface];
1572 count = 10; /* header length */
1573 for (j = 0; j < f->os_desc_n; ++j) {
1574 if (interface != f->os_desc_table[j].if_id)
1576 d = f->os_desc_table[j].os_desc;
1578 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1579 n = ext_prop->data_len +
1580 ext_prop->name_len + 14;
1581 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1583 usb_ext_prop_put_size(buf, n);
1584 usb_ext_prop_put_type(buf, ext_prop->type);
1585 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1586 ext_prop->name_len);
1589 switch (ext_prop->type) {
1590 case USB_EXT_PROP_UNICODE:
1591 case USB_EXT_PROP_UNICODE_ENV:
1592 case USB_EXT_PROP_UNICODE_LINK:
1593 usb_ext_prop_put_unicode(buf, ret,
1595 ext_prop->data_len);
1597 case USB_EXT_PROP_BINARY:
1598 usb_ext_prop_put_binary(buf, ret,
1600 ext_prop->data_len);
1602 case USB_EXT_PROP_LE32:
1603 /* not implemented */
1604 case USB_EXT_PROP_BE32:
1605 /* not implemented */
1618 * The setup() callback implements all the ep0 functionality that's
1619 * not handled lower down, in hardware or the hardware driver(like
1620 * device and endpoint feature flags, and their status). It's all
1621 * housekeeping for the gadget function we're implementing. Most of
1622 * the work is in config and function specific setup.
1625 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1627 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1628 struct usb_request *req = cdev->req;
1629 int value = -EOPNOTSUPP;
1631 u16 w_index = le16_to_cpu(ctrl->wIndex);
1632 u8 intf = w_index & 0xFF;
1633 u16 w_value = le16_to_cpu(ctrl->wValue);
1634 u16 w_length = le16_to_cpu(ctrl->wLength);
1635 struct usb_function *f = NULL;
1638 if (w_length > USB_COMP_EP0_BUFSIZ) {
1639 if (ctrl->bRequestType & USB_DIR_IN) {
1640 /* Cast away the const, we are going to overwrite on purpose. */
1641 __le16 *temp = (__le16 *)&ctrl->wLength;
1643 *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
1644 w_length = USB_COMP_EP0_BUFSIZ;
1650 /* partial re-init of the response message; the function or the
1651 * gadget might need to intercept e.g. a control-OUT completion
1652 * when we delegate to it.
1655 req->context = cdev;
1656 req->complete = composite_setup_complete;
1658 gadget->ep0->driver_data = cdev;
1661 * Don't let non-standard requests match any of the cases below
1664 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1667 switch (ctrl->bRequest) {
1669 /* we handle all standard USB descriptors */
1670 case USB_REQ_GET_DESCRIPTOR:
1671 if (ctrl->bRequestType != USB_DIR_IN)
1673 switch (w_value >> 8) {
1676 cdev->desc.bNumConfigurations =
1677 count_configs(cdev, USB_DT_DEVICE);
1678 cdev->desc.bMaxPacketSize0 =
1679 cdev->gadget->ep0->maxpacket;
1680 if (gadget_is_superspeed(gadget)) {
1681 if (gadget->speed >= USB_SPEED_SUPER) {
1682 cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1683 cdev->desc.bMaxPacketSize0 = 9;
1685 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1688 if (gadget->lpm_capable)
1689 cdev->desc.bcdUSB = cpu_to_le16(0x0201);
1691 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1694 value = min(w_length, (u16) sizeof cdev->desc);
1695 memcpy(req->buf, &cdev->desc, value);
1697 case USB_DT_DEVICE_QUALIFIER:
1698 if (!gadget_is_dualspeed(gadget) ||
1699 gadget->speed >= USB_SPEED_SUPER)
1702 value = min_t(int, w_length,
1703 sizeof(struct usb_qualifier_descriptor));
1705 case USB_DT_OTHER_SPEED_CONFIG:
1706 if (!gadget_is_dualspeed(gadget) ||
1707 gadget->speed >= USB_SPEED_SUPER)
1711 value = config_desc(cdev, w_value);
1713 value = min(w_length, (u16) value);
1716 value = get_string(cdev, req->buf,
1717 w_index, w_value & 0xff);
1719 value = min(w_length, (u16) value);
1722 if (gadget_is_superspeed(gadget) ||
1723 gadget->lpm_capable) {
1724 value = bos_desc(cdev);
1725 value = min(w_length, (u16) value);
1729 if (gadget_is_otg(gadget)) {
1730 struct usb_configuration *config;
1731 int otg_desc_len = 0;
1734 config = cdev->config;
1736 config = list_first_entry(
1738 struct usb_configuration, list);
1742 if (gadget->otg_caps &&
1743 (gadget->otg_caps->otg_rev >= 0x0200))
1744 otg_desc_len += sizeof(
1745 struct usb_otg20_descriptor);
1747 otg_desc_len += sizeof(
1748 struct usb_otg_descriptor);
1750 value = min_t(int, w_length, otg_desc_len);
1751 memcpy(req->buf, config->descriptors[0], value);
1757 /* any number of configs can work */
1758 case USB_REQ_SET_CONFIGURATION:
1759 if (ctrl->bRequestType != 0)
1761 if (gadget_is_otg(gadget)) {
1762 if (gadget->a_hnp_support)
1763 DBG(cdev, "HNP available\n");
1764 else if (gadget->a_alt_hnp_support)
1765 DBG(cdev, "HNP on another port\n");
1767 VDBG(cdev, "HNP inactive\n");
1769 spin_lock(&cdev->lock);
1770 value = set_config(cdev, ctrl, w_value);
1771 spin_unlock(&cdev->lock);
1773 case USB_REQ_GET_CONFIGURATION:
1774 if (ctrl->bRequestType != USB_DIR_IN)
1777 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1779 *(u8 *)req->buf = 0;
1780 value = min(w_length, (u16) 1);
1783 /* function drivers must handle get/set altsetting */
1784 case USB_REQ_SET_INTERFACE:
1785 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1787 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1789 f = cdev->config->interface[intf];
1794 * If there's no get_alt() method, we know only altsetting zero
1795 * works. There is no need to check if set_alt() is not NULL
1796 * as we check this in usb_add_function().
1798 if (w_value && !f->get_alt)
1801 spin_lock(&cdev->lock);
1802 value = f->set_alt(f, w_index, w_value);
1803 if (value == USB_GADGET_DELAYED_STATUS) {
1805 "%s: interface %d (%s) requested delayed status\n",
1806 __func__, intf, f->name);
1807 cdev->delayed_status++;
1808 DBG(cdev, "delayed_status count %d\n",
1809 cdev->delayed_status);
1811 spin_unlock(&cdev->lock);
1813 case USB_REQ_GET_INTERFACE:
1814 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1816 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1818 f = cdev->config->interface[intf];
1821 /* lots of interfaces only need altsetting zero... */
1822 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1825 *((u8 *)req->buf) = value;
1826 value = min(w_length, (u16) 1);
1828 case USB_REQ_GET_STATUS:
1829 if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1830 (w_index == OTG_STS_SELECTOR)) {
1831 if (ctrl->bRequestType != (USB_DIR_IN |
1834 *((u8 *)req->buf) = gadget->host_request_flag;
1840 * USB 3.0 additions:
1841 * Function driver should handle get_status request. If such cb
1842 * wasn't supplied we respond with default value = 0
1843 * Note: function driver should supply such cb only for the
1844 * first interface of the function
1846 if (!gadget_is_superspeed(gadget))
1848 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1850 value = 2; /* This is the length of the get_status reply */
1851 put_unaligned_le16(0, req->buf);
1852 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1854 f = cdev->config->interface[intf];
1857 status = f->get_status ? f->get_status(f) : 0;
1860 put_unaligned_le16(status & 0x0000ffff, req->buf);
1863 * Function drivers should handle SetFeature/ClearFeature
1864 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1865 * only for the first interface of the function
1867 case USB_REQ_CLEAR_FEATURE:
1868 case USB_REQ_SET_FEATURE:
1869 if (!gadget_is_superspeed(gadget))
1871 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1874 case USB_INTRF_FUNC_SUSPEND:
1875 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1877 f = cdev->config->interface[intf];
1881 if (f->func_suspend)
1882 value = f->func_suspend(f, w_index >> 8);
1885 "func_suspend() returned error %d\n",
1895 * OS descriptors handling
1897 if (cdev->use_os_string && cdev->os_desc_config &&
1898 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1899 ctrl->bRequest == cdev->b_vendor_code) {
1900 struct usb_request *req;
1901 struct usb_configuration *os_desc_cfg;
1906 req = cdev->os_desc_req;
1907 req->context = cdev;
1908 req->complete = composite_setup_complete;
1910 os_desc_cfg = cdev->os_desc_config;
1911 w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1912 memset(buf, 0, w_length);
1914 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1915 case USB_RECIP_DEVICE:
1916 if (w_index != 0x4 || (w_value >> 8))
1919 if (w_length == 0x10) {
1920 /* Number of ext compat interfaces */
1921 count = count_ext_compat(os_desc_cfg);
1923 count *= 24; /* 24 B/ext compat desc */
1924 count += 16; /* header */
1925 put_unaligned_le32(count, buf);
1928 /* "extended compatibility ID"s */
1929 count = count_ext_compat(os_desc_cfg);
1931 count *= 24; /* 24 B/ext compat desc */
1932 count += 16; /* header */
1933 put_unaligned_le32(count, buf);
1935 value = fill_ext_compat(os_desc_cfg, buf);
1936 value = min_t(u16, w_length, value);
1939 case USB_RECIP_INTERFACE:
1940 if (w_index != 0x5 || (w_value >> 8))
1942 interface = w_value & 0xFF;
1944 if (w_length == 0x0A) {
1945 count = count_ext_prop(os_desc_cfg,
1947 put_unaligned_le16(count, buf + 8);
1948 count = len_ext_prop(os_desc_cfg,
1950 put_unaligned_le32(count, buf);
1954 count = count_ext_prop(os_desc_cfg,
1956 put_unaligned_le16(count, buf + 8);
1957 count = len_ext_prop(os_desc_cfg,
1959 put_unaligned_le32(count, buf);
1961 value = fill_ext_prop(os_desc_cfg,
1965 value = min_t(u16, w_length, value);
1971 req->length = value;
1972 req->context = cdev;
1973 req->zero = value < w_length;
1974 value = composite_ep0_queue(cdev, req,
1977 DBG(cdev, "ep_queue --> %d\n", value);
1979 composite_setup_complete(gadget->ep0,
1987 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1988 ctrl->bRequestType, ctrl->bRequest,
1989 w_value, w_index, w_length);
1991 /* functions always handle their interfaces and endpoints...
1992 * punt other recipients (other, WUSB, ...) to the current
1993 * configuration code.
1996 list_for_each_entry(f, &cdev->config->functions, list)
1998 f->req_match(f, ctrl, false))
2001 struct usb_configuration *c;
2002 list_for_each_entry(c, &cdev->configs, list)
2003 list_for_each_entry(f, &c->functions, list)
2005 f->req_match(f, ctrl, true))
2010 switch (ctrl->bRequestType & USB_RECIP_MASK) {
2011 case USB_RECIP_INTERFACE:
2012 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2014 f = cdev->config->interface[intf];
2017 case USB_RECIP_ENDPOINT:
2020 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
2021 list_for_each_entry(f, &cdev->config->functions, list) {
2022 if (test_bit(endp, f->endpoints))
2025 if (&f->list == &cdev->config->functions)
2031 value = f->setup(f, ctrl);
2033 struct usb_configuration *c;
2039 /* try current config's setup */
2041 value = c->setup(c, ctrl);
2045 /* try the only function in the current config */
2046 if (!list_is_singular(&c->functions))
2048 f = list_first_entry(&c->functions, struct usb_function,
2051 value = f->setup(f, ctrl);
2057 /* respond with data transfer before status phase? */
2058 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2059 req->length = value;
2060 req->context = cdev;
2061 req->zero = value < w_length;
2062 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2064 DBG(cdev, "ep_queue --> %d\n", value);
2066 composite_setup_complete(gadget->ep0, req);
2068 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2070 "%s: Delayed status not supported for w_length != 0",
2075 /* device either stalls (value < 0) or reports success */
2079 void composite_disconnect(struct usb_gadget *gadget)
2081 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2082 unsigned long flags;
2084 /* REVISIT: should we have config and device level
2085 * disconnect callbacks?
2087 spin_lock_irqsave(&cdev->lock, flags);
2088 cdev->suspended = 0;
2091 if (cdev->driver->disconnect)
2092 cdev->driver->disconnect(cdev);
2093 spin_unlock_irqrestore(&cdev->lock, flags);
2096 /*-------------------------------------------------------------------------*/
2098 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2101 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2102 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2104 return sprintf(buf, "%d\n", cdev->suspended);
2106 static DEVICE_ATTR_RO(suspended);
2108 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2110 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2111 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2112 struct usb_string *dev_str = gstr->strings;
2114 /* composite_disconnect() must already have been called
2115 * by the underlying peripheral controller driver!
2116 * so there's no i/o concurrency that could affect the
2117 * state protected by cdev->lock.
2119 WARN_ON(cdev->config);
2121 while (!list_empty(&cdev->configs)) {
2122 struct usb_configuration *c;
2123 c = list_first_entry(&cdev->configs,
2124 struct usb_configuration, list);
2125 remove_config(cdev, c);
2127 if (cdev->driver->unbind && unbind_driver)
2128 cdev->driver->unbind(cdev);
2130 composite_dev_cleanup(cdev);
2132 if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2133 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2135 kfree(cdev->def_manufacturer);
2137 set_gadget_data(gadget, NULL);
2140 static void composite_unbind(struct usb_gadget *gadget)
2142 __composite_unbind(gadget, true);
2145 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2146 const struct usb_device_descriptor *old)
2156 * these variables may have been set in
2157 * usb_composite_overwrite_options()
2159 idVendor = new->idVendor;
2160 idProduct = new->idProduct;
2161 bcdDevice = new->bcdDevice;
2162 iSerialNumber = new->iSerialNumber;
2163 iManufacturer = new->iManufacturer;
2164 iProduct = new->iProduct;
2168 new->idVendor = idVendor;
2170 new->idProduct = idProduct;
2172 new->bcdDevice = bcdDevice;
2174 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2176 new->iSerialNumber = iSerialNumber;
2178 new->iManufacturer = iManufacturer;
2180 new->iProduct = iProduct;
2183 int composite_dev_prepare(struct usb_composite_driver *composite,
2184 struct usb_composite_dev *cdev)
2186 struct usb_gadget *gadget = cdev->gadget;
2189 /* preallocate control response and buffer */
2190 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2194 cdev->req->buf = kzalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2195 if (!cdev->req->buf)
2198 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2202 cdev->req->complete = composite_setup_complete;
2203 cdev->req->context = cdev;
2204 gadget->ep0->driver_data = cdev;
2206 cdev->driver = composite;
2209 * As per USB compliance update, a device that is actively drawing
2210 * more than 100mA from USB must report itself as bus-powered in
2211 * the GetStatus(DEVICE) call.
2213 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2214 usb_gadget_set_selfpowered(gadget);
2216 /* interface and string IDs start at zero via kzalloc.
2217 * we force endpoints to start unassigned; few controller
2218 * drivers will zero ep->driver_data.
2220 usb_ep_autoconfig_reset(gadget);
2223 kfree(cdev->req->buf);
2225 usb_ep_free_request(gadget->ep0, cdev->req);
2230 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2235 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2236 if (!cdev->os_desc_req) {
2241 cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2243 if (!cdev->os_desc_req->buf) {
2245 usb_ep_free_request(ep0, cdev->os_desc_req);
2248 cdev->os_desc_req->context = cdev;
2249 cdev->os_desc_req->complete = composite_setup_complete;
2254 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2256 struct usb_gadget_string_container *uc, *tmp;
2258 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2259 list_del(&uc->list);
2262 if (cdev->os_desc_req) {
2263 if (cdev->os_desc_pending)
2264 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2266 kfree(cdev->os_desc_req->buf);
2267 cdev->os_desc_req->buf = NULL;
2268 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2269 cdev->os_desc_req = NULL;
2272 if (cdev->setup_pending)
2273 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2275 kfree(cdev->req->buf);
2276 cdev->req->buf = NULL;
2277 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2280 cdev->next_string_id = 0;
2281 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2284 static int composite_bind(struct usb_gadget *gadget,
2285 struct usb_gadget_driver *gdriver)
2287 struct usb_composite_dev *cdev;
2288 struct usb_composite_driver *composite = to_cdriver(gdriver);
2289 int status = -ENOMEM;
2291 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2295 spin_lock_init(&cdev->lock);
2296 cdev->gadget = gadget;
2297 set_gadget_data(gadget, cdev);
2298 INIT_LIST_HEAD(&cdev->configs);
2299 INIT_LIST_HEAD(&cdev->gstrings);
2301 status = composite_dev_prepare(composite, cdev);
2305 /* composite gadget needs to assign strings for whole device (like
2306 * serial number), register function drivers, potentially update
2307 * power state and consumption, etc
2309 status = composite->bind(cdev);
2313 if (cdev->use_os_string) {
2314 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2319 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2321 /* has userspace failed to provide a serial number? */
2322 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2323 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2325 INFO(cdev, "%s ready\n", composite->name);
2329 __composite_unbind(gadget, false);
2333 /*-------------------------------------------------------------------------*/
2335 void composite_suspend(struct usb_gadget *gadget)
2337 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2338 struct usb_function *f;
2340 /* REVISIT: should we have config level
2341 * suspend/resume callbacks?
2343 DBG(cdev, "suspend\n");
2345 list_for_each_entry(f, &cdev->config->functions, list) {
2350 if (cdev->driver->suspend)
2351 cdev->driver->suspend(cdev);
2353 cdev->suspended = 1;
2355 usb_gadget_set_selfpowered(gadget);
2356 usb_gadget_vbus_draw(gadget, 2);
2359 void composite_resume(struct usb_gadget *gadget)
2361 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2362 struct usb_function *f;
2365 /* REVISIT: should we have config level
2366 * suspend/resume callbacks?
2368 DBG(cdev, "resume\n");
2369 if (cdev->driver->resume)
2370 cdev->driver->resume(cdev);
2372 list_for_each_entry(f, &cdev->config->functions, list) {
2377 maxpower = cdev->config->MaxPower ?
2378 cdev->config->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
2379 if (gadget->speed < USB_SPEED_SUPER)
2380 maxpower = min(maxpower, 500U);
2382 maxpower = min(maxpower, 900U);
2384 if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2385 usb_gadget_clear_selfpowered(gadget);
2387 usb_gadget_vbus_draw(gadget, maxpower);
2390 cdev->suspended = 0;
2393 /*-------------------------------------------------------------------------*/
2395 static const struct usb_gadget_driver composite_driver_template = {
2396 .bind = composite_bind,
2397 .unbind = composite_unbind,
2399 .setup = composite_setup,
2400 .reset = composite_disconnect,
2401 .disconnect = composite_disconnect,
2403 .suspend = composite_suspend,
2404 .resume = composite_resume,
2407 .owner = THIS_MODULE,
2412 * usb_composite_probe() - register a composite driver
2413 * @driver: the driver to register
2415 * Context: single threaded during gadget setup
2417 * This function is used to register drivers using the composite driver
2418 * framework. The return value is zero, or a negative errno value.
2419 * Those values normally come from the driver's @bind method, which does
2420 * all the work of setting up the driver to match the hardware.
2422 * On successful return, the gadget is ready to respond to requests from
2423 * the host, unless one of its components invokes usb_gadget_disconnect()
2424 * while it was binding. That would usually be done in order to wait for
2425 * some userspace participation.
2427 int usb_composite_probe(struct usb_composite_driver *driver)
2429 struct usb_gadget_driver *gadget_driver;
2431 if (!driver || !driver->dev || !driver->bind)
2435 driver->name = "composite";
2437 driver->gadget_driver = composite_driver_template;
2438 gadget_driver = &driver->gadget_driver;
2440 gadget_driver->function = (char *) driver->name;
2441 gadget_driver->driver.name = driver->name;
2442 gadget_driver->max_speed = driver->max_speed;
2444 return usb_gadget_probe_driver(gadget_driver);
2446 EXPORT_SYMBOL_GPL(usb_composite_probe);
2449 * usb_composite_unregister() - unregister a composite driver
2450 * @driver: the driver to unregister
2452 * This function is used to unregister drivers using the composite
2455 void usb_composite_unregister(struct usb_composite_driver *driver)
2457 usb_gadget_unregister_driver(&driver->gadget_driver);
2459 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2462 * usb_composite_setup_continue() - Continue with the control transfer
2463 * @cdev: the composite device who's control transfer was kept waiting
2465 * This function must be called by the USB function driver to continue
2466 * with the control transfer's data/status stage in case it had requested to
2467 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2468 * can request the composite framework to delay the setup request's data/status
2469 * stages by returning USB_GADGET_DELAYED_STATUS.
2471 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2474 struct usb_request *req = cdev->req;
2475 unsigned long flags;
2477 DBG(cdev, "%s\n", __func__);
2478 spin_lock_irqsave(&cdev->lock, flags);
2480 if (cdev->delayed_status == 0) {
2481 WARN(cdev, "%s: Unexpected call\n", __func__);
2483 } else if (--cdev->delayed_status == 0) {
2484 DBG(cdev, "%s: Completing delayed status\n", __func__);
2486 req->context = cdev;
2487 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2489 DBG(cdev, "ep_queue --> %d\n", value);
2491 composite_setup_complete(cdev->gadget->ep0, req);
2495 spin_unlock_irqrestore(&cdev->lock, flags);
2497 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2499 static char *composite_default_mfr(struct usb_gadget *gadget)
2501 return kasprintf(GFP_KERNEL, "%s %s with %s", init_utsname()->sysname,
2502 init_utsname()->release, gadget->name);
2505 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2506 struct usb_composite_overwrite *covr)
2508 struct usb_device_descriptor *desc = &cdev->desc;
2509 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2510 struct usb_string *dev_str = gstr->strings;
2513 desc->idVendor = cpu_to_le16(covr->idVendor);
2515 if (covr->idProduct)
2516 desc->idProduct = cpu_to_le16(covr->idProduct);
2518 if (covr->bcdDevice)
2519 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2521 if (covr->serial_number) {
2522 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2523 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2525 if (covr->manufacturer) {
2526 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2527 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2529 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2530 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2531 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2532 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2535 if (covr->product) {
2536 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2537 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2540 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2542 MODULE_LICENSE("GPL");
2543 MODULE_AUTHOR("David Brownell");