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) & 0x7ff;
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(_ep->desc) & 0x1800) >> 11) + 1;
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 EXPORT_SYMBOL_GPL(usb_remove_function);
369 * usb_function_deactivate - prevent function and gadget enumeration
370 * @function: the function that isn't yet ready to respond
372 * Blocks response of the gadget driver to host enumeration by
373 * preventing the data line pullup from being activated. This is
374 * normally called during @bind() processing to change from the
375 * initial "ready to respond" state, or when a required resource
378 * For example, drivers that serve as a passthrough to a userspace
379 * daemon can block enumeration unless that daemon (such as an OBEX,
380 * MTP, or print server) is ready to handle host requests.
382 * Not all systems support software control of their USB peripheral
385 * Returns zero on success, else negative errno.
387 int usb_function_deactivate(struct usb_function *function)
389 struct usb_composite_dev *cdev = function->config->cdev;
393 spin_lock_irqsave(&cdev->lock, flags);
395 if (cdev->deactivations == 0) {
396 spin_unlock_irqrestore(&cdev->lock, flags);
397 status = usb_gadget_deactivate(cdev->gadget);
398 spin_lock_irqsave(&cdev->lock, flags);
401 cdev->deactivations++;
403 spin_unlock_irqrestore(&cdev->lock, flags);
406 EXPORT_SYMBOL_GPL(usb_function_deactivate);
409 * usb_function_activate - allow function and gadget enumeration
410 * @function: function on which usb_function_activate() was called
412 * Reverses effect of usb_function_deactivate(). If no more functions
413 * are delaying their activation, the gadget driver will respond to
414 * host enumeration procedures.
416 * Returns zero on success, else negative errno.
418 int usb_function_activate(struct usb_function *function)
420 struct usb_composite_dev *cdev = function->config->cdev;
424 spin_lock_irqsave(&cdev->lock, flags);
426 if (WARN_ON(cdev->deactivations == 0))
429 cdev->deactivations--;
430 if (cdev->deactivations == 0) {
431 spin_unlock_irqrestore(&cdev->lock, flags);
432 status = usb_gadget_activate(cdev->gadget);
433 spin_lock_irqsave(&cdev->lock, flags);
437 spin_unlock_irqrestore(&cdev->lock, flags);
440 EXPORT_SYMBOL_GPL(usb_function_activate);
443 * usb_interface_id() - allocate an unused interface ID
444 * @config: configuration associated with the interface
445 * @function: function handling the interface
446 * Context: single threaded during gadget setup
448 * usb_interface_id() is called from usb_function.bind() callbacks to
449 * allocate new interface IDs. The function driver will then store that
450 * ID in interface, association, CDC union, and other descriptors. It
451 * will also handle any control requests targeted at that interface,
452 * particularly changing its altsetting via set_alt(). There may
453 * also be class-specific or vendor-specific requests to handle.
455 * All interface identifier should be allocated using this routine, to
456 * ensure that for example different functions don't wrongly assign
457 * different meanings to the same identifier. Note that since interface
458 * identifiers are configuration-specific, functions used in more than
459 * one configuration (or more than once in a given configuration) need
460 * multiple versions of the relevant descriptors.
462 * Returns the interface ID which was allocated; or -ENODEV if no
463 * more interface IDs can be allocated.
465 int usb_interface_id(struct usb_configuration *config,
466 struct usb_function *function)
468 unsigned id = config->next_interface_id;
470 if (id < MAX_CONFIG_INTERFACES) {
471 config->interface[id] = function;
472 config->next_interface_id = id + 1;
477 EXPORT_SYMBOL_GPL(usb_interface_id);
479 static u8 encode_bMaxPower(enum usb_device_speed speed,
480 struct usb_configuration *c)
484 if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
487 val = CONFIG_USB_GADGET_VBUS_DRAW;
490 if (speed < USB_SPEED_SUPER)
491 return min(val, 500U) / 2;
494 * USB 3.x supports up to 900mA, but since 900 isn't divisible
495 * by 8 the integral division will effectively cap to 896mA.
497 return min(val, 900U) / 8;
500 static int config_buf(struct usb_configuration *config,
501 enum usb_device_speed speed, void *buf, u8 type)
503 struct usb_config_descriptor *c = buf;
504 void *next = buf + USB_DT_CONFIG_SIZE;
506 struct usb_function *f;
509 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
510 /* write the config descriptor */
512 c->bLength = USB_DT_CONFIG_SIZE;
513 c->bDescriptorType = type;
514 /* wTotalLength is written later */
515 c->bNumInterfaces = config->next_interface_id;
516 c->bConfigurationValue = config->bConfigurationValue;
517 c->iConfiguration = config->iConfiguration;
518 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
519 c->bMaxPower = encode_bMaxPower(speed, config);
521 /* There may be e.g. OTG descriptors */
522 if (config->descriptors) {
523 status = usb_descriptor_fillbuf(next, len,
524 config->descriptors);
531 /* add each function's descriptors */
532 list_for_each_entry(f, &config->functions, list) {
533 struct usb_descriptor_header **descriptors;
535 descriptors = function_descriptors(f, speed);
538 status = usb_descriptor_fillbuf(next, len,
539 (const struct usb_descriptor_header **) descriptors);
547 c->wTotalLength = cpu_to_le16(len);
551 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
553 struct usb_gadget *gadget = cdev->gadget;
554 struct usb_configuration *c;
555 struct list_head *pos;
556 u8 type = w_value >> 8;
557 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
559 if (gadget->speed >= USB_SPEED_SUPER)
560 speed = gadget->speed;
561 else if (gadget_is_dualspeed(gadget)) {
563 if (gadget->speed == USB_SPEED_HIGH)
565 if (type == USB_DT_OTHER_SPEED_CONFIG)
568 speed = USB_SPEED_HIGH;
572 /* This is a lookup by config *INDEX* */
575 pos = &cdev->configs;
576 c = cdev->os_desc_config;
580 while ((pos = pos->next) != &cdev->configs) {
581 c = list_entry(pos, typeof(*c), list);
583 /* skip OS Descriptors config which is handled separately */
584 if (c == cdev->os_desc_config)
588 /* ignore configs that won't work at this speed */
590 case USB_SPEED_SUPER_PLUS:
591 if (!c->superspeed_plus)
594 case USB_SPEED_SUPER:
608 return config_buf(c, speed, cdev->req->buf, type);
614 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
616 struct usb_gadget *gadget = cdev->gadget;
617 struct usb_configuration *c;
623 if (gadget_is_dualspeed(gadget)) {
624 if (gadget->speed == USB_SPEED_HIGH)
626 if (gadget->speed == USB_SPEED_SUPER)
628 if (gadget->speed == USB_SPEED_SUPER_PLUS)
630 if (type == USB_DT_DEVICE_QUALIFIER)
633 list_for_each_entry(c, &cdev->configs, list) {
634 /* ignore configs that won't work at this speed */
636 if (!c->superspeed_plus)
654 * bos_desc() - prepares the BOS descriptor.
655 * @cdev: pointer to usb_composite device to generate the bos
658 * This function generates the BOS (Binary Device Object)
659 * descriptor and its device capabilities descriptors. The BOS
660 * descriptor should be supported by a SuperSpeed device.
662 static int bos_desc(struct usb_composite_dev *cdev)
664 struct usb_ext_cap_descriptor *usb_ext;
665 struct usb_ss_cap_descriptor *ss_cap;
666 struct usb_dcd_config_params dcd_config_params;
667 struct usb_bos_descriptor *bos = cdev->req->buf;
669 bos->bLength = USB_DT_BOS_SIZE;
670 bos->bDescriptorType = USB_DT_BOS;
672 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
673 bos->bNumDeviceCaps = 0;
676 * A SuperSpeed device shall include the USB2.0 extension descriptor
677 * and shall support LPM when operating in USB2.0 HS mode.
679 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
680 bos->bNumDeviceCaps++;
681 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
682 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
683 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
684 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
685 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
688 * The Superspeed USB Capability descriptor shall be implemented by all
689 * SuperSpeed devices.
691 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
692 bos->bNumDeviceCaps++;
693 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
694 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
695 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
696 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
697 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
698 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
699 USB_FULL_SPEED_OPERATION |
700 USB_HIGH_SPEED_OPERATION |
701 USB_5GBPS_OPERATION);
702 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
704 /* Get Controller configuration */
705 if (cdev->gadget->ops->get_config_params)
706 cdev->gadget->ops->get_config_params(&dcd_config_params);
708 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
709 dcd_config_params.bU2DevExitLat =
710 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
712 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
713 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
715 /* The SuperSpeedPlus USB Device Capability descriptor */
716 if (gadget_is_superspeed_plus(cdev->gadget)) {
717 struct usb_ssp_cap_descriptor *ssp_cap;
719 ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
720 bos->bNumDeviceCaps++;
723 * Report typical values.
726 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
727 ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
728 ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
729 ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
730 ssp_cap->bReserved = 0;
731 ssp_cap->wReserved = 0;
733 /* SSAC = 1 (2 attributes) */
734 ssp_cap->bmAttributes = cpu_to_le32(1);
736 /* Min RX/TX Lane Count = 1 */
737 ssp_cap->wFunctionalitySupport =
738 cpu_to_le16((1 << 8) | (1 << 12));
741 * bmSublinkSpeedAttr[0]:
744 * LP = 1 (SuperSpeedPlus)
747 ssp_cap->bmSublinkSpeedAttr[0] =
748 cpu_to_le32((3 << 4) | (1 << 14) | (0xa << 16));
750 * bmSublinkSpeedAttr[1] =
753 * LP = 1 (SuperSpeedPlus)
756 ssp_cap->bmSublinkSpeedAttr[1] =
757 cpu_to_le32((3 << 4) | (1 << 14) |
758 (0xa << 16) | (1 << 7));
761 return le16_to_cpu(bos->wTotalLength);
764 static void device_qual(struct usb_composite_dev *cdev)
766 struct usb_qualifier_descriptor *qual = cdev->req->buf;
768 qual->bLength = sizeof(*qual);
769 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
770 /* POLICY: same bcdUSB and device type info at both speeds */
771 qual->bcdUSB = cdev->desc.bcdUSB;
772 qual->bDeviceClass = cdev->desc.bDeviceClass;
773 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
774 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
775 /* ASSUME same EP0 fifo size at both speeds */
776 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
777 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
781 /*-------------------------------------------------------------------------*/
783 static void reset_config(struct usb_composite_dev *cdev)
785 struct usb_function *f;
787 DBG(cdev, "reset config\n");
789 list_for_each_entry(f, &cdev->config->functions, list) {
793 bitmap_zero(f->endpoints, 32);
796 cdev->delayed_status = 0;
799 static int set_config(struct usb_composite_dev *cdev,
800 const struct usb_ctrlrequest *ctrl, unsigned number)
802 struct usb_gadget *gadget = cdev->gadget;
803 struct usb_configuration *c = NULL;
804 int result = -EINVAL;
805 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
809 list_for_each_entry(c, &cdev->configs, list) {
810 if (c->bConfigurationValue == number) {
812 * We disable the FDs of the previous
813 * configuration only if the new configuration
824 } else { /* Zero configuration value - need to reset the config */
830 INFO(cdev, "%s config #%d: %s\n",
831 usb_speed_string(gadget->speed),
832 number, c ? c->label : "unconfigured");
837 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
840 /* Initialize all interfaces by setting them to altsetting zero. */
841 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
842 struct usb_function *f = c->interface[tmp];
843 struct usb_descriptor_header **descriptors;
849 * Record which endpoints are used by the function. This is used
850 * to dispatch control requests targeted at that endpoint to the
851 * function's setup callback instead of the current
852 * configuration's setup callback.
854 descriptors = function_descriptors(f, gadget->speed);
856 for (; *descriptors; ++descriptors) {
857 struct usb_endpoint_descriptor *ep;
860 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
863 ep = (struct usb_endpoint_descriptor *)*descriptors;
864 addr = ((ep->bEndpointAddress & 0x80) >> 3)
865 | (ep->bEndpointAddress & 0x0f);
866 set_bit(addr, f->endpoints);
869 result = f->set_alt(f, tmp, 0);
871 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
872 tmp, f->name, f, result);
878 if (result == USB_GADGET_DELAYED_STATUS) {
880 "%s: interface %d (%s) requested delayed status\n",
881 __func__, tmp, f->name);
882 cdev->delayed_status++;
883 DBG(cdev, "delayed_status count %d\n",
884 cdev->delayed_status);
888 /* when we return, be sure our power usage is valid */
889 if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
892 power = CONFIG_USB_GADGET_VBUS_DRAW;
894 if (gadget->speed < USB_SPEED_SUPER)
895 power = min(power, 500U);
897 power = min(power, 900U);
899 if (power <= USB_SELF_POWER_VBUS_MAX_DRAW)
900 usb_gadget_set_selfpowered(gadget);
902 usb_gadget_clear_selfpowered(gadget);
904 usb_gadget_vbus_draw(gadget, power);
905 if (result >= 0 && cdev->delayed_status)
906 result = USB_GADGET_DELAYED_STATUS;
910 int usb_add_config_only(struct usb_composite_dev *cdev,
911 struct usb_configuration *config)
913 struct usb_configuration *c;
915 if (!config->bConfigurationValue)
918 /* Prevent duplicate configuration identifiers */
919 list_for_each_entry(c, &cdev->configs, list) {
920 if (c->bConfigurationValue == config->bConfigurationValue)
925 list_add_tail(&config->list, &cdev->configs);
927 INIT_LIST_HEAD(&config->functions);
928 config->next_interface_id = 0;
929 memset(config->interface, 0, sizeof(config->interface));
933 EXPORT_SYMBOL_GPL(usb_add_config_only);
936 * usb_add_config() - add a configuration to a device.
937 * @cdev: wraps the USB gadget
938 * @config: the configuration, with bConfigurationValue assigned
939 * @bind: the configuration's bind function
940 * Context: single threaded during gadget setup
942 * One of the main tasks of a composite @bind() routine is to
943 * add each of the configurations it supports, using this routine.
945 * This function returns the value of the configuration's @bind(), which
946 * is zero for success else a negative errno value. Binding configurations
947 * assigns global resources including string IDs, and per-configuration
948 * resources such as interface IDs and endpoints.
950 int usb_add_config(struct usb_composite_dev *cdev,
951 struct usb_configuration *config,
952 int (*bind)(struct usb_configuration *))
954 int status = -EINVAL;
959 DBG(cdev, "adding config #%u '%s'/%p\n",
960 config->bConfigurationValue,
961 config->label, config);
963 status = usb_add_config_only(cdev, config);
967 status = bind(config);
969 while (!list_empty(&config->functions)) {
970 struct usb_function *f;
972 f = list_first_entry(&config->functions,
973 struct usb_function, list);
976 DBG(cdev, "unbind function '%s'/%p\n",
978 f->unbind(config, f);
979 /* may free memory for "f" */
982 list_del(&config->list);
987 DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
988 config->bConfigurationValue, config,
989 config->superspeed_plus ? " superplus" : "",
990 config->superspeed ? " super" : "",
991 config->highspeed ? " high" : "",
993 ? (gadget_is_dualspeed(cdev->gadget)
998 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
999 struct usb_function *f = config->interface[i];
1003 DBG(cdev, " interface %d = %s/%p\n",
1008 /* set_alt(), or next bind(), sets up ep->claimed as needed */
1009 usb_ep_autoconfig_reset(cdev->gadget);
1013 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1014 config->bConfigurationValue, status);
1017 EXPORT_SYMBOL_GPL(usb_add_config);
1019 static void remove_config(struct usb_composite_dev *cdev,
1020 struct usb_configuration *config)
1022 while (!list_empty(&config->functions)) {
1023 struct usb_function *f;
1025 f = list_first_entry(&config->functions,
1026 struct usb_function, list);
1029 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
1030 f->unbind(config, f);
1031 /* may free memory for "f" */
1034 list_del(&config->list);
1035 if (config->unbind) {
1036 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
1037 config->unbind(config);
1038 /* may free memory for "c" */
1043 * usb_remove_config() - remove a configuration from a device.
1044 * @cdev: wraps the USB gadget
1045 * @config: the configuration
1047 * Drivers must call usb_gadget_disconnect before calling this function
1048 * to disconnect the device from the host and make sure the host will not
1049 * try to enumerate the device while we are changing the config list.
1051 void usb_remove_config(struct usb_composite_dev *cdev,
1052 struct usb_configuration *config)
1054 unsigned long flags;
1056 spin_lock_irqsave(&cdev->lock, flags);
1058 if (cdev->config == config)
1061 spin_unlock_irqrestore(&cdev->lock, flags);
1063 remove_config(cdev, config);
1066 /*-------------------------------------------------------------------------*/
1068 /* We support strings in multiple languages ... string descriptor zero
1069 * says which languages are supported. The typical case will be that
1070 * only one language (probably English) is used, with i18n handled on
1074 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1076 const struct usb_gadget_strings *s;
1082 language = cpu_to_le16(s->language);
1083 for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
1084 if (*tmp == language)
1093 static int lookup_string(
1094 struct usb_gadget_strings **sp,
1100 struct usb_gadget_strings *s;
1105 if (s->language != language)
1107 value = usb_gadget_get_string(s, id, buf);
1114 static int get_string(struct usb_composite_dev *cdev,
1115 void *buf, u16 language, int id)
1117 struct usb_composite_driver *composite = cdev->driver;
1118 struct usb_gadget_string_container *uc;
1119 struct usb_configuration *c;
1120 struct usb_function *f;
1123 /* Yes, not only is USB's i18n support probably more than most
1124 * folk will ever care about ... also, it's all supported here.
1125 * (Except for UTF8 support for Unicode's "Astral Planes".)
1128 /* 0 == report all available language codes */
1130 struct usb_string_descriptor *s = buf;
1131 struct usb_gadget_strings **sp;
1134 s->bDescriptorType = USB_DT_STRING;
1136 sp = composite->strings;
1138 collect_langs(sp, s->wData);
1140 list_for_each_entry(c, &cdev->configs, list) {
1143 collect_langs(sp, s->wData);
1145 list_for_each_entry(f, &c->functions, list) {
1148 collect_langs(sp, s->wData);
1151 list_for_each_entry(uc, &cdev->gstrings, list) {
1152 struct usb_gadget_strings **sp;
1154 sp = get_containers_gs(uc);
1155 collect_langs(sp, s->wData);
1158 for (len = 0; len <= USB_MAX_STRING_LEN && s->wData[len]; len++)
1163 s->bLength = 2 * (len + 1);
1167 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1168 struct usb_os_string *b = buf;
1169 b->bLength = sizeof(*b);
1170 b->bDescriptorType = USB_DT_STRING;
1172 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1173 "qwSignature size must be equal to qw_sign");
1174 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1175 b->bMS_VendorCode = cdev->b_vendor_code;
1180 list_for_each_entry(uc, &cdev->gstrings, list) {
1181 struct usb_gadget_strings **sp;
1183 sp = get_containers_gs(uc);
1184 len = lookup_string(sp, buf, language, id);
1189 /* String IDs are device-scoped, so we look up each string
1190 * table we're told about. These lookups are infrequent;
1191 * simpler-is-better here.
1193 if (composite->strings) {
1194 len = lookup_string(composite->strings, buf, language, id);
1198 list_for_each_entry(c, &cdev->configs, list) {
1200 len = lookup_string(c->strings, buf, language, id);
1204 list_for_each_entry(f, &c->functions, list) {
1207 len = lookup_string(f->strings, buf, language, id);
1216 * usb_string_id() - allocate an unused string ID
1217 * @cdev: the device whose string descriptor IDs are being allocated
1218 * Context: single threaded during gadget setup
1220 * @usb_string_id() is called from bind() callbacks to allocate
1221 * string IDs. Drivers for functions, configurations, or gadgets will
1222 * then store that ID in the appropriate descriptors and string table.
1224 * All string identifier should be allocated using this,
1225 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1226 * that for example different functions don't wrongly assign different
1227 * meanings to the same identifier.
1229 int usb_string_id(struct usb_composite_dev *cdev)
1231 if (cdev->next_string_id < 254) {
1232 /* string id 0 is reserved by USB spec for list of
1233 * supported languages */
1234 /* 255 reserved as well? -- mina86 */
1235 cdev->next_string_id++;
1236 return cdev->next_string_id;
1240 EXPORT_SYMBOL_GPL(usb_string_id);
1243 * usb_string_ids() - allocate unused string IDs in batch
1244 * @cdev: the device whose string descriptor IDs are being allocated
1245 * @str: an array of usb_string objects to assign numbers to
1246 * Context: single threaded during gadget setup
1248 * @usb_string_ids() is called from bind() callbacks to allocate
1249 * string IDs. Drivers for functions, configurations, or gadgets will
1250 * then copy IDs from the string table to the appropriate descriptors
1251 * and string table for other languages.
1253 * All string identifier should be allocated using this,
1254 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1255 * example different functions don't wrongly assign different meanings
1256 * to the same identifier.
1258 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1260 int next = cdev->next_string_id;
1262 for (; str->s; ++str) {
1263 if (unlikely(next >= 254))
1268 cdev->next_string_id = next;
1272 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1274 static struct usb_gadget_string_container *copy_gadget_strings(
1275 struct usb_gadget_strings **sp, unsigned n_gstrings,
1278 struct usb_gadget_string_container *uc;
1279 struct usb_gadget_strings **gs_array;
1280 struct usb_gadget_strings *gs;
1281 struct usb_string *s;
1288 mem += sizeof(void *) * (n_gstrings + 1);
1289 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1290 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1291 uc = kmalloc(mem, GFP_KERNEL);
1293 return ERR_PTR(-ENOMEM);
1294 gs_array = get_containers_gs(uc);
1296 stash += sizeof(void *) * (n_gstrings + 1);
1297 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1298 struct usb_string *org_s;
1300 gs_array[n_gs] = stash;
1301 gs = gs_array[n_gs];
1302 stash += sizeof(struct usb_gadget_strings);
1303 gs->language = sp[n_gs]->language;
1304 gs->strings = stash;
1305 org_s = sp[n_gs]->strings;
1307 for (n_s = 0; n_s < n_strings; n_s++) {
1309 stash += sizeof(struct usb_string);
1318 stash += sizeof(struct usb_string);
1321 gs_array[n_gs] = NULL;
1326 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1327 * @cdev: the device whose string descriptor IDs are being allocated
1329 * @sp: an array of usb_gadget_strings to attach.
1330 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1332 * This function will create a deep copy of usb_gadget_strings and usb_string
1333 * and attach it to the cdev. The actual string (usb_string.s) will not be
1334 * copied but only a referenced will be made. The struct usb_gadget_strings
1335 * array may contain multiple languages and should be NULL terminated.
1336 * The ->language pointer of each struct usb_gadget_strings has to contain the
1337 * same amount of entries.
1338 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1339 * usb_string entry of es-ES contains the translation of the first usb_string
1340 * entry of en-US. Therefore both entries become the same id assign.
1342 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1343 struct usb_gadget_strings **sp, unsigned n_strings)
1345 struct usb_gadget_string_container *uc;
1346 struct usb_gadget_strings **n_gs;
1347 unsigned n_gstrings = 0;
1351 for (i = 0; sp[i]; i++)
1355 return ERR_PTR(-EINVAL);
1357 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1359 return ERR_CAST(uc);
1361 n_gs = get_containers_gs(uc);
1362 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1366 for (i = 1; i < n_gstrings; i++) {
1367 struct usb_string *m_s;
1368 struct usb_string *s;
1371 m_s = n_gs[0]->strings;
1372 s = n_gs[i]->strings;
1373 for (n = 0; n < n_strings; n++) {
1379 list_add_tail(&uc->list, &cdev->gstrings);
1380 return n_gs[0]->strings;
1383 return ERR_PTR(ret);
1385 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1388 * usb_string_ids_n() - allocate unused string IDs in batch
1389 * @c: the device whose string descriptor IDs are being allocated
1390 * @n: number of string IDs to allocate
1391 * Context: single threaded during gadget setup
1393 * Returns the first requested ID. This ID and next @n-1 IDs are now
1394 * valid IDs. At least provided that @n is non-zero because if it
1395 * is, returns last requested ID which is now very useful information.
1397 * @usb_string_ids_n() is called from bind() callbacks to allocate
1398 * string IDs. Drivers for functions, configurations, or gadgets will
1399 * then store that ID in the appropriate descriptors and string table.
1401 * All string identifier should be allocated using this,
1402 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1403 * example different functions don't wrongly assign different meanings
1404 * to the same identifier.
1406 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1408 unsigned next = c->next_string_id;
1409 if (unlikely(n > 254 || (unsigned)next + n > 254))
1411 c->next_string_id += n;
1414 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1416 /*-------------------------------------------------------------------------*/
1418 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1420 struct usb_composite_dev *cdev;
1422 if (req->status || req->actual != req->length)
1423 DBG((struct usb_composite_dev *) ep->driver_data,
1424 "setup complete --> %d, %d/%d\n",
1425 req->status, req->actual, req->length);
1428 * REVIST The same ep0 requests are shared with function drivers
1429 * so they don't have to maintain the same ->complete() stubs.
1431 * Because of that, we need to check for the validity of ->context
1432 * here, even though we know we've set it to something useful.
1437 cdev = req->context;
1439 if (cdev->req == req)
1440 cdev->setup_pending = false;
1441 else if (cdev->os_desc_req == req)
1442 cdev->os_desc_pending = false;
1444 WARN(1, "unknown request %p\n", req);
1447 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1448 struct usb_request *req, gfp_t gfp_flags)
1452 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1454 if (cdev->req == req)
1455 cdev->setup_pending = true;
1456 else if (cdev->os_desc_req == req)
1457 cdev->os_desc_pending = true;
1459 WARN(1, "unknown request %p\n", req);
1465 static int count_ext_compat(struct usb_configuration *c)
1470 for (i = 0; i < c->next_interface_id; ++i) {
1471 struct usb_function *f;
1474 f = c->interface[i];
1475 for (j = 0; j < f->os_desc_n; ++j) {
1476 struct usb_os_desc *d;
1478 if (i != f->os_desc_table[j].if_id)
1480 d = f->os_desc_table[j].os_desc;
1481 if (d && d->ext_compat_id)
1489 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1494 for (i = 0; i < c->next_interface_id; ++i) {
1495 struct usb_function *f;
1498 f = c->interface[i];
1499 for (j = 0; j < f->os_desc_n; ++j) {
1500 struct usb_os_desc *d;
1502 if (i != f->os_desc_table[j].if_id)
1504 d = f->os_desc_table[j].os_desc;
1505 if (d && d->ext_compat_id) {
1508 memcpy(buf, d->ext_compat_id, 16);
1516 if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1524 static int count_ext_prop(struct usb_configuration *c, int interface)
1526 struct usb_function *f;
1529 f = c->interface[interface];
1530 for (j = 0; j < f->os_desc_n; ++j) {
1531 struct usb_os_desc *d;
1533 if (interface != f->os_desc_table[j].if_id)
1535 d = f->os_desc_table[j].os_desc;
1536 if (d && d->ext_compat_id)
1537 return d->ext_prop_count;
1542 static int len_ext_prop(struct usb_configuration *c, int interface)
1544 struct usb_function *f;
1545 struct usb_os_desc *d;
1548 res = 10; /* header length */
1549 f = c->interface[interface];
1550 for (j = 0; j < f->os_desc_n; ++j) {
1551 if (interface != f->os_desc_table[j].if_id)
1553 d = f->os_desc_table[j].os_desc;
1555 return min(res + d->ext_prop_len, 4096);
1560 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1562 struct usb_function *f;
1563 struct usb_os_desc *d;
1564 struct usb_os_desc_ext_prop *ext_prop;
1565 int j, count, n, ret;
1567 f = c->interface[interface];
1568 count = 10; /* header length */
1569 for (j = 0; j < f->os_desc_n; ++j) {
1570 if (interface != f->os_desc_table[j].if_id)
1572 d = f->os_desc_table[j].os_desc;
1574 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1575 n = ext_prop->data_len +
1576 ext_prop->name_len + 14;
1577 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1579 usb_ext_prop_put_size(buf, n);
1580 usb_ext_prop_put_type(buf, ext_prop->type);
1581 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1582 ext_prop->name_len);
1585 switch (ext_prop->type) {
1586 case USB_EXT_PROP_UNICODE:
1587 case USB_EXT_PROP_UNICODE_ENV:
1588 case USB_EXT_PROP_UNICODE_LINK:
1589 usb_ext_prop_put_unicode(buf, ret,
1591 ext_prop->data_len);
1593 case USB_EXT_PROP_BINARY:
1594 usb_ext_prop_put_binary(buf, ret,
1596 ext_prop->data_len);
1598 case USB_EXT_PROP_LE32:
1599 /* not implemented */
1600 case USB_EXT_PROP_BE32:
1601 /* not implemented */
1614 * The setup() callback implements all the ep0 functionality that's
1615 * not handled lower down, in hardware or the hardware driver(like
1616 * device and endpoint feature flags, and their status). It's all
1617 * housekeeping for the gadget function we're implementing. Most of
1618 * the work is in config and function specific setup.
1621 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1623 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1624 struct usb_request *req = cdev->req;
1625 int value = -EOPNOTSUPP;
1627 u16 w_index = le16_to_cpu(ctrl->wIndex);
1628 u8 intf = w_index & 0xFF;
1629 u16 w_value = le16_to_cpu(ctrl->wValue);
1630 u16 w_length = le16_to_cpu(ctrl->wLength);
1631 struct usb_function *f = NULL;
1634 if (w_length > USB_COMP_EP0_BUFSIZ) {
1635 if (ctrl->bRequestType & USB_DIR_IN) {
1636 /* Cast away the const, we are going to overwrite on purpose. */
1637 __le16 *temp = (__le16 *)&ctrl->wLength;
1639 *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
1640 w_length = USB_COMP_EP0_BUFSIZ;
1646 /* partial re-init of the response message; the function or the
1647 * gadget might need to intercept e.g. a control-OUT completion
1648 * when we delegate to it.
1651 req->context = cdev;
1652 req->complete = composite_setup_complete;
1654 gadget->ep0->driver_data = cdev;
1657 * Don't let non-standard requests match any of the cases below
1660 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1663 switch (ctrl->bRequest) {
1665 /* we handle all standard USB descriptors */
1666 case USB_REQ_GET_DESCRIPTOR:
1667 if (ctrl->bRequestType != USB_DIR_IN)
1669 switch (w_value >> 8) {
1672 cdev->desc.bNumConfigurations =
1673 count_configs(cdev, USB_DT_DEVICE);
1674 cdev->desc.bMaxPacketSize0 =
1675 cdev->gadget->ep0->maxpacket;
1676 if (gadget_is_superspeed(gadget)) {
1677 if (gadget->speed >= USB_SPEED_SUPER) {
1678 cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1679 cdev->desc.bMaxPacketSize0 = 9;
1681 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1684 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1687 value = min(w_length, (u16) sizeof cdev->desc);
1688 memcpy(req->buf, &cdev->desc, value);
1690 case USB_DT_DEVICE_QUALIFIER:
1691 if (!gadget_is_dualspeed(gadget) ||
1692 gadget->speed >= USB_SPEED_SUPER)
1695 value = min_t(int, w_length,
1696 sizeof(struct usb_qualifier_descriptor));
1698 case USB_DT_OTHER_SPEED_CONFIG:
1699 if (!gadget_is_dualspeed(gadget) ||
1700 gadget->speed >= USB_SPEED_SUPER)
1704 value = config_desc(cdev, w_value);
1706 value = min(w_length, (u16) value);
1709 value = get_string(cdev, req->buf,
1710 w_index, w_value & 0xff);
1712 value = min(w_length, (u16) value);
1715 if (gadget_is_superspeed(gadget)) {
1716 value = bos_desc(cdev);
1717 value = min(w_length, (u16) value);
1721 if (gadget_is_otg(gadget)) {
1722 struct usb_configuration *config;
1723 int otg_desc_len = 0;
1726 config = cdev->config;
1728 config = list_first_entry(
1730 struct usb_configuration, list);
1734 if (gadget->otg_caps &&
1735 (gadget->otg_caps->otg_rev >= 0x0200))
1736 otg_desc_len += sizeof(
1737 struct usb_otg20_descriptor);
1739 otg_desc_len += sizeof(
1740 struct usb_otg_descriptor);
1742 value = min_t(int, w_length, otg_desc_len);
1743 memcpy(req->buf, config->descriptors[0], value);
1749 /* any number of configs can work */
1750 case USB_REQ_SET_CONFIGURATION:
1751 if (ctrl->bRequestType != 0)
1753 if (gadget_is_otg(gadget)) {
1754 if (gadget->a_hnp_support)
1755 DBG(cdev, "HNP available\n");
1756 else if (gadget->a_alt_hnp_support)
1757 DBG(cdev, "HNP on another port\n");
1759 VDBG(cdev, "HNP inactive\n");
1761 spin_lock(&cdev->lock);
1762 value = set_config(cdev, ctrl, w_value);
1763 spin_unlock(&cdev->lock);
1765 case USB_REQ_GET_CONFIGURATION:
1766 if (ctrl->bRequestType != USB_DIR_IN)
1769 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1771 *(u8 *)req->buf = 0;
1772 value = min(w_length, (u16) 1);
1775 /* function drivers must handle get/set altsetting */
1776 case USB_REQ_SET_INTERFACE:
1777 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1779 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1781 f = cdev->config->interface[intf];
1786 * If there's no get_alt() method, we know only altsetting zero
1787 * works. There is no need to check if set_alt() is not NULL
1788 * as we check this in usb_add_function().
1790 if (w_value && !f->get_alt)
1793 spin_lock(&cdev->lock);
1794 value = f->set_alt(f, w_index, w_value);
1795 if (value == USB_GADGET_DELAYED_STATUS) {
1797 "%s: interface %d (%s) requested delayed status\n",
1798 __func__, intf, f->name);
1799 cdev->delayed_status++;
1800 DBG(cdev, "delayed_status count %d\n",
1801 cdev->delayed_status);
1803 spin_unlock(&cdev->lock);
1805 case USB_REQ_GET_INTERFACE:
1806 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1808 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1810 f = cdev->config->interface[intf];
1813 /* lots of interfaces only need altsetting zero... */
1814 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1817 *((u8 *)req->buf) = value;
1818 value = min(w_length, (u16) 1);
1820 case USB_REQ_GET_STATUS:
1821 if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1822 (w_index == OTG_STS_SELECTOR)) {
1823 if (ctrl->bRequestType != (USB_DIR_IN |
1826 *((u8 *)req->buf) = gadget->host_request_flag;
1832 * USB 3.0 additions:
1833 * Function driver should handle get_status request. If such cb
1834 * wasn't supplied we respond with default value = 0
1835 * Note: function driver should supply such cb only for the
1836 * first interface of the function
1838 if (!gadget_is_superspeed(gadget))
1840 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1842 value = 2; /* This is the length of the get_status reply */
1843 put_unaligned_le16(0, req->buf);
1844 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1846 f = cdev->config->interface[intf];
1849 status = f->get_status ? f->get_status(f) : 0;
1852 put_unaligned_le16(status & 0x0000ffff, req->buf);
1855 * Function drivers should handle SetFeature/ClearFeature
1856 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1857 * only for the first interface of the function
1859 case USB_REQ_CLEAR_FEATURE:
1860 case USB_REQ_SET_FEATURE:
1861 if (!gadget_is_superspeed(gadget))
1863 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1866 case USB_INTRF_FUNC_SUSPEND:
1867 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1869 f = cdev->config->interface[intf];
1873 if (f->func_suspend)
1874 value = f->func_suspend(f, w_index >> 8);
1877 "func_suspend() returned error %d\n",
1887 * OS descriptors handling
1889 if (cdev->use_os_string && cdev->os_desc_config &&
1890 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1891 ctrl->bRequest == cdev->b_vendor_code) {
1892 struct usb_request *req;
1893 struct usb_configuration *os_desc_cfg;
1898 req = cdev->os_desc_req;
1899 req->context = cdev;
1900 req->complete = composite_setup_complete;
1902 os_desc_cfg = cdev->os_desc_config;
1903 w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1904 memset(buf, 0, w_length);
1906 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1907 case USB_RECIP_DEVICE:
1908 if (w_index != 0x4 || (w_value >> 8))
1911 if (w_length == 0x10) {
1912 /* Number of ext compat interfaces */
1913 count = count_ext_compat(os_desc_cfg);
1915 count *= 24; /* 24 B/ext compat desc */
1916 count += 16; /* header */
1917 put_unaligned_le32(count, buf);
1920 /* "extended compatibility ID"s */
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);
1927 value = fill_ext_compat(os_desc_cfg, buf);
1928 value = min_t(u16, w_length, value);
1931 case USB_RECIP_INTERFACE:
1932 if (w_index != 0x5 || (w_value >> 8))
1934 interface = w_value & 0xFF;
1935 if (interface >= MAX_CONFIG_INTERFACES ||
1936 !os_desc_cfg->interface[interface])
1939 if (w_length == 0x0A) {
1940 count = count_ext_prop(os_desc_cfg,
1942 put_unaligned_le16(count, buf + 8);
1943 count = len_ext_prop(os_desc_cfg,
1945 put_unaligned_le32(count, buf);
1949 count = count_ext_prop(os_desc_cfg,
1951 put_unaligned_le16(count, buf + 8);
1952 count = len_ext_prop(os_desc_cfg,
1954 put_unaligned_le32(count, buf);
1956 value = fill_ext_prop(os_desc_cfg,
1960 value = min_t(u16, w_length, value);
1966 req->length = value;
1967 req->context = cdev;
1968 req->zero = value < w_length;
1969 value = composite_ep0_queue(cdev, req,
1972 DBG(cdev, "ep_queue --> %d\n", value);
1974 composite_setup_complete(gadget->ep0,
1982 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1983 ctrl->bRequestType, ctrl->bRequest,
1984 w_value, w_index, w_length);
1986 /* functions always handle their interfaces and endpoints...
1987 * punt other recipients (other, WUSB, ...) to the current
1988 * configuration code.
1991 list_for_each_entry(f, &cdev->config->functions, list)
1993 f->req_match(f, ctrl, false))
1996 struct usb_configuration *c;
1997 list_for_each_entry(c, &cdev->configs, list)
1998 list_for_each_entry(f, &c->functions, list)
2000 f->req_match(f, ctrl, true))
2005 switch (ctrl->bRequestType & USB_RECIP_MASK) {
2006 case USB_RECIP_INTERFACE:
2007 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2009 f = cdev->config->interface[intf];
2012 case USB_RECIP_ENDPOINT:
2015 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
2016 list_for_each_entry(f, &cdev->config->functions, list) {
2017 if (test_bit(endp, f->endpoints))
2020 if (&f->list == &cdev->config->functions)
2026 value = f->setup(f, ctrl);
2028 struct usb_configuration *c;
2034 /* try current config's setup */
2036 value = c->setup(c, ctrl);
2040 /* try the only function in the current config */
2041 if (!list_is_singular(&c->functions))
2043 f = list_first_entry(&c->functions, struct usb_function,
2046 value = f->setup(f, ctrl);
2052 /* respond with data transfer before status phase? */
2053 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2054 req->length = value;
2055 req->context = cdev;
2056 req->zero = value < w_length;
2057 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2059 DBG(cdev, "ep_queue --> %d\n", value);
2061 composite_setup_complete(gadget->ep0, req);
2063 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2065 "%s: Delayed status not supported for w_length != 0",
2070 /* device either stalls (value < 0) or reports success */
2074 void composite_disconnect(struct usb_gadget *gadget)
2076 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2077 unsigned long flags;
2079 /* REVISIT: should we have config and device level
2080 * disconnect callbacks?
2082 spin_lock_irqsave(&cdev->lock, flags);
2083 cdev->suspended = 0;
2086 if (cdev->driver->disconnect)
2087 cdev->driver->disconnect(cdev);
2088 spin_unlock_irqrestore(&cdev->lock, flags);
2091 /*-------------------------------------------------------------------------*/
2093 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2096 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2097 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2099 return sprintf(buf, "%d\n", cdev->suspended);
2101 static DEVICE_ATTR_RO(suspended);
2103 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2105 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2106 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2107 struct usb_string *dev_str = gstr->strings;
2109 /* composite_disconnect() must already have been called
2110 * by the underlying peripheral controller driver!
2111 * so there's no i/o concurrency that could affect the
2112 * state protected by cdev->lock.
2114 WARN_ON(cdev->config);
2116 while (!list_empty(&cdev->configs)) {
2117 struct usb_configuration *c;
2118 c = list_first_entry(&cdev->configs,
2119 struct usb_configuration, list);
2120 remove_config(cdev, c);
2122 if (cdev->driver->unbind && unbind_driver)
2123 cdev->driver->unbind(cdev);
2125 composite_dev_cleanup(cdev);
2127 if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2128 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2130 kfree(cdev->def_manufacturer);
2132 set_gadget_data(gadget, NULL);
2135 static void composite_unbind(struct usb_gadget *gadget)
2137 __composite_unbind(gadget, true);
2140 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2141 const struct usb_device_descriptor *old)
2151 * these variables may have been set in
2152 * usb_composite_overwrite_options()
2154 idVendor = new->idVendor;
2155 idProduct = new->idProduct;
2156 bcdDevice = new->bcdDevice;
2157 iSerialNumber = new->iSerialNumber;
2158 iManufacturer = new->iManufacturer;
2159 iProduct = new->iProduct;
2163 new->idVendor = idVendor;
2165 new->idProduct = idProduct;
2167 new->bcdDevice = bcdDevice;
2169 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2171 new->iSerialNumber = iSerialNumber;
2173 new->iManufacturer = iManufacturer;
2175 new->iProduct = iProduct;
2178 int composite_dev_prepare(struct usb_composite_driver *composite,
2179 struct usb_composite_dev *cdev)
2181 struct usb_gadget *gadget = cdev->gadget;
2184 /* preallocate control response and buffer */
2185 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2189 cdev->req->buf = kzalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2190 if (!cdev->req->buf)
2193 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2197 cdev->req->complete = composite_setup_complete;
2198 cdev->req->context = cdev;
2199 gadget->ep0->driver_data = cdev;
2201 cdev->driver = composite;
2204 * As per USB compliance update, a device that is actively drawing
2205 * more than 100mA from USB must report itself as bus-powered in
2206 * the GetStatus(DEVICE) call.
2208 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2209 usb_gadget_set_selfpowered(gadget);
2211 /* interface and string IDs start at zero via kzalloc.
2212 * we force endpoints to start unassigned; few controller
2213 * drivers will zero ep->driver_data.
2215 usb_ep_autoconfig_reset(gadget);
2218 kfree(cdev->req->buf);
2220 usb_ep_free_request(gadget->ep0, cdev->req);
2225 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2230 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2231 if (!cdev->os_desc_req) {
2236 cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2238 if (!cdev->os_desc_req->buf) {
2240 usb_ep_free_request(ep0, cdev->os_desc_req);
2243 cdev->os_desc_req->context = cdev;
2244 cdev->os_desc_req->complete = composite_setup_complete;
2249 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2251 struct usb_gadget_string_container *uc, *tmp;
2253 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2254 list_del(&uc->list);
2257 if (cdev->os_desc_req) {
2258 if (cdev->os_desc_pending)
2259 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2261 kfree(cdev->os_desc_req->buf);
2262 cdev->os_desc_req->buf = NULL;
2263 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2264 cdev->os_desc_req = NULL;
2267 if (cdev->setup_pending)
2268 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2270 kfree(cdev->req->buf);
2271 cdev->req->buf = NULL;
2272 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2275 cdev->next_string_id = 0;
2276 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2279 static int composite_bind(struct usb_gadget *gadget,
2280 struct usb_gadget_driver *gdriver)
2282 struct usb_composite_dev *cdev;
2283 struct usb_composite_driver *composite = to_cdriver(gdriver);
2284 int status = -ENOMEM;
2286 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2290 spin_lock_init(&cdev->lock);
2291 cdev->gadget = gadget;
2292 set_gadget_data(gadget, cdev);
2293 INIT_LIST_HEAD(&cdev->configs);
2294 INIT_LIST_HEAD(&cdev->gstrings);
2296 status = composite_dev_prepare(composite, cdev);
2300 /* composite gadget needs to assign strings for whole device (like
2301 * serial number), register function drivers, potentially update
2302 * power state and consumption, etc
2304 status = composite->bind(cdev);
2308 if (cdev->use_os_string) {
2309 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2314 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2316 /* has userspace failed to provide a serial number? */
2317 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2318 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2320 INFO(cdev, "%s ready\n", composite->name);
2324 __composite_unbind(gadget, false);
2328 /*-------------------------------------------------------------------------*/
2330 void composite_suspend(struct usb_gadget *gadget)
2332 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2333 struct usb_function *f;
2335 /* REVISIT: should we have config level
2336 * suspend/resume callbacks?
2338 DBG(cdev, "suspend\n");
2340 list_for_each_entry(f, &cdev->config->functions, list) {
2345 if (cdev->driver->suspend)
2346 cdev->driver->suspend(cdev);
2348 cdev->suspended = 1;
2350 usb_gadget_set_selfpowered(gadget);
2351 usb_gadget_vbus_draw(gadget, 2);
2354 void composite_resume(struct usb_gadget *gadget)
2356 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2357 struct usb_function *f;
2360 /* REVISIT: should we have config level
2361 * suspend/resume callbacks?
2363 DBG(cdev, "resume\n");
2364 if (cdev->driver->resume)
2365 cdev->driver->resume(cdev);
2367 list_for_each_entry(f, &cdev->config->functions, list) {
2372 maxpower = cdev->config->MaxPower ?
2373 cdev->config->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
2374 if (gadget->speed < USB_SPEED_SUPER)
2375 maxpower = min(maxpower, 500U);
2377 maxpower = min(maxpower, 900U);
2379 if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2380 usb_gadget_clear_selfpowered(gadget);
2382 usb_gadget_vbus_draw(gadget, maxpower);
2385 cdev->suspended = 0;
2388 /*-------------------------------------------------------------------------*/
2390 static const struct usb_gadget_driver composite_driver_template = {
2391 .bind = composite_bind,
2392 .unbind = composite_unbind,
2394 .setup = composite_setup,
2395 .reset = composite_disconnect,
2396 .disconnect = composite_disconnect,
2398 .suspend = composite_suspend,
2399 .resume = composite_resume,
2402 .owner = THIS_MODULE,
2407 * usb_composite_probe() - register a composite driver
2408 * @driver: the driver to register
2410 * Context: single threaded during gadget setup
2412 * This function is used to register drivers using the composite driver
2413 * framework. The return value is zero, or a negative errno value.
2414 * Those values normally come from the driver's @bind method, which does
2415 * all the work of setting up the driver to match the hardware.
2417 * On successful return, the gadget is ready to respond to requests from
2418 * the host, unless one of its components invokes usb_gadget_disconnect()
2419 * while it was binding. That would usually be done in order to wait for
2420 * some userspace participation.
2422 int usb_composite_probe(struct usb_composite_driver *driver)
2424 struct usb_gadget_driver *gadget_driver;
2426 if (!driver || !driver->dev || !driver->bind)
2430 driver->name = "composite";
2432 driver->gadget_driver = composite_driver_template;
2433 gadget_driver = &driver->gadget_driver;
2435 gadget_driver->function = (char *) driver->name;
2436 gadget_driver->driver.name = driver->name;
2437 gadget_driver->max_speed = driver->max_speed;
2439 return usb_gadget_probe_driver(gadget_driver);
2441 EXPORT_SYMBOL_GPL(usb_composite_probe);
2444 * usb_composite_unregister() - unregister a composite driver
2445 * @driver: the driver to unregister
2447 * This function is used to unregister drivers using the composite
2450 void usb_composite_unregister(struct usb_composite_driver *driver)
2452 usb_gadget_unregister_driver(&driver->gadget_driver);
2454 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2457 * usb_composite_setup_continue() - Continue with the control transfer
2458 * @cdev: the composite device who's control transfer was kept waiting
2460 * This function must be called by the USB function driver to continue
2461 * with the control transfer's data/status stage in case it had requested to
2462 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2463 * can request the composite framework to delay the setup request's data/status
2464 * stages by returning USB_GADGET_DELAYED_STATUS.
2466 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2469 struct usb_request *req = cdev->req;
2470 unsigned long flags;
2472 DBG(cdev, "%s\n", __func__);
2473 spin_lock_irqsave(&cdev->lock, flags);
2475 if (cdev->delayed_status == 0) {
2476 WARN(cdev, "%s: Unexpected call\n", __func__);
2478 } else if (--cdev->delayed_status == 0) {
2479 DBG(cdev, "%s: Completing delayed status\n", __func__);
2481 req->context = cdev;
2482 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2484 DBG(cdev, "ep_queue --> %d\n", value);
2486 composite_setup_complete(cdev->gadget->ep0, req);
2490 spin_unlock_irqrestore(&cdev->lock, flags);
2492 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2494 static char *composite_default_mfr(struct usb_gadget *gadget)
2499 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2500 init_utsname()->release, gadget->name);
2502 mfr = kmalloc(len, GFP_KERNEL);
2505 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2506 init_utsname()->release, gadget->name);
2510 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2511 struct usb_composite_overwrite *covr)
2513 struct usb_device_descriptor *desc = &cdev->desc;
2514 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2515 struct usb_string *dev_str = gstr->strings;
2518 desc->idVendor = cpu_to_le16(covr->idVendor);
2520 if (covr->idProduct)
2521 desc->idProduct = cpu_to_le16(covr->idProduct);
2523 if (covr->bcdDevice)
2524 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2526 if (covr->serial_number) {
2527 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2528 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2530 if (covr->manufacturer) {
2531 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2532 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2534 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2535 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2536 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2537 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2540 if (covr->product) {
2541 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2542 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2545 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2547 MODULE_LICENSE("GPL");
2548 MODULE_AUTHOR("David Brownell");