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"
26 #define SSUSB_GADGET_VBUS_DRAW 900 /* in mA */
27 #define SSUSB_GADGET_VBUS_DRAW_UNITS 8
28 #define HSUSB_GADGET_VBUS_DRAW_UNITS 2
31 * Based on enumerated USB speed, draw power with set_config and resume
32 * HSUSB: 500mA, SSUSB: 900mA
34 #define USB_VBUS_DRAW(speed)\
35 (speed == USB_SPEED_SUPER ?\
36 SSUSB_GADGET_VBUS_DRAW : CONFIG_USB_GADGET_VBUS_DRAW)
38 /* disable LPM by default */
39 static bool disable_l1_for_hs = true;
40 module_param(disable_l1_for_hs, bool, S_IRUGO | S_IWUSR);
41 MODULE_PARM_DESC(disable_l1_for_hs,
42 "Disable support for L1 LPM for HS devices");
45 * struct usb_os_string - represents OS String to be reported by a gadget
46 * @bLength: total length of the entire descritor, always 0x12
47 * @bDescriptorType: USB_DT_STRING
48 * @qwSignature: the OS String proper
49 * @bMS_VendorCode: code used by the host for subsequent requests
50 * @bPad: not used, must be zero
52 struct usb_os_string {
55 __u8 qwSignature[OS_STRING_QW_SIGN_LEN];
61 * The code in this file is utility code, used to build a gadget driver
62 * from one or more "function" drivers, one or more "configuration"
63 * objects, and a "usb_composite_driver" by gluing them together along
64 * with the relevant device-wide data.
67 static struct usb_gadget_strings **get_containers_gs(
68 struct usb_gadget_string_container *uc)
70 return (struct usb_gadget_strings **)uc->stash;
74 * next_ep_desc() - advance to the next EP descriptor
75 * @t: currect pointer within descriptor array
77 * Return: next EP descriptor or NULL
79 * Iterate over @t until either EP descriptor found or
80 * NULL (that indicates end of list) encountered
82 static struct usb_descriptor_header**
83 next_ep_desc(struct usb_descriptor_header **t)
86 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
93 * for_each_ep_desc()- iterate over endpoint descriptors in the
95 * @start: pointer within descriptor array.
96 * @ep_desc: endpoint descriptor to use as the loop cursor
98 #define for_each_ep_desc(start, ep_desc) \
99 for (ep_desc = next_ep_desc(start); \
100 ep_desc; ep_desc = next_ep_desc(ep_desc+1))
103 * config_ep_by_speed() - configures the given endpoint
104 * according to gadget speed.
105 * @g: pointer to the gadget
107 * @_ep: the endpoint to configure
109 * Return: error code, 0 on success
111 * This function chooses the right descriptors for a given
112 * endpoint according to gadget speed and saves it in the
113 * endpoint desc field. If the endpoint already has a descriptor
114 * assigned to it - overwrites it with currently corresponding
115 * descriptor. The endpoint maxpacket field is updated according
116 * to the chosen descriptor.
117 * Note: the supplied function should hold all the descriptors
118 * for supported speeds
120 int config_ep_by_speed(struct usb_gadget *g,
121 struct usb_function *f,
124 struct usb_endpoint_descriptor *chosen_desc = NULL;
125 struct usb_descriptor_header **speed_desc = NULL;
127 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
128 int want_comp_desc = 0;
130 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
132 if (!g || !f || !_ep)
135 /* select desired speed */
137 case USB_SPEED_SUPER:
138 if (gadget_is_superspeed(g)) {
139 speed_desc = f->ss_descriptors;
143 /* else: Fall trough */
145 if (gadget_is_dualspeed(g)) {
146 speed_desc = f->hs_descriptors;
149 /* else: fall through */
151 speed_desc = f->fs_descriptors;
153 /* find descriptors */
154 for_each_ep_desc(speed_desc, d_spd) {
155 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
156 if (chosen_desc->bEndpointAddress == _ep->address)
163 _ep->maxpacket = usb_endpoint_maxp(chosen_desc) & 0x7ff;
164 _ep->desc = chosen_desc;
165 _ep->comp_desc = NULL;
169 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
170 usb_endpoint_xfer_int(_ep->desc)))
171 _ep->mult = ((usb_endpoint_maxp(_ep->desc) & 0x1800) >> 11) + 1;
177 * Companion descriptor should follow EP descriptor
178 * USB 3.0 spec, #9.6.7
180 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
182 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
184 _ep->comp_desc = comp_desc;
185 if (g->speed == USB_SPEED_SUPER) {
186 switch (usb_endpoint_type(_ep->desc)) {
187 case USB_ENDPOINT_XFER_ISOC:
188 /* mult: bits 1:0 of bmAttributes */
189 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
190 case USB_ENDPOINT_XFER_BULK:
191 case USB_ENDPOINT_XFER_INT:
192 _ep->maxburst = comp_desc->bMaxBurst + 1;
195 if (comp_desc->bMaxBurst != 0) {
196 struct usb_composite_dev *cdev;
198 cdev = get_gadget_data(g);
199 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
207 EXPORT_SYMBOL_GPL(config_ep_by_speed);
210 * usb_add_function() - add a function to a configuration
211 * @config: the configuration
212 * @function: the function being added
213 * Context: single threaded during gadget setup
215 * After initialization, each configuration must have one or more
216 * functions added to it. Adding a function involves calling its @bind()
217 * method to allocate resources such as interface and string identifiers
220 * This function returns the value of the function's bind(), which is
221 * zero for success else a negative errno value.
223 int usb_add_function(struct usb_configuration *config,
224 struct usb_function *function)
228 DBG(config->cdev, "adding '%s'/%pK to config '%s'/%pK\n",
229 function->name, function,
230 config->label, config);
232 if (!function->set_alt || !function->disable)
235 function->config = config;
236 function->intf_id = -EINVAL;
237 list_add_tail(&function->list, &config->functions);
239 if (function->bind_deactivated) {
240 value = usb_function_deactivate(function);
245 /* REVISIT *require* function->bind? */
246 if (function->bind) {
247 value = function->bind(config, function);
249 list_del(&function->list);
250 function->config = NULL;
255 /* We allow configurations that don't work at both speeds.
256 * If we run into a lowspeed Linux system, treat it the same
257 * as full speed ... it's the function drivers that will need
258 * to avoid bulk and ISO transfers.
260 if (!config->fullspeed && function->fs_descriptors)
261 config->fullspeed = true;
262 if (!config->highspeed && function->hs_descriptors)
263 config->highspeed = true;
264 if (!config->superspeed && function->ss_descriptors)
265 config->superspeed = true;
269 DBG(config->cdev, "adding '%s'/%pK --> %d\n",
270 function->name, function, value);
273 EXPORT_SYMBOL_GPL(usb_add_function);
275 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
280 bitmap_zero(f->endpoints, 32);
285 EXPORT_SYMBOL_GPL(usb_remove_function);
288 * usb_function_deactivate - prevent function and gadget enumeration
289 * @function: the function that isn't yet ready to respond
291 * Blocks response of the gadget driver to host enumeration by
292 * preventing the data line pullup from being activated. This is
293 * normally called during @bind() processing to change from the
294 * initial "ready to respond" state, or when a required resource
297 * For example, drivers that serve as a passthrough to a userspace
298 * daemon can block enumeration unless that daemon (such as an OBEX,
299 * MTP, or print server) is ready to handle host requests.
301 * Not all systems support software control of their USB peripheral
304 * Returns zero on success, else negative errno.
306 int usb_function_deactivate(struct usb_function *function)
308 struct usb_composite_dev *cdev = function->config->cdev;
312 spin_lock_irqsave(&cdev->lock, flags);
314 if (cdev->deactivations == 0)
315 status = usb_gadget_deactivate(cdev->gadget);
317 cdev->deactivations++;
319 spin_unlock_irqrestore(&cdev->lock, flags);
322 EXPORT_SYMBOL_GPL(usb_function_deactivate);
325 * usb_function_activate - allow function and gadget enumeration
326 * @function: function on which usb_function_activate() was called
328 * Reverses effect of usb_function_deactivate(). If no more functions
329 * are delaying their activation, the gadget driver will respond to
330 * host enumeration procedures.
332 * Returns zero on success, else negative errno.
334 int usb_function_activate(struct usb_function *function)
336 struct usb_composite_dev *cdev = function->config->cdev;
340 spin_lock_irqsave(&cdev->lock, flags);
342 if (WARN_ON(cdev->deactivations == 0))
345 cdev->deactivations--;
346 if (cdev->deactivations == 0)
347 status = usb_gadget_activate(cdev->gadget);
350 spin_unlock_irqrestore(&cdev->lock, flags);
353 EXPORT_SYMBOL_GPL(usb_function_activate);
356 * usb_interface_id() - allocate an unused interface ID
357 * @config: configuration associated with the interface
358 * @function: function handling the interface
359 * Context: single threaded during gadget setup
361 * usb_interface_id() is called from usb_function.bind() callbacks to
362 * allocate new interface IDs. The function driver will then store that
363 * ID in interface, association, CDC union, and other descriptors. It
364 * will also handle any control requests targeted at that interface,
365 * particularly changing its altsetting via set_alt(). There may
366 * also be class-specific or vendor-specific requests to handle.
368 * All interface identifier should be allocated using this routine, to
369 * ensure that for example different functions don't wrongly assign
370 * different meanings to the same identifier. Note that since interface
371 * identifiers are configuration-specific, functions used in more than
372 * one configuration (or more than once in a given configuration) need
373 * multiple versions of the relevant descriptors.
375 * Returns the interface ID which was allocated; or -ENODEV if no
376 * more interface IDs can be allocated.
378 int usb_interface_id(struct usb_configuration *config,
379 struct usb_function *function)
381 unsigned id = config->next_interface_id;
383 if (id < MAX_CONFIG_INTERFACES) {
384 config->interface[id] = function;
385 if (function->intf_id < 0)
386 function->intf_id = id;
387 config->next_interface_id = id + 1;
392 EXPORT_SYMBOL_GPL(usb_interface_id);
394 static int usb_func_wakeup_int(struct usb_function *func)
397 struct usb_gadget *gadget;
399 pr_debug("%s - %s function wakeup\n",
400 __func__, func->name ? func->name : "");
402 if (!func || !func->config || !func->config->cdev ||
403 !func->config->cdev->gadget)
406 gadget = func->config->cdev->gadget;
407 if ((gadget->speed != USB_SPEED_SUPER) || !func->func_wakeup_allowed) {
408 DBG(func->config->cdev,
409 "Function Wakeup is not possible. speed=%u, func_wakeup_allowed=%u\n",
411 func->func_wakeup_allowed);
416 ret = usb_gadget_func_wakeup(gadget, func->intf_id);
421 int usb_func_wakeup(struct usb_function *func)
426 pr_debug("%s function wakeup\n",
427 func->name ? func->name : "");
429 spin_lock_irqsave(&func->config->cdev->lock, flags);
430 ret = usb_func_wakeup_int(func);
431 if (ret == -EAGAIN) {
432 DBG(func->config->cdev,
433 "Function wakeup for %s could not complete due to suspend state. Delayed until after bus resume.\n",
434 func->name ? func->name : "");
436 } else if (ret < 0 && ret != -ENOTSUPP) {
437 ERROR(func->config->cdev,
438 "Failed to wake function %s from suspend state. ret=%d. Canceling USB request.\n",
439 func->name ? func->name : "", ret);
442 spin_unlock_irqrestore(&func->config->cdev->lock, flags);
445 EXPORT_SYMBOL_GPL(usb_func_wakeup);
447 int usb_func_ep_queue(struct usb_function *func, struct usb_ep *ep,
448 struct usb_request *req, gfp_t gfp_flags)
451 struct usb_gadget *gadget;
453 if (!func || !func->config || !func->config->cdev ||
454 !func->config->cdev->gadget || !ep || !req) {
459 pr_debug("Function %s queueing new data into ep %u\n",
460 func->name ? func->name : "", ep->address);
462 gadget = func->config->cdev->gadget;
464 if (func->func_is_suspended && func->func_wakeup_allowed) {
465 ret = usb_gadget_func_wakeup(gadget, func->intf_id);
466 if (ret == -EAGAIN) {
467 pr_debug("bus suspended func wakeup for %s delayed until bus resume.\n",
468 func->name ? func->name : "");
469 } else if (ret < 0 && ret != -ENOTSUPP) {
470 pr_err("Failed to wake function %s from suspend state. ret=%d.\n",
471 func->name ? func->name : "", ret);
476 if (func->func_is_suspended && !func->func_wakeup_allowed) {
481 ret = usb_ep_queue(ep, req, gfp_flags);
486 static u8 encode_bMaxPower(enum usb_device_speed speed,
487 struct usb_configuration *c)
489 unsigned val = c->MaxPower;
492 case USB_SPEED_SUPER:
493 /* with super-speed report 900mA if user hasn't specified */
495 val = SSUSB_GADGET_VBUS_DRAW;
497 return (u8)(val / SSUSB_GADGET_VBUS_DRAW_UNITS);
500 val = CONFIG_USB_GADGET_VBUS_DRAW;
502 return DIV_ROUND_UP(val, HSUSB_GADGET_VBUS_DRAW_UNITS);
506 static int config_buf(struct usb_configuration *config,
507 enum usb_device_speed speed, void *buf, u8 type)
509 struct usb_config_descriptor *c = buf;
510 void *next = buf + USB_DT_CONFIG_SIZE;
512 struct usb_function *f;
515 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
516 /* write the config descriptor */
518 c->bLength = USB_DT_CONFIG_SIZE;
519 c->bDescriptorType = type;
520 /* wTotalLength is written later */
521 c->bNumInterfaces = config->next_interface_id;
522 c->bConfigurationValue = config->bConfigurationValue;
523 c->iConfiguration = config->iConfiguration;
524 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
525 c->bMaxPower = encode_bMaxPower(speed, config);
526 if (config->cdev->gadget->is_selfpowered) {
527 c->bmAttributes |= USB_CONFIG_ATT_SELFPOWER;
531 /* There may be e.g. OTG descriptors */
532 if (config->descriptors) {
533 status = usb_descriptor_fillbuf(next, len,
534 config->descriptors);
541 /* add each function's descriptors */
542 list_for_each_entry(f, &config->functions, list) {
543 struct usb_descriptor_header **descriptors;
546 case USB_SPEED_SUPER:
547 descriptors = f->ss_descriptors;
550 descriptors = f->hs_descriptors;
553 descriptors = f->fs_descriptors;
558 status = usb_descriptor_fillbuf(next, len,
559 (const struct usb_descriptor_header **) descriptors);
567 c->wTotalLength = cpu_to_le16(len);
571 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
573 struct usb_gadget *gadget = cdev->gadget;
574 struct usb_configuration *c;
575 struct list_head *pos;
576 u8 type = w_value >> 8;
577 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
579 if (gadget->speed == USB_SPEED_SUPER)
580 speed = gadget->speed;
581 else if (gadget_is_dualspeed(gadget)) {
583 if (gadget->speed == USB_SPEED_HIGH)
585 if (type == USB_DT_OTHER_SPEED_CONFIG)
588 speed = USB_SPEED_HIGH;
592 /* This is a lookup by config *INDEX* */
595 pos = &cdev->configs;
596 c = cdev->os_desc_config;
600 while ((pos = pos->next) != &cdev->configs) {
601 c = list_entry(pos, typeof(*c), list);
603 /* skip OS Descriptors config which is handled separately */
604 if (c == cdev->os_desc_config)
608 /* ignore configs that won't work at this speed */
610 case USB_SPEED_SUPER:
624 return config_buf(c, speed, cdev->req->buf, type);
630 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
632 struct usb_gadget *gadget = cdev->gadget;
633 struct usb_configuration *c;
638 if (gadget_is_dualspeed(gadget)) {
639 if (gadget->speed == USB_SPEED_HIGH)
641 if (gadget->speed == USB_SPEED_SUPER)
643 if (type == USB_DT_DEVICE_QUALIFIER)
646 list_for_each_entry(c, &cdev->configs, list) {
647 /* ignore configs that won't work at this speed */
664 * bos_desc() - prepares the BOS descriptor.
665 * @cdev: pointer to usb_composite device to generate the bos
668 * This function generates the BOS (Binary Device Object)
669 * descriptor and its device capabilities descriptors. The BOS
670 * descriptor should be supported by a SuperSpeed device.
672 static int bos_desc(struct usb_composite_dev *cdev)
674 struct usb_ext_cap_descriptor *usb_ext;
675 struct usb_ss_cap_descriptor *ss_cap;
676 struct usb_dcd_config_params dcd_config_params;
677 struct usb_bos_descriptor *bos = cdev->req->buf;
679 bos->bLength = USB_DT_BOS_SIZE;
680 bos->bDescriptorType = USB_DT_BOS;
682 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
683 bos->bNumDeviceCaps = 0;
686 * A SuperSpeed device shall include the USB2.0 extension descriptor
687 * and shall support LPM when operating in USB2.0 HS mode, as well as
688 * a HS device when operating in USB2.1 HS mode.
690 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
691 bos->bNumDeviceCaps++;
692 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
693 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
694 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
695 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
696 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
698 if (gadget_is_superspeed(cdev->gadget)) {
700 * The Superspeed USB Capability descriptor shall be
701 * implemented by all SuperSpeed devices.
703 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
704 bos->bNumDeviceCaps++;
705 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
706 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
707 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
708 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
709 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
710 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
711 USB_FULL_SPEED_OPERATION |
712 USB_HIGH_SPEED_OPERATION |
713 USB_5GBPS_OPERATION);
714 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
716 /* Get Controller configuration */
717 if (cdev->gadget->ops->get_config_params)
718 cdev->gadget->ops->get_config_params
719 (&dcd_config_params);
721 dcd_config_params.bU1devExitLat =
722 USB_DEFAULT_U1_DEV_EXIT_LAT;
723 dcd_config_params.bU2DevExitLat =
724 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
726 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
727 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
730 return le16_to_cpu(bos->wTotalLength);
733 static void device_qual(struct usb_composite_dev *cdev)
735 struct usb_qualifier_descriptor *qual = cdev->req->buf;
737 qual->bLength = sizeof(*qual);
738 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
739 /* POLICY: same bcdUSB and device type info at both speeds */
740 qual->bcdUSB = cdev->desc.bcdUSB;
741 qual->bDeviceClass = cdev->desc.bDeviceClass;
742 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
743 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
744 /* ASSUME same EP0 fifo size at both speeds */
745 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
746 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
750 /*-------------------------------------------------------------------------*/
752 static void reset_config(struct usb_composite_dev *cdev)
754 struct usb_function *f;
756 DBG(cdev, "reset config\n");
758 list_for_each_entry(f, &cdev->config->functions, list) {
762 /* USB 3.0 addition */
763 f->func_is_suspended = false;
764 f->func_wakeup_allowed = false;
765 f->func_wakeup_pending = false;
767 bitmap_zero(f->endpoints, 32);
770 cdev->delayed_status = 0;
773 static int set_config(struct usb_composite_dev *cdev,
774 const struct usb_ctrlrequest *ctrl, unsigned number)
776 struct usb_gadget *gadget = cdev->gadget;
777 struct usb_configuration *c = NULL;
778 int result = -EINVAL;
782 * ignore 2nd time SET_CONFIGURATION
783 * only for same config value twice.
785 if (cdev->config && (cdev->config->bConfigurationValue == number)) {
786 DBG(cdev, "already in the same config with value %d\n",
792 list_for_each_entry(c, &cdev->configs, list) {
793 if (c->bConfigurationValue == number) {
795 * We disable the FDs of the previous
796 * configuration only if the new configuration
807 } else { /* Zero configuration value - need to reset the config */
813 INFO(cdev, "%s config #%d: %s\n",
814 usb_speed_string(gadget->speed),
815 number, c ? c->label : "unconfigured");
820 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
822 c->num_ineps_used = 0;
823 c->num_outeps_used = 0;
825 /* Initialize all interfaces by setting them to altsetting zero. */
826 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
827 struct usb_function *f = c->interface[tmp];
828 struct usb_descriptor_header **descriptors;
834 * Record which endpoints are used by the function. This is used
835 * to dispatch control requests targeted at that endpoint to the
836 * function's setup callback instead of the current
837 * configuration's setup callback.
839 switch (gadget->speed) {
840 case USB_SPEED_SUPER:
841 if (!f->ss_descriptors) {
842 pr_err("%s(): No SS desc for function:%s\n",
844 usb_gadget_set_state(gadget, USB_STATE_ADDRESS);
847 descriptors = f->ss_descriptors;
850 descriptors = f->hs_descriptors;
853 descriptors = f->fs_descriptors;
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);
867 if (usb_endpoint_dir_in(ep))
870 c->num_outeps_used++;
873 result = f->set_alt(f, tmp, 0);
875 DBG(cdev, "interface %d (%s/%pK) alt 0 --> %d\n",
876 tmp, f->name, f, result);
882 if (result == USB_GADGET_DELAYED_STATUS) {
884 "%s: interface %d (%s) requested delayed status\n",
885 __func__, tmp, f->name);
886 cdev->delayed_status++;
887 DBG(cdev, "delayed_status count %d\n",
888 cdev->delayed_status);
893 usb_gadget_vbus_draw(gadget, USB_VBUS_DRAW(gadget->speed));
894 if (result >= 0 && cdev->delayed_status)
895 result = USB_GADGET_DELAYED_STATUS;
899 int usb_add_config_only(struct usb_composite_dev *cdev,
900 struct usb_configuration *config)
902 struct usb_configuration *c;
904 if (!config->bConfigurationValue)
907 /* Prevent duplicate configuration identifiers */
908 list_for_each_entry(c, &cdev->configs, list) {
909 if (c->bConfigurationValue == config->bConfigurationValue)
914 list_add_tail(&config->list, &cdev->configs);
916 INIT_LIST_HEAD(&config->functions);
917 config->next_interface_id = 0;
918 memset(config->interface, 0, sizeof(config->interface));
922 EXPORT_SYMBOL_GPL(usb_add_config_only);
925 * usb_add_config() - add a configuration to a device.
926 * @cdev: wraps the USB gadget
927 * @config: the configuration, with bConfigurationValue assigned
928 * @bind: the configuration's bind function
929 * Context: single threaded during gadget setup
931 * One of the main tasks of a composite @bind() routine is to
932 * add each of the configurations it supports, using this routine.
934 * This function returns the value of the configuration's @bind(), which
935 * is zero for success else a negative errno value. Binding configurations
936 * assigns global resources including string IDs, and per-configuration
937 * resources such as interface IDs and endpoints.
939 int usb_add_config(struct usb_composite_dev *cdev,
940 struct usb_configuration *config,
941 int (*bind)(struct usb_configuration *))
943 int status = -EINVAL;
948 DBG(cdev, "adding config #%u '%s'/%pK\n",
949 config->bConfigurationValue,
950 config->label, config);
952 status = usb_add_config_only(cdev, config);
956 status = bind(config);
958 while (!list_empty(&config->functions)) {
959 struct usb_function *f;
961 f = list_first_entry(&config->functions,
962 struct usb_function, list);
965 DBG(cdev, "unbind function '%s'/%pK\n",
967 f->unbind(config, f);
968 /* may free memory for "f" */
971 list_del(&config->list);
976 DBG(cdev, "cfg %d/%pK speeds:%s%s%s\n",
977 config->bConfigurationValue, config,
978 config->superspeed ? " super" : "",
979 config->highspeed ? " high" : "",
981 ? (gadget_is_dualspeed(cdev->gadget)
986 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
987 struct usb_function *f = config->interface[i];
991 DBG(cdev, " interface %d = %s/%pK\n",
996 /* set_alt(), or next bind(), sets up ep->claimed as needed */
997 usb_ep_autoconfig_reset(cdev->gadget);
1001 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1002 config->bConfigurationValue, status);
1005 EXPORT_SYMBOL_GPL(usb_add_config);
1007 static void remove_config(struct usb_composite_dev *cdev,
1008 struct usb_configuration *config)
1010 while (!list_empty(&config->functions)) {
1011 struct usb_function *f;
1013 f = list_first_entry(&config->functions,
1014 struct usb_function, list);
1017 DBG(cdev, "unbind function '%s'/%pK\n", f->name, f);
1018 f->unbind(config, f);
1019 /* may free memory for "f" */
1022 list_del(&config->list);
1023 if (config->unbind) {
1024 DBG(cdev, "unbind config '%s'/%pK\n", config->label, config);
1025 config->unbind(config);
1026 /* may free memory for "c" */
1031 * usb_remove_config() - remove a configuration from a device.
1032 * @cdev: wraps the USB gadget
1033 * @config: the configuration
1035 * Drivers must call usb_gadget_disconnect before calling this function
1036 * to disconnect the device from the host and make sure the host will not
1037 * try to enumerate the device while we are changing the config list.
1039 void usb_remove_config(struct usb_composite_dev *cdev,
1040 struct usb_configuration *config)
1042 unsigned long flags;
1044 spin_lock_irqsave(&cdev->lock, flags);
1046 if (cdev->config == config)
1049 spin_unlock_irqrestore(&cdev->lock, flags);
1051 remove_config(cdev, config);
1054 /*-------------------------------------------------------------------------*/
1056 /* We support strings in multiple languages ... string descriptor zero
1057 * says which languages are supported. The typical case will be that
1058 * only one language (probably English) is used, with i18n handled on
1062 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1064 const struct usb_gadget_strings *s;
1070 language = cpu_to_le16(s->language);
1071 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
1072 if (*tmp == language)
1081 static int lookup_string(
1082 struct usb_gadget_strings **sp,
1088 struct usb_gadget_strings *s;
1093 if (s->language != language)
1095 value = usb_gadget_get_string(s, id, buf);
1102 static int get_string(struct usb_composite_dev *cdev,
1103 void *buf, u16 language, int id)
1105 struct usb_composite_driver *composite = cdev->driver;
1106 struct usb_gadget_string_container *uc;
1107 struct usb_configuration *c;
1108 struct usb_function *f;
1111 /* Yes, not only is USB's i18n support probably more than most
1112 * folk will ever care about ... also, it's all supported here.
1113 * (Except for UTF8 support for Unicode's "Astral Planes".)
1116 /* 0 == report all available language codes */
1118 struct usb_string_descriptor *s = buf;
1119 struct usb_gadget_strings **sp;
1122 s->bDescriptorType = USB_DT_STRING;
1124 sp = composite->strings;
1126 collect_langs(sp, s->wData);
1128 list_for_each_entry(c, &cdev->configs, list) {
1131 collect_langs(sp, s->wData);
1133 list_for_each_entry(f, &c->functions, list) {
1136 collect_langs(sp, s->wData);
1139 list_for_each_entry(uc, &cdev->gstrings, list) {
1140 struct usb_gadget_strings **sp;
1142 sp = get_containers_gs(uc);
1143 collect_langs(sp, s->wData);
1146 for (len = 0; len <= 126 && s->wData[len]; len++)
1151 s->bLength = 2 * (len + 1);
1155 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1156 struct usb_os_string *b = buf;
1157 b->bLength = sizeof(*b);
1158 b->bDescriptorType = USB_DT_STRING;
1160 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1161 "qwSignature size must be equal to qw_sign");
1162 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1163 b->bMS_VendorCode = cdev->b_vendor_code;
1168 list_for_each_entry(uc, &cdev->gstrings, list) {
1169 struct usb_gadget_strings **sp;
1171 sp = get_containers_gs(uc);
1172 len = lookup_string(sp, buf, language, id);
1177 /* String IDs are device-scoped, so we look up each string
1178 * table we're told about. These lookups are infrequent;
1179 * simpler-is-better here.
1181 if (composite->strings) {
1182 len = lookup_string(composite->strings, buf, language, id);
1186 list_for_each_entry(c, &cdev->configs, list) {
1188 len = lookup_string(c->strings, buf, language, id);
1192 list_for_each_entry(f, &c->functions, list) {
1195 len = lookup_string(f->strings, buf, language, id);
1204 * usb_string_id() - allocate an unused string ID
1205 * @cdev: the device whose string descriptor IDs are being allocated
1206 * Context: single threaded during gadget setup
1208 * @usb_string_id() is called from bind() callbacks to allocate
1209 * string IDs. Drivers for functions, configurations, or gadgets will
1210 * then store that ID in the appropriate descriptors and string table.
1212 * All string identifier should be allocated using this,
1213 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1214 * that for example different functions don't wrongly assign different
1215 * meanings to the same identifier.
1217 int usb_string_id(struct usb_composite_dev *cdev)
1219 if (cdev->next_string_id < 254) {
1220 /* string id 0 is reserved by USB spec for list of
1221 * supported languages */
1222 /* 255 reserved as well? -- mina86 */
1223 cdev->next_string_id++;
1224 return cdev->next_string_id;
1228 EXPORT_SYMBOL_GPL(usb_string_id);
1231 * usb_string_ids() - allocate unused string IDs in batch
1232 * @cdev: the device whose string descriptor IDs are being allocated
1233 * @str: an array of usb_string objects to assign numbers to
1234 * Context: single threaded during gadget setup
1236 * @usb_string_ids() is called from bind() callbacks to allocate
1237 * string IDs. Drivers for functions, configurations, or gadgets will
1238 * then copy IDs from the string table to the appropriate descriptors
1239 * and string table for other languages.
1241 * All string identifier should be allocated using this,
1242 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1243 * example different functions don't wrongly assign different meanings
1244 * to the same identifier.
1246 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1248 int next = cdev->next_string_id;
1250 for (; str->s; ++str) {
1251 if (unlikely(next >= 254))
1256 cdev->next_string_id = next;
1260 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1262 static struct usb_gadget_string_container *copy_gadget_strings(
1263 struct usb_gadget_strings **sp, unsigned n_gstrings,
1266 struct usb_gadget_string_container *uc;
1267 struct usb_gadget_strings **gs_array;
1268 struct usb_gadget_strings *gs;
1269 struct usb_string *s;
1276 mem += sizeof(void *) * (n_gstrings + 1);
1277 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1278 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1279 uc = kmalloc(mem, GFP_KERNEL);
1281 return ERR_PTR(-ENOMEM);
1282 gs_array = get_containers_gs(uc);
1284 stash += sizeof(void *) * (n_gstrings + 1);
1285 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1286 struct usb_string *org_s;
1288 gs_array[n_gs] = stash;
1289 gs = gs_array[n_gs];
1290 stash += sizeof(struct usb_gadget_strings);
1291 gs->language = sp[n_gs]->language;
1292 gs->strings = stash;
1293 org_s = sp[n_gs]->strings;
1295 for (n_s = 0; n_s < n_strings; n_s++) {
1297 stash += sizeof(struct usb_string);
1306 stash += sizeof(struct usb_string);
1309 gs_array[n_gs] = NULL;
1314 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1315 * @cdev: the device whose string descriptor IDs are being allocated
1317 * @sp: an array of usb_gadget_strings to attach.
1318 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1320 * This function will create a deep copy of usb_gadget_strings and usb_string
1321 * and attach it to the cdev. The actual string (usb_string.s) will not be
1322 * copied but only a referenced will be made. The struct usb_gadget_strings
1323 * array may contain multiple languages and should be NULL terminated.
1324 * The ->language pointer of each struct usb_gadget_strings has to contain the
1325 * same amount of entries.
1326 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1327 * usb_string entry of es-ES contains the translation of the first usb_string
1328 * entry of en-US. Therefore both entries become the same id assign.
1330 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1331 struct usb_gadget_strings **sp, unsigned n_strings)
1333 struct usb_gadget_string_container *uc;
1334 struct usb_gadget_strings **n_gs;
1335 unsigned n_gstrings = 0;
1339 for (i = 0; sp[i]; i++)
1343 return ERR_PTR(-EINVAL);
1345 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1347 return ERR_CAST(uc);
1349 n_gs = get_containers_gs(uc);
1350 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1354 for (i = 1; i < n_gstrings; i++) {
1355 struct usb_string *m_s;
1356 struct usb_string *s;
1359 m_s = n_gs[0]->strings;
1360 s = n_gs[i]->strings;
1361 for (n = 0; n < n_strings; n++) {
1367 list_add_tail(&uc->list, &cdev->gstrings);
1368 return n_gs[0]->strings;
1371 return ERR_PTR(ret);
1373 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1376 * usb_string_ids_n() - allocate unused string IDs in batch
1377 * @c: the device whose string descriptor IDs are being allocated
1378 * @n: number of string IDs to allocate
1379 * Context: single threaded during gadget setup
1381 * Returns the first requested ID. This ID and next @n-1 IDs are now
1382 * valid IDs. At least provided that @n is non-zero because if it
1383 * is, returns last requested ID which is now very useful information.
1385 * @usb_string_ids_n() is called from bind() callbacks to allocate
1386 * string IDs. Drivers for functions, configurations, or gadgets will
1387 * then store that ID in the appropriate descriptors and string table.
1389 * All string identifier should be allocated using this,
1390 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1391 * example different functions don't wrongly assign different meanings
1392 * to the same identifier.
1394 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1396 unsigned next = c->next_string_id;
1397 if (unlikely(n > 254 || (unsigned)next + n > 254))
1399 c->next_string_id += n;
1402 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1404 /*-------------------------------------------------------------------------*/
1406 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1408 struct usb_composite_dev *cdev;
1410 if (req->status || req->actual != req->length)
1411 DBG((struct usb_composite_dev *) ep->driver_data,
1412 "setup complete --> %d, %d/%d\n",
1413 req->status, req->actual, req->length);
1416 * REVIST The same ep0 requests are shared with function drivers
1417 * so they don't have to maintain the same ->complete() stubs.
1419 * Because of that, we need to check for the validity of ->context
1420 * here, even though we know we've set it to something useful.
1425 cdev = req->context;
1427 if (cdev->req == req)
1428 cdev->setup_pending = false;
1429 else if (cdev->os_desc_req == req)
1430 cdev->os_desc_pending = false;
1432 WARN(1, "unknown request %pK\n", req);
1435 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1436 struct usb_request *req, gfp_t gfp_flags)
1440 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1442 if (cdev->req == req)
1443 cdev->setup_pending = true;
1444 else if (cdev->os_desc_req == req)
1445 cdev->os_desc_pending = true;
1447 WARN(1, "unknown request %pK\n", req);
1453 static int count_ext_compat(struct usb_configuration *c)
1458 for (i = 0; i < c->next_interface_id; ++i) {
1459 struct usb_function *f;
1462 f = c->interface[i];
1463 for (j = 0; j < f->os_desc_n; ++j) {
1464 struct usb_os_desc *d;
1466 if (i != f->os_desc_table[j].if_id)
1468 d = f->os_desc_table[j].os_desc;
1469 if (d && d->ext_compat_id)
1477 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1482 for (i = 0; i < c->next_interface_id; ++i) {
1483 struct usb_function *f;
1486 f = c->interface[i];
1487 for (j = 0; j < f->os_desc_n; ++j) {
1488 struct usb_os_desc *d;
1490 if (i != f->os_desc_table[j].if_id)
1492 d = f->os_desc_table[j].os_desc;
1493 if (d && d->ext_compat_id) {
1496 memcpy(buf, d->ext_compat_id, 16);
1504 if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1512 static int count_ext_prop(struct usb_configuration *c, int interface)
1514 struct usb_function *f;
1517 f = c->interface[interface];
1518 for (j = 0; j < f->os_desc_n; ++j) {
1519 struct usb_os_desc *d;
1521 if (interface != f->os_desc_table[j].if_id)
1523 d = f->os_desc_table[j].os_desc;
1524 if (d && d->ext_compat_id)
1525 return d->ext_prop_count;
1530 static int len_ext_prop(struct usb_configuration *c, int interface)
1532 struct usb_function *f;
1533 struct usb_os_desc *d;
1536 res = 10; /* header length */
1537 f = c->interface[interface];
1538 for (j = 0; j < f->os_desc_n; ++j) {
1539 if (interface != f->os_desc_table[j].if_id)
1541 d = f->os_desc_table[j].os_desc;
1543 return min(res + d->ext_prop_len, 4096);
1548 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1550 struct usb_function *f;
1551 struct usb_os_desc *d;
1552 struct usb_os_desc_ext_prop *ext_prop;
1553 int j, count, n, ret;
1555 f = c->interface[interface];
1556 count = 10; /* header length */
1557 for (j = 0; j < f->os_desc_n; ++j) {
1558 if (interface != f->os_desc_table[j].if_id)
1560 d = f->os_desc_table[j].os_desc;
1562 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1563 n = ext_prop->data_len +
1564 ext_prop->name_len + 14;
1565 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1567 usb_ext_prop_put_size(buf, n);
1568 usb_ext_prop_put_type(buf, ext_prop->type);
1569 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1570 ext_prop->name_len);
1573 switch (ext_prop->type) {
1574 case USB_EXT_PROP_UNICODE:
1575 case USB_EXT_PROP_UNICODE_ENV:
1576 case USB_EXT_PROP_UNICODE_LINK:
1577 usb_ext_prop_put_unicode(buf, ret,
1579 ext_prop->data_len);
1581 case USB_EXT_PROP_BINARY:
1582 usb_ext_prop_put_binary(buf, ret,
1584 ext_prop->data_len);
1586 case USB_EXT_PROP_LE32:
1587 /* not implemented */
1588 case USB_EXT_PROP_BE32:
1589 /* not implemented */
1602 * The setup() callback implements all the ep0 functionality that's
1603 * not handled lower down, in hardware or the hardware driver(like
1604 * device and endpoint feature flags, and their status). It's all
1605 * housekeeping for the gadget function we're implementing. Most of
1606 * the work is in config and function specific setup.
1609 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1611 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1612 struct usb_request *req = cdev->req;
1613 int value = -EOPNOTSUPP;
1615 u16 w_index = le16_to_cpu(ctrl->wIndex);
1616 u8 intf = w_index & 0xFF;
1617 u16 w_value = le16_to_cpu(ctrl->wValue);
1618 u16 w_length = le16_to_cpu(ctrl->wLength);
1619 struct usb_function *f = NULL;
1622 /* partial re-init of the response message; the function or the
1623 * gadget might need to intercept e.g. a control-OUT completion
1624 * when we delegate to it.
1627 req->context = cdev;
1628 req->complete = composite_setup_complete;
1630 gadget->ep0->driver_data = cdev;
1633 * Don't let non-standard requests match any of the cases below
1636 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1639 switch (ctrl->bRequest) {
1641 /* we handle all standard USB descriptors */
1642 case USB_REQ_GET_DESCRIPTOR:
1643 if (ctrl->bRequestType != USB_DIR_IN)
1645 switch (w_value >> 8) {
1648 cdev->desc.bNumConfigurations =
1649 count_configs(cdev, USB_DT_DEVICE);
1650 if (cdev->desc.bNumConfigurations == 0) {
1651 pr_err("%s:config is not active. send stall\n",
1656 cdev->desc.bMaxPacketSize0 =
1657 cdev->gadget->ep0->maxpacket;
1658 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1659 if (gadget_is_superspeed(gadget)) {
1660 if (gadget->speed >= USB_SPEED_SUPER) {
1661 cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1662 cdev->desc.bMaxPacketSize0 = 9;
1663 } else if (!disable_l1_for_hs) {
1664 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1666 "Config HS device with LPM(L1)\n");
1670 value = min(w_length, (u16) sizeof cdev->desc);
1671 memcpy(req->buf, &cdev->desc, value);
1673 case USB_DT_DEVICE_QUALIFIER:
1674 if (!gadget_is_dualspeed(gadget) ||
1675 gadget->speed >= USB_SPEED_SUPER)
1677 spin_lock(&cdev->lock);
1679 spin_unlock(&cdev->lock);
1680 value = min_t(int, w_length,
1681 sizeof(struct usb_qualifier_descriptor));
1683 case USB_DT_OTHER_SPEED_CONFIG:
1684 if (!gadget_is_dualspeed(gadget) ||
1685 gadget->speed >= USB_SPEED_SUPER)
1689 spin_lock(&cdev->lock);
1690 value = config_desc(cdev, w_value);
1691 spin_unlock(&cdev->lock);
1693 value = min(w_length, (u16) value);
1696 spin_lock(&cdev->lock);
1697 value = get_string(cdev, req->buf,
1698 w_index, w_value & 0xff);
1699 spin_unlock(&cdev->lock);
1701 value = min(w_length, (u16) value);
1704 if ((gadget_is_superspeed(gadget) &&
1705 (gadget->speed >= USB_SPEED_SUPER))
1706 || !disable_l1_for_hs) {
1707 value = bos_desc(cdev);
1708 value = min(w_length, (u16) value);
1712 if (gadget_is_otg(gadget)) {
1713 struct usb_configuration *config;
1714 int otg_desc_len = 0;
1717 config = cdev->config;
1719 config = list_first_entry(
1721 struct usb_configuration, list);
1725 if (gadget->otg_caps &&
1726 (gadget->otg_caps->otg_rev >= 0x0200))
1727 otg_desc_len += sizeof(
1728 struct usb_otg20_descriptor);
1730 otg_desc_len += sizeof(
1731 struct usb_otg_descriptor);
1733 value = min_t(int, w_length, otg_desc_len);
1734 memcpy(req->buf, config->descriptors[0], value);
1740 /* any number of configs can work */
1741 case USB_REQ_SET_CONFIGURATION:
1742 if (ctrl->bRequestType != 0)
1744 if (gadget_is_otg(gadget)) {
1745 if (gadget->a_hnp_support)
1746 DBG(cdev, "HNP available\n");
1747 else if (gadget->a_alt_hnp_support)
1748 DBG(cdev, "HNP on another port\n");
1750 VDBG(cdev, "HNP inactive\n");
1752 spin_lock(&cdev->lock);
1753 value = set_config(cdev, ctrl, w_value);
1754 spin_unlock(&cdev->lock);
1756 case USB_REQ_GET_CONFIGURATION:
1757 if (ctrl->bRequestType != USB_DIR_IN)
1760 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1762 *(u8 *)req->buf = 0;
1763 value = min(w_length, (u16) 1);
1766 /* function drivers must handle get/set altsetting */
1767 case USB_REQ_SET_INTERFACE:
1768 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1770 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1772 f = cdev->config->interface[intf];
1777 * If there's no get_alt() method, we know only altsetting zero
1778 * works. There is no need to check if set_alt() is not NULL
1779 * as we check this in usb_add_function().
1781 if (w_value && !f->get_alt)
1784 spin_lock(&cdev->lock);
1785 value = f->set_alt(f, w_index, w_value);
1786 if (value == USB_GADGET_DELAYED_STATUS) {
1788 "%s: interface %d (%s) requested delayed status\n",
1789 __func__, intf, f->name);
1790 cdev->delayed_status++;
1791 DBG(cdev, "delayed_status count %d\n",
1792 cdev->delayed_status);
1794 spin_unlock(&cdev->lock);
1796 case USB_REQ_GET_INTERFACE:
1797 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1799 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1801 f = cdev->config->interface[intf];
1804 /* lots of interfaces only need altsetting zero... */
1805 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1808 *((u8 *)req->buf) = value;
1809 value = min(w_length, (u16) 1);
1813 * USB 3.0 additions:
1814 * Function driver should handle get_status request. If such cb
1815 * wasn't supplied we respond with default value = 0
1816 * Note: function driver should supply such cb only for the first
1817 * interface of the function
1819 case USB_REQ_GET_STATUS:
1820 if (!gadget_is_superspeed(gadget))
1822 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1824 value = 2; /* This is the length of the get_status reply */
1825 put_unaligned_le16(0, req->buf);
1826 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1828 f = cdev->config->interface[intf];
1831 status = f->get_status ? f->get_status(f) : 0;
1834 put_unaligned_le16(status & 0x0000ffff, req->buf);
1837 * Function drivers should handle SetFeature/ClearFeature
1838 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1839 * only for the first interface of the function
1841 case USB_REQ_CLEAR_FEATURE:
1842 case USB_REQ_SET_FEATURE:
1843 if (!gadget_is_superspeed(gadget))
1845 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1848 case USB_INTRF_FUNC_SUSPEND:
1849 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1851 f = cdev->config->interface[intf];
1855 if (f->func_suspend) {
1856 const u8 suspend_opt = w_index >> 8;
1858 value = f->func_suspend(f, suspend_opt);
1859 DBG(cdev, "%s function: FUNCTION_SUSPEND(%u)",
1860 f->name ? f->name : "", suspend_opt);
1864 "func_suspend() returned error %d\n",
1874 * OS descriptors handling
1876 if (cdev->use_os_string && cdev->os_desc_config &&
1877 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1878 ctrl->bRequest == cdev->b_vendor_code) {
1879 struct usb_request *req;
1880 struct usb_configuration *os_desc_cfg;
1885 req = cdev->os_desc_req;
1886 req->context = cdev;
1887 req->complete = composite_setup_complete;
1889 os_desc_cfg = cdev->os_desc_config;
1890 w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1891 memset(buf, 0, w_length);
1893 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1894 case USB_RECIP_DEVICE:
1895 if (w_index != 0x4 || (w_value >> 8))
1898 if (w_length == 0x10) {
1899 /* Number of ext compat interfaces */
1900 count = count_ext_compat(os_desc_cfg);
1902 count *= 24; /* 24 B/ext compat desc */
1903 count += 16; /* header */
1904 put_unaligned_le32(count, buf);
1907 /* "extended compatibility ID"s */
1908 count = count_ext_compat(os_desc_cfg);
1910 count *= 24; /* 24 B/ext compat desc */
1911 count += 16; /* header */
1912 put_unaligned_le32(count, buf);
1914 value = fill_ext_compat(os_desc_cfg, buf);
1915 value = min_t(u16, w_length, value);
1918 case USB_RECIP_INTERFACE:
1919 if (w_index != 0x5 || (w_value >> 8))
1921 interface = w_value & 0xFF;
1923 if (w_length == 0x0A) {
1924 count = count_ext_prop(os_desc_cfg,
1926 put_unaligned_le16(count, buf + 8);
1927 count = len_ext_prop(os_desc_cfg,
1929 put_unaligned_le32(count, buf);
1933 count = count_ext_prop(os_desc_cfg,
1935 put_unaligned_le16(count, buf + 8);
1936 count = len_ext_prop(os_desc_cfg,
1938 put_unaligned_le32(count, buf);
1940 value = fill_ext_prop(os_desc_cfg,
1944 value = min_t(u16, w_length, value);
1950 DBG(cdev, "%s: unhandled os desc request\n",
1952 DBG(cdev, "req%02x.%02x v%04x i%04x l%d\n",
1953 ctrl->bRequestType, ctrl->bRequest,
1954 w_value, w_index, w_length);
1958 req->length = value;
1959 req->context = cdev;
1960 req->zero = value < w_length;
1961 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1963 DBG(cdev, "ep_queue --> %d\n", value);
1965 if (value != -ESHUTDOWN)
1966 composite_setup_complete(gadget->ep0,
1973 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1974 ctrl->bRequestType, ctrl->bRequest,
1975 w_value, w_index, w_length);
1977 /* functions always handle their interfaces and endpoints...
1978 * punt other recipients (other, WUSB, ...) to the current
1979 * configuration code.
1981 * REVISIT it could make sense to let the composite device
1982 * take such requests too, if that's ever needed: to work
1986 list_for_each_entry(f, &cdev->config->functions, list)
1987 if (f->req_match && f->req_match(f, ctrl))
1992 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1993 case USB_RECIP_INTERFACE:
1994 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1996 f = cdev->config->interface[intf];
1999 case USB_RECIP_ENDPOINT:
2002 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
2003 list_for_each_entry(f, &cdev->config->functions, list) {
2004 if (test_bit(endp, f->endpoints))
2007 if (&f->list == &cdev->config->functions)
2013 value = f->setup(f, ctrl);
2015 struct usb_configuration *c;
2021 /* try current config's setup */
2023 value = c->setup(c, ctrl);
2027 /* try the only function in the current config */
2028 if (!list_is_singular(&c->functions))
2030 f = list_first_entry(&c->functions, struct usb_function,
2033 value = f->setup(f, ctrl);
2035 if (value == USB_GADGET_DELAYED_STATUS) {
2037 "%s: interface %d (%s) requested delayed status\n",
2038 __func__, intf, f->name);
2039 cdev->delayed_status++;
2040 DBG(cdev, "delayed_status count %d\n",
2041 cdev->delayed_status);
2047 /* respond with data transfer before status phase? */
2048 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2049 req->length = value;
2050 req->context = cdev;
2051 req->zero = value < w_length;
2052 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2054 DBG(cdev, "ep_queue --> %d\n", value);
2056 if (value != -ESHUTDOWN)
2057 composite_setup_complete(gadget->ep0, req);
2059 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2061 "%s: Delayed status not supported for w_length != 0",
2066 /* device either stalls (value < 0) or reports success */
2070 void composite_disconnect(struct usb_gadget *gadget)
2072 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2073 unsigned long flags;
2076 WARN(1, "%s: Calling disconnect on a Gadget that is \
2077 not connected\n", __func__);
2081 /* REVISIT: should we have config and device level
2082 * disconnect callbacks?
2084 spin_lock_irqsave(&cdev->lock, flags);
2085 cdev->suspended = 0;
2088 if (cdev->driver->disconnect)
2089 cdev->driver->disconnect(cdev);
2090 if (cdev->delayed_status != 0) {
2091 INFO(cdev, "delayed status mismatch..resetting\n");
2092 cdev->delayed_status = 0;
2094 spin_unlock_irqrestore(&cdev->lock, flags);
2097 /*-------------------------------------------------------------------------*/
2099 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2102 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2103 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2105 return snprintf(buf, PAGE_SIZE, "%d\n", cdev->suspended);
2107 static DEVICE_ATTR_RO(suspended);
2109 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2111 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2112 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2113 struct usb_string *dev_str = gstr->strings;
2115 /* composite_disconnect() must already have been called
2116 * by the underlying peripheral controller driver!
2117 * so there's no i/o concurrency that could affect the
2118 * state protected by cdev->lock.
2120 WARN_ON(cdev->config);
2122 while (!list_empty(&cdev->configs)) {
2123 struct usb_configuration *c;
2124 c = list_first_entry(&cdev->configs,
2125 struct usb_configuration, list);
2126 remove_config(cdev, c);
2128 if (cdev->driver->unbind && unbind_driver)
2129 cdev->driver->unbind(cdev);
2131 composite_dev_cleanup(cdev);
2133 if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2134 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2136 kfree(cdev->def_manufacturer);
2138 set_gadget_data(gadget, NULL);
2141 static void composite_unbind(struct usb_gadget *gadget)
2143 __composite_unbind(gadget, true);
2146 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2147 const struct usb_device_descriptor *old)
2157 * these variables may have been set in
2158 * usb_composite_overwrite_options()
2160 idVendor = new->idVendor;
2161 idProduct = new->idProduct;
2162 bcdDevice = new->bcdDevice;
2163 iSerialNumber = new->iSerialNumber;
2164 iManufacturer = new->iManufacturer;
2165 iProduct = new->iProduct;
2169 new->idVendor = idVendor;
2171 new->idProduct = idProduct;
2173 new->bcdDevice = bcdDevice;
2175 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2177 new->iSerialNumber = iSerialNumber;
2179 new->iManufacturer = iManufacturer;
2181 new->iProduct = iProduct;
2184 int composite_dev_prepare(struct usb_composite_driver *composite,
2185 struct usb_composite_dev *cdev)
2187 struct usb_gadget *gadget = cdev->gadget;
2190 /* preallocate control response and buffer */
2191 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2195 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2196 if (!cdev->req->buf)
2199 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2203 cdev->req->complete = composite_setup_complete;
2204 cdev->req->context = cdev;
2205 gadget->ep0->driver_data = cdev;
2207 cdev->driver = composite;
2210 * As per USB compliance update, a device that is actively drawing
2211 * more than 100mA from USB must report itself as bus-powered in
2212 * the GetStatus(DEVICE) call.
2214 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2215 usb_gadget_set_selfpowered(gadget);
2217 /* interface and string IDs start at zero via kzalloc.
2218 * we force endpoints to start unassigned; few controller
2219 * drivers will zero ep->driver_data.
2221 usb_ep_autoconfig_reset(gadget);
2224 kfree(cdev->req->buf);
2226 usb_ep_free_request(gadget->ep0, cdev->req);
2231 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2236 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2237 if (!cdev->os_desc_req) {
2238 ret = PTR_ERR(cdev->os_desc_req);
2242 cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2244 if (!cdev->os_desc_req->buf) {
2245 ret = PTR_ERR(cdev->os_desc_req->buf);
2246 kfree(cdev->os_desc_req);
2249 cdev->os_desc_req->context = cdev;
2250 cdev->os_desc_req->complete = composite_setup_complete;
2255 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2257 struct usb_gadget_string_container *uc, *tmp;
2259 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2260 list_del(&uc->list);
2263 if (cdev->os_desc_req) {
2264 if (cdev->os_desc_pending)
2265 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2267 kfree(cdev->os_desc_req->buf);
2268 cdev->os_desc_req->buf = NULL;
2269 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2270 cdev->os_desc_req = NULL;
2273 if (cdev->setup_pending)
2274 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2276 kfree(cdev->req->buf);
2277 cdev->req->buf = NULL;
2278 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2281 cdev->next_string_id = 0;
2282 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2285 static int composite_bind(struct usb_gadget *gadget,
2286 struct usb_gadget_driver *gdriver)
2288 struct usb_composite_dev *cdev;
2289 struct usb_composite_driver *composite = to_cdriver(gdriver);
2290 int status = -ENOMEM;
2292 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2296 spin_lock_init(&cdev->lock);
2297 cdev->gadget = gadget;
2298 set_gadget_data(gadget, cdev);
2299 INIT_LIST_HEAD(&cdev->configs);
2300 INIT_LIST_HEAD(&cdev->gstrings);
2302 status = composite_dev_prepare(composite, cdev);
2306 /* composite gadget needs to assign strings for whole device (like
2307 * serial number), register function drivers, potentially update
2308 * power state and consumption, etc
2310 status = composite->bind(cdev);
2314 if (cdev->use_os_string) {
2315 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2320 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2322 /* has userspace failed to provide a serial number? */
2323 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2324 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2326 INFO(cdev, "%s ready\n", composite->name);
2330 __composite_unbind(gadget, false);
2334 /*-------------------------------------------------------------------------*/
2336 void composite_suspend(struct usb_gadget *gadget)
2338 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2339 struct usb_function *f;
2340 unsigned long flags;
2342 /* REVISIT: should we have config level
2343 * suspend/resume callbacks?
2345 DBG(cdev, "suspend\n");
2346 spin_lock_irqsave(&cdev->lock, flags);
2348 list_for_each_entry(f, &cdev->config->functions, list) {
2353 if (cdev->driver->suspend)
2354 cdev->driver->suspend(cdev);
2356 cdev->suspended = 1;
2357 spin_unlock_irqrestore(&cdev->lock, flags);
2359 usb_gadget_vbus_draw(gadget, 2);
2362 void composite_resume(struct usb_gadget *gadget)
2364 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2365 struct usb_function *f;
2367 unsigned long flags;
2369 /* REVISIT: should we have config level
2370 * suspend/resume callbacks?
2372 DBG(cdev, "resume\n");
2373 if (cdev->driver->resume)
2374 cdev->driver->resume(cdev);
2376 spin_lock_irqsave(&cdev->lock, flags);
2378 list_for_each_entry(f, &cdev->config->functions, list) {
2379 ret = usb_func_wakeup_int(f);
2381 if (ret == -EAGAIN) {
2382 ERROR(f->config->cdev,
2383 "Function wakeup for %s could not complete due to suspend state.\n",
2384 f->name ? f->name : "");
2386 } else if (ret != -ENOTSUPP) {
2387 ERROR(f->config->cdev,
2388 "Failed to wake function %s from suspend state. ret=%d. Canceling USB request.\n",
2389 f->name ? f->name : "",
2398 usb_gadget_vbus_draw(gadget, USB_VBUS_DRAW(gadget->speed));
2401 spin_unlock_irqrestore(&cdev->lock, flags);
2402 cdev->suspended = 0;
2405 /*-------------------------------------------------------------------------*/
2407 static const struct usb_gadget_driver composite_driver_template = {
2408 .bind = composite_bind,
2409 .unbind = composite_unbind,
2411 .setup = composite_setup,
2412 .reset = composite_disconnect,
2413 .disconnect = composite_disconnect,
2415 .suspend = composite_suspend,
2416 .resume = composite_resume,
2419 .owner = THIS_MODULE,
2424 * usb_composite_probe() - register a composite driver
2425 * @driver: the driver to register
2427 * Context: single threaded during gadget setup
2429 * This function is used to register drivers using the composite driver
2430 * framework. The return value is zero, or a negative errno value.
2431 * Those values normally come from the driver's @bind method, which does
2432 * all the work of setting up the driver to match the hardware.
2434 * On successful return, the gadget is ready to respond to requests from
2435 * the host, unless one of its components invokes usb_gadget_disconnect()
2436 * while it was binding. That would usually be done in order to wait for
2437 * some userspace participation.
2439 int usb_composite_probe(struct usb_composite_driver *driver)
2441 struct usb_gadget_driver *gadget_driver;
2443 if (!driver || !driver->dev || !driver->bind)
2447 driver->name = "composite";
2449 driver->gadget_driver = composite_driver_template;
2450 gadget_driver = &driver->gadget_driver;
2452 gadget_driver->function = (char *) driver->name;
2453 gadget_driver->driver.name = driver->name;
2454 gadget_driver->max_speed = driver->max_speed;
2456 return usb_gadget_probe_driver(gadget_driver);
2458 EXPORT_SYMBOL_GPL(usb_composite_probe);
2461 * usb_composite_unregister() - unregister a composite driver
2462 * @driver: the driver to unregister
2464 * This function is used to unregister drivers using the composite
2467 void usb_composite_unregister(struct usb_composite_driver *driver)
2469 usb_gadget_unregister_driver(&driver->gadget_driver);
2471 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2474 * usb_composite_setup_continue() - Continue with the control transfer
2475 * @cdev: the composite device who's control transfer was kept waiting
2477 * This function must be called by the USB function driver to continue
2478 * with the control transfer's data/status stage in case it had requested to
2479 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2480 * can request the composite framework to delay the setup request's data/status
2481 * stages by returning USB_GADGET_DELAYED_STATUS.
2483 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2486 struct usb_request *req = cdev->req;
2487 unsigned long flags;
2489 DBG(cdev, "%s\n", __func__);
2490 spin_lock_irqsave(&cdev->lock, flags);
2492 if (cdev->delayed_status == 0) {
2493 if (!cdev->config) {
2494 spin_unlock_irqrestore(&cdev->lock, flags);
2497 spin_unlock_irqrestore(&cdev->lock, flags);
2498 WARN(cdev, "%s: Unexpected call\n", __func__);
2501 } else if (--cdev->delayed_status == 0) {
2502 DBG(cdev, "%s: Completing delayed status\n", __func__);
2504 req->context = cdev;
2505 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2507 DBG(cdev, "ep_queue --> %d\n", value);
2509 composite_setup_complete(cdev->gadget->ep0, req);
2513 spin_unlock_irqrestore(&cdev->lock, flags);
2515 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2517 static char *composite_default_mfr(struct usb_gadget *gadget)
2522 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2523 init_utsname()->release, gadget->name);
2525 mfr = kmalloc(len, GFP_KERNEL);
2528 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2529 init_utsname()->release, gadget->name);
2533 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2534 struct usb_composite_overwrite *covr)
2536 struct usb_device_descriptor *desc = &cdev->desc;
2537 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2538 struct usb_string *dev_str = gstr->strings;
2541 desc->idVendor = cpu_to_le16(covr->idVendor);
2543 if (covr->idProduct)
2544 desc->idProduct = cpu_to_le16(covr->idProduct);
2546 if (covr->bcdDevice)
2547 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2549 if (covr->serial_number) {
2550 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2551 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2553 if (covr->manufacturer) {
2554 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2555 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2557 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2558 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2559 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2560 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2563 if (covr->product) {
2564 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2565 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2568 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2570 MODULE_LICENSE("GPL");
2571 MODULE_AUTHOR("David Brownell");