2 * composite.c - infrastructure for Composite USB Gadgets
4 * Copyright (C) 2006-2008 David Brownell
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
12 /* #define VERBOSE_DEBUG */
14 #include <linux/kallsyms.h>
15 #include <linux/kernel.h>
16 #include <linux/slab.h>
17 #include <linux/module.h>
18 #include <linux/device.h>
19 #include <linux/utsname.h>
21 #include <linux/usb/composite.h>
22 #include <linux/usb/otg.h>
23 #include <asm/unaligned.h>
25 #include "u_os_desc.h"
28 * struct usb_os_string - represents OS String to be reported by a gadget
29 * @bLength: total length of the entire descritor, always 0x12
30 * @bDescriptorType: USB_DT_STRING
31 * @qwSignature: the OS String proper
32 * @bMS_VendorCode: code used by the host for subsequent requests
33 * @bPad: not used, must be zero
35 struct usb_os_string {
38 __u8 qwSignature[OS_STRING_QW_SIGN_LEN];
44 * The code in this file is utility code, used to build a gadget driver
45 * from one or more "function" drivers, one or more "configuration"
46 * objects, and a "usb_composite_driver" by gluing them together along
47 * with the relevant device-wide data.
50 static struct usb_gadget_strings **get_containers_gs(
51 struct usb_gadget_string_container *uc)
53 return (struct usb_gadget_strings **)uc->stash;
57 * next_ep_desc() - advance to the next EP descriptor
58 * @t: currect pointer within descriptor array
60 * Return: next EP descriptor or NULL
62 * Iterate over @t until either EP descriptor found or
63 * NULL (that indicates end of list) encountered
65 static struct usb_descriptor_header**
66 next_ep_desc(struct usb_descriptor_header **t)
69 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
76 * for_each_ep_desc()- iterate over endpoint descriptors in the
78 * @start: pointer within descriptor array.
79 * @ep_desc: endpoint descriptor to use as the loop cursor
81 #define for_each_ep_desc(start, ep_desc) \
82 for (ep_desc = next_ep_desc(start); \
83 ep_desc; ep_desc = next_ep_desc(ep_desc+1))
86 * config_ep_by_speed() - configures the given endpoint
87 * according to gadget speed.
88 * @g: pointer to the gadget
90 * @_ep: the endpoint to configure
92 * Return: error code, 0 on success
94 * This function chooses the right descriptors for a given
95 * endpoint according to gadget speed and saves it in the
96 * endpoint desc field. If the endpoint already has a descriptor
97 * assigned to it - overwrites it with currently corresponding
98 * descriptor. The endpoint maxpacket field is updated according
99 * to the chosen descriptor.
100 * Note: the supplied function should hold all the descriptors
101 * for supported speeds
103 int config_ep_by_speed(struct usb_gadget *g,
104 struct usb_function *f,
107 struct usb_composite_dev *cdev = get_gadget_data(g);
108 struct usb_endpoint_descriptor *chosen_desc = NULL;
109 struct usb_descriptor_header **speed_desc = NULL;
111 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
112 int want_comp_desc = 0;
114 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
116 if (!g || !f || !_ep)
119 /* select desired speed */
121 case USB_SPEED_SUPER:
122 if (gadget_is_superspeed(g)) {
123 speed_desc = f->ss_descriptors;
127 /* else: Fall trough */
129 if (gadget_is_dualspeed(g)) {
130 speed_desc = f->hs_descriptors;
133 /* else: fall through */
135 speed_desc = f->fs_descriptors;
137 /* find descriptors */
138 for_each_ep_desc(speed_desc, d_spd) {
139 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
140 if (chosen_desc->bEndpointAddress == _ep->address)
147 _ep->maxpacket = usb_endpoint_maxp(chosen_desc) & 0x7ff;
148 _ep->desc = chosen_desc;
149 _ep->comp_desc = NULL;
153 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
154 usb_endpoint_xfer_int(_ep->desc)))
155 _ep->mult = usb_endpoint_maxp(_ep->desc) & 0x7ff;
161 * Companion descriptor should follow EP descriptor
162 * USB 3.0 spec, #9.6.7
164 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
166 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
168 _ep->comp_desc = comp_desc;
169 if (g->speed == USB_SPEED_SUPER) {
170 switch (usb_endpoint_type(_ep->desc)) {
171 case USB_ENDPOINT_XFER_ISOC:
172 /* mult: bits 1:0 of bmAttributes */
173 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
174 case USB_ENDPOINT_XFER_BULK:
175 case USB_ENDPOINT_XFER_INT:
176 _ep->maxburst = comp_desc->bMaxBurst + 1;
179 if (comp_desc->bMaxBurst != 0)
180 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
187 EXPORT_SYMBOL_GPL(config_ep_by_speed);
190 * usb_add_function() - add a function to a configuration
191 * @config: the configuration
192 * @function: the function being added
193 * Context: single threaded during gadget setup
195 * After initialization, each configuration must have one or more
196 * functions added to it. Adding a function involves calling its @bind()
197 * method to allocate resources such as interface and string identifiers
200 * This function returns the value of the function's bind(), which is
201 * zero for success else a negative errno value.
203 int usb_add_function(struct usb_configuration *config,
204 struct usb_function *function)
208 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
209 function->name, function,
210 config->label, config);
212 if (!function->set_alt || !function->disable)
215 function->config = config;
216 list_add_tail(&function->list, &config->functions);
218 if (function->bind_deactivated) {
219 value = usb_function_deactivate(function);
224 /* REVISIT *require* function->bind? */
225 if (function->bind) {
226 value = function->bind(config, function);
228 list_del(&function->list);
229 function->config = NULL;
234 /* We allow configurations that don't work at both speeds.
235 * If we run into a lowspeed Linux system, treat it the same
236 * as full speed ... it's the function drivers that will need
237 * to avoid bulk and ISO transfers.
239 if (!config->fullspeed && function->fs_descriptors)
240 config->fullspeed = true;
241 if (!config->highspeed && function->hs_descriptors)
242 config->highspeed = true;
243 if (!config->superspeed && function->ss_descriptors)
244 config->superspeed = true;
248 DBG(config->cdev, "adding '%s'/%p --> %d\n",
249 function->name, function, value);
252 EXPORT_SYMBOL_GPL(usb_add_function);
254 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
259 bitmap_zero(f->endpoints, 32);
264 EXPORT_SYMBOL_GPL(usb_remove_function);
267 * usb_function_deactivate - prevent function and gadget enumeration
268 * @function: the function that isn't yet ready to respond
270 * Blocks response of the gadget driver to host enumeration by
271 * preventing the data line pullup from being activated. This is
272 * normally called during @bind() processing to change from the
273 * initial "ready to respond" state, or when a required resource
276 * For example, drivers that serve as a passthrough to a userspace
277 * daemon can block enumeration unless that daemon (such as an OBEX,
278 * MTP, or print server) is ready to handle host requests.
280 * Not all systems support software control of their USB peripheral
283 * Returns zero on success, else negative errno.
285 int usb_function_deactivate(struct usb_function *function)
287 struct usb_composite_dev *cdev = function->config->cdev;
291 spin_lock_irqsave(&cdev->lock, flags);
293 if (cdev->deactivations == 0)
294 status = usb_gadget_deactivate(cdev->gadget);
296 cdev->deactivations++;
298 spin_unlock_irqrestore(&cdev->lock, flags);
301 EXPORT_SYMBOL_GPL(usb_function_deactivate);
304 * usb_function_activate - allow function and gadget enumeration
305 * @function: function on which usb_function_activate() was called
307 * Reverses effect of usb_function_deactivate(). If no more functions
308 * are delaying their activation, the gadget driver will respond to
309 * host enumeration procedures.
311 * Returns zero on success, else negative errno.
313 int usb_function_activate(struct usb_function *function)
315 struct usb_composite_dev *cdev = function->config->cdev;
319 spin_lock_irqsave(&cdev->lock, flags);
321 if (WARN_ON(cdev->deactivations == 0))
324 cdev->deactivations--;
325 if (cdev->deactivations == 0)
326 status = usb_gadget_activate(cdev->gadget);
329 spin_unlock_irqrestore(&cdev->lock, flags);
332 EXPORT_SYMBOL_GPL(usb_function_activate);
335 * usb_interface_id() - allocate an unused interface ID
336 * @config: configuration associated with the interface
337 * @function: function handling the interface
338 * Context: single threaded during gadget setup
340 * usb_interface_id() is called from usb_function.bind() callbacks to
341 * allocate new interface IDs. The function driver will then store that
342 * ID in interface, association, CDC union, and other descriptors. It
343 * will also handle any control requests targeted at that interface,
344 * particularly changing its altsetting via set_alt(). There may
345 * also be class-specific or vendor-specific requests to handle.
347 * All interface identifier should be allocated using this routine, to
348 * ensure that for example different functions don't wrongly assign
349 * different meanings to the same identifier. Note that since interface
350 * identifiers are configuration-specific, functions used in more than
351 * one configuration (or more than once in a given configuration) need
352 * multiple versions of the relevant descriptors.
354 * Returns the interface ID which was allocated; or -ENODEV if no
355 * more interface IDs can be allocated.
357 int usb_interface_id(struct usb_configuration *config,
358 struct usb_function *function)
360 unsigned id = config->next_interface_id;
362 if (id < MAX_CONFIG_INTERFACES) {
363 config->interface[id] = function;
364 config->next_interface_id = id + 1;
369 EXPORT_SYMBOL_GPL(usb_interface_id);
371 static u8 encode_bMaxPower(enum usb_device_speed speed,
372 struct usb_configuration *c)
379 val = CONFIG_USB_GADGET_VBUS_DRAW;
383 case USB_SPEED_SUPER:
384 return DIV_ROUND_UP(val, 8);
386 return DIV_ROUND_UP(val, 2);
390 static int config_buf(struct usb_configuration *config,
391 enum usb_device_speed speed, void *buf, u8 type)
393 struct usb_config_descriptor *c = buf;
394 void *next = buf + USB_DT_CONFIG_SIZE;
396 struct usb_function *f;
399 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
400 /* write the config descriptor */
402 c->bLength = USB_DT_CONFIG_SIZE;
403 c->bDescriptorType = type;
404 /* wTotalLength is written later */
405 c->bNumInterfaces = config->next_interface_id;
406 c->bConfigurationValue = config->bConfigurationValue;
407 c->iConfiguration = config->iConfiguration;
408 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
409 c->bMaxPower = encode_bMaxPower(speed, config);
411 /* There may be e.g. OTG descriptors */
412 if (config->descriptors) {
413 status = usb_descriptor_fillbuf(next, len,
414 config->descriptors);
421 /* add each function's descriptors */
422 list_for_each_entry(f, &config->functions, list) {
423 struct usb_descriptor_header **descriptors;
426 case USB_SPEED_SUPER:
427 descriptors = f->ss_descriptors;
430 descriptors = f->hs_descriptors;
433 descriptors = f->fs_descriptors;
438 status = usb_descriptor_fillbuf(next, len,
439 (const struct usb_descriptor_header **) descriptors);
447 c->wTotalLength = cpu_to_le16(len);
451 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
453 struct usb_gadget *gadget = cdev->gadget;
454 struct usb_configuration *c;
455 struct list_head *pos;
456 u8 type = w_value >> 8;
457 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
459 if (gadget->speed == USB_SPEED_SUPER)
460 speed = gadget->speed;
461 else if (gadget_is_dualspeed(gadget)) {
463 if (gadget->speed == USB_SPEED_HIGH)
465 if (type == USB_DT_OTHER_SPEED_CONFIG)
468 speed = USB_SPEED_HIGH;
472 /* This is a lookup by config *INDEX* */
475 pos = &cdev->configs;
476 c = cdev->os_desc_config;
480 while ((pos = pos->next) != &cdev->configs) {
481 c = list_entry(pos, typeof(*c), list);
483 /* skip OS Descriptors config which is handled separately */
484 if (c == cdev->os_desc_config)
488 /* ignore configs that won't work at this speed */
490 case USB_SPEED_SUPER:
504 return config_buf(c, speed, cdev->req->buf, type);
510 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
512 struct usb_gadget *gadget = cdev->gadget;
513 struct usb_configuration *c;
518 if (gadget_is_dualspeed(gadget)) {
519 if (gadget->speed == USB_SPEED_HIGH)
521 if (gadget->speed == USB_SPEED_SUPER)
523 if (type == USB_DT_DEVICE_QUALIFIER)
526 list_for_each_entry(c, &cdev->configs, list) {
527 /* ignore configs that won't work at this speed */
544 * bos_desc() - prepares the BOS descriptor.
545 * @cdev: pointer to usb_composite device to generate the bos
548 * This function generates the BOS (Binary Device Object)
549 * descriptor and its device capabilities descriptors. The BOS
550 * descriptor should be supported by a SuperSpeed device.
552 static int bos_desc(struct usb_composite_dev *cdev)
554 struct usb_ext_cap_descriptor *usb_ext;
555 struct usb_ss_cap_descriptor *ss_cap;
556 struct usb_dcd_config_params dcd_config_params;
557 struct usb_bos_descriptor *bos = cdev->req->buf;
559 bos->bLength = USB_DT_BOS_SIZE;
560 bos->bDescriptorType = USB_DT_BOS;
562 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
563 bos->bNumDeviceCaps = 0;
566 * A SuperSpeed device shall include the USB2.0 extension descriptor
567 * and shall support LPM when operating in USB2.0 HS mode.
569 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
570 bos->bNumDeviceCaps++;
571 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
572 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
573 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
574 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
575 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
578 * The Superspeed USB Capability descriptor shall be implemented by all
579 * SuperSpeed devices.
581 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
582 bos->bNumDeviceCaps++;
583 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
584 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
585 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
586 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
587 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
588 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
589 USB_FULL_SPEED_OPERATION |
590 USB_HIGH_SPEED_OPERATION |
591 USB_5GBPS_OPERATION);
592 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
594 /* Get Controller configuration */
595 if (cdev->gadget->ops->get_config_params)
596 cdev->gadget->ops->get_config_params(&dcd_config_params);
598 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
599 dcd_config_params.bU2DevExitLat =
600 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
602 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
603 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
605 return le16_to_cpu(bos->wTotalLength);
608 static void device_qual(struct usb_composite_dev *cdev)
610 struct usb_qualifier_descriptor *qual = cdev->req->buf;
612 qual->bLength = sizeof(*qual);
613 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
614 /* POLICY: same bcdUSB and device type info at both speeds */
615 qual->bcdUSB = cdev->desc.bcdUSB;
616 qual->bDeviceClass = cdev->desc.bDeviceClass;
617 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
618 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
619 /* ASSUME same EP0 fifo size at both speeds */
620 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
621 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
625 /*-------------------------------------------------------------------------*/
627 static void reset_config(struct usb_composite_dev *cdev)
629 struct usb_function *f;
631 DBG(cdev, "reset config\n");
633 list_for_each_entry(f, &cdev->config->functions, list) {
637 bitmap_zero(f->endpoints, 32);
640 cdev->delayed_status = 0;
643 static int set_config(struct usb_composite_dev *cdev,
644 const struct usb_ctrlrequest *ctrl, unsigned number)
646 struct usb_gadget *gadget = cdev->gadget;
647 struct usb_configuration *c = NULL;
648 int result = -EINVAL;
649 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
653 list_for_each_entry(c, &cdev->configs, list) {
654 if (c->bConfigurationValue == number) {
656 * We disable the FDs of the previous
657 * configuration only if the new configuration
668 } else { /* Zero configuration value - need to reset the config */
674 INFO(cdev, "%s config #%d: %s\n",
675 usb_speed_string(gadget->speed),
676 number, c ? c->label : "unconfigured");
681 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
684 /* Initialize all interfaces by setting them to altsetting zero. */
685 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
686 struct usb_function *f = c->interface[tmp];
687 struct usb_descriptor_header **descriptors;
693 * Record which endpoints are used by the function. This is used
694 * to dispatch control requests targeted at that endpoint to the
695 * function's setup callback instead of the current
696 * configuration's setup callback.
698 switch (gadget->speed) {
699 case USB_SPEED_SUPER:
700 descriptors = f->ss_descriptors;
703 descriptors = f->hs_descriptors;
706 descriptors = f->fs_descriptors;
709 for (; *descriptors; ++descriptors) {
710 struct usb_endpoint_descriptor *ep;
713 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
716 ep = (struct usb_endpoint_descriptor *)*descriptors;
717 addr = ((ep->bEndpointAddress & 0x80) >> 3)
718 | (ep->bEndpointAddress & 0x0f);
719 set_bit(addr, f->endpoints);
722 result = f->set_alt(f, tmp, 0);
724 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
725 tmp, f->name, f, result);
731 if (result == USB_GADGET_DELAYED_STATUS) {
733 "%s: interface %d (%s) requested delayed status\n",
734 __func__, tmp, f->name);
735 cdev->delayed_status++;
736 DBG(cdev, "delayed_status count %d\n",
737 cdev->delayed_status);
741 /* when we return, be sure our power usage is valid */
742 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
744 usb_gadget_vbus_draw(gadget, power);
745 if (result >= 0 && cdev->delayed_status)
746 result = USB_GADGET_DELAYED_STATUS;
750 int usb_add_config_only(struct usb_composite_dev *cdev,
751 struct usb_configuration *config)
753 struct usb_configuration *c;
755 if (!config->bConfigurationValue)
758 /* Prevent duplicate configuration identifiers */
759 list_for_each_entry(c, &cdev->configs, list) {
760 if (c->bConfigurationValue == config->bConfigurationValue)
765 list_add_tail(&config->list, &cdev->configs);
767 INIT_LIST_HEAD(&config->functions);
768 config->next_interface_id = 0;
769 memset(config->interface, 0, sizeof(config->interface));
773 EXPORT_SYMBOL_GPL(usb_add_config_only);
776 * usb_add_config() - add a configuration to a device.
777 * @cdev: wraps the USB gadget
778 * @config: the configuration, with bConfigurationValue assigned
779 * @bind: the configuration's bind function
780 * Context: single threaded during gadget setup
782 * One of the main tasks of a composite @bind() routine is to
783 * add each of the configurations it supports, using this routine.
785 * This function returns the value of the configuration's @bind(), which
786 * is zero for success else a negative errno value. Binding configurations
787 * assigns global resources including string IDs, and per-configuration
788 * resources such as interface IDs and endpoints.
790 int usb_add_config(struct usb_composite_dev *cdev,
791 struct usb_configuration *config,
792 int (*bind)(struct usb_configuration *))
794 int status = -EINVAL;
799 DBG(cdev, "adding config #%u '%s'/%p\n",
800 config->bConfigurationValue,
801 config->label, config);
803 status = usb_add_config_only(cdev, config);
807 status = bind(config);
809 while (!list_empty(&config->functions)) {
810 struct usb_function *f;
812 f = list_first_entry(&config->functions,
813 struct usb_function, list);
816 DBG(cdev, "unbind function '%s'/%p\n",
818 f->unbind(config, f);
819 /* may free memory for "f" */
822 list_del(&config->list);
827 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
828 config->bConfigurationValue, config,
829 config->superspeed ? " super" : "",
830 config->highspeed ? " high" : "",
832 ? (gadget_is_dualspeed(cdev->gadget)
837 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
838 struct usb_function *f = config->interface[i];
842 DBG(cdev, " interface %d = %s/%p\n",
847 /* set_alt(), or next bind(), sets up ep->claimed as needed */
848 usb_ep_autoconfig_reset(cdev->gadget);
852 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
853 config->bConfigurationValue, status);
856 EXPORT_SYMBOL_GPL(usb_add_config);
858 static void remove_config(struct usb_composite_dev *cdev,
859 struct usb_configuration *config)
861 while (!list_empty(&config->functions)) {
862 struct usb_function *f;
864 f = list_first_entry(&config->functions,
865 struct usb_function, list);
868 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
869 f->unbind(config, f);
870 /* may free memory for "f" */
873 list_del(&config->list);
874 if (config->unbind) {
875 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
876 config->unbind(config);
877 /* may free memory for "c" */
882 * usb_remove_config() - remove a configuration from a device.
883 * @cdev: wraps the USB gadget
884 * @config: the configuration
886 * Drivers must call usb_gadget_disconnect before calling this function
887 * to disconnect the device from the host and make sure the host will not
888 * try to enumerate the device while we are changing the config list.
890 void usb_remove_config(struct usb_composite_dev *cdev,
891 struct usb_configuration *config)
895 spin_lock_irqsave(&cdev->lock, flags);
897 if (cdev->config == config)
900 spin_unlock_irqrestore(&cdev->lock, flags);
902 remove_config(cdev, config);
905 /*-------------------------------------------------------------------------*/
907 /* We support strings in multiple languages ... string descriptor zero
908 * says which languages are supported. The typical case will be that
909 * only one language (probably English) is used, with i18n handled on
913 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
915 const struct usb_gadget_strings *s;
921 language = cpu_to_le16(s->language);
922 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
923 if (*tmp == language)
932 static int lookup_string(
933 struct usb_gadget_strings **sp,
939 struct usb_gadget_strings *s;
944 if (s->language != language)
946 value = usb_gadget_get_string(s, id, buf);
953 static int get_string(struct usb_composite_dev *cdev,
954 void *buf, u16 language, int id)
956 struct usb_composite_driver *composite = cdev->driver;
957 struct usb_gadget_string_container *uc;
958 struct usb_configuration *c;
959 struct usb_function *f;
962 /* Yes, not only is USB's i18n support probably more than most
963 * folk will ever care about ... also, it's all supported here.
964 * (Except for UTF8 support for Unicode's "Astral Planes".)
967 /* 0 == report all available language codes */
969 struct usb_string_descriptor *s = buf;
970 struct usb_gadget_strings **sp;
973 s->bDescriptorType = USB_DT_STRING;
975 sp = composite->strings;
977 collect_langs(sp, s->wData);
979 list_for_each_entry(c, &cdev->configs, list) {
982 collect_langs(sp, s->wData);
984 list_for_each_entry(f, &c->functions, list) {
987 collect_langs(sp, s->wData);
990 list_for_each_entry(uc, &cdev->gstrings, list) {
991 struct usb_gadget_strings **sp;
993 sp = get_containers_gs(uc);
994 collect_langs(sp, s->wData);
997 for (len = 0; len <= 126 && s->wData[len]; len++)
1002 s->bLength = 2 * (len + 1);
1006 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1007 struct usb_os_string *b = buf;
1008 b->bLength = sizeof(*b);
1009 b->bDescriptorType = USB_DT_STRING;
1011 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1012 "qwSignature size must be equal to qw_sign");
1013 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1014 b->bMS_VendorCode = cdev->b_vendor_code;
1019 list_for_each_entry(uc, &cdev->gstrings, list) {
1020 struct usb_gadget_strings **sp;
1022 sp = get_containers_gs(uc);
1023 len = lookup_string(sp, buf, language, id);
1028 /* String IDs are device-scoped, so we look up each string
1029 * table we're told about. These lookups are infrequent;
1030 * simpler-is-better here.
1032 if (composite->strings) {
1033 len = lookup_string(composite->strings, buf, language, id);
1037 list_for_each_entry(c, &cdev->configs, list) {
1039 len = lookup_string(c->strings, buf, language, id);
1043 list_for_each_entry(f, &c->functions, list) {
1046 len = lookup_string(f->strings, buf, language, id);
1055 * usb_string_id() - allocate an unused string ID
1056 * @cdev: the device whose string descriptor IDs are being allocated
1057 * Context: single threaded during gadget setup
1059 * @usb_string_id() is called from bind() callbacks to allocate
1060 * string IDs. Drivers for functions, configurations, or gadgets will
1061 * then store that ID in the appropriate descriptors and string table.
1063 * All string identifier should be allocated using this,
1064 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1065 * that for example different functions don't wrongly assign different
1066 * meanings to the same identifier.
1068 int usb_string_id(struct usb_composite_dev *cdev)
1070 if (cdev->next_string_id < 254) {
1071 /* string id 0 is reserved by USB spec for list of
1072 * supported languages */
1073 /* 255 reserved as well? -- mina86 */
1074 cdev->next_string_id++;
1075 return cdev->next_string_id;
1079 EXPORT_SYMBOL_GPL(usb_string_id);
1082 * usb_string_ids() - allocate unused string IDs in batch
1083 * @cdev: the device whose string descriptor IDs are being allocated
1084 * @str: an array of usb_string objects to assign numbers to
1085 * Context: single threaded during gadget setup
1087 * @usb_string_ids() is called from bind() callbacks to allocate
1088 * string IDs. Drivers for functions, configurations, or gadgets will
1089 * then copy IDs from the string table to the appropriate descriptors
1090 * and string table for other languages.
1092 * All string identifier should be allocated using this,
1093 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1094 * example different functions don't wrongly assign different meanings
1095 * to the same identifier.
1097 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1099 int next = cdev->next_string_id;
1101 for (; str->s; ++str) {
1102 if (unlikely(next >= 254))
1107 cdev->next_string_id = next;
1111 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1113 static struct usb_gadget_string_container *copy_gadget_strings(
1114 struct usb_gadget_strings **sp, unsigned n_gstrings,
1117 struct usb_gadget_string_container *uc;
1118 struct usb_gadget_strings **gs_array;
1119 struct usb_gadget_strings *gs;
1120 struct usb_string *s;
1127 mem += sizeof(void *) * (n_gstrings + 1);
1128 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1129 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1130 uc = kmalloc(mem, GFP_KERNEL);
1132 return ERR_PTR(-ENOMEM);
1133 gs_array = get_containers_gs(uc);
1135 stash += sizeof(void *) * (n_gstrings + 1);
1136 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1137 struct usb_string *org_s;
1139 gs_array[n_gs] = stash;
1140 gs = gs_array[n_gs];
1141 stash += sizeof(struct usb_gadget_strings);
1142 gs->language = sp[n_gs]->language;
1143 gs->strings = stash;
1144 org_s = sp[n_gs]->strings;
1146 for (n_s = 0; n_s < n_strings; n_s++) {
1148 stash += sizeof(struct usb_string);
1157 stash += sizeof(struct usb_string);
1160 gs_array[n_gs] = NULL;
1165 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1166 * @cdev: the device whose string descriptor IDs are being allocated
1168 * @sp: an array of usb_gadget_strings to attach.
1169 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1171 * This function will create a deep copy of usb_gadget_strings and usb_string
1172 * and attach it to the cdev. The actual string (usb_string.s) will not be
1173 * copied but only a referenced will be made. The struct usb_gadget_strings
1174 * array may contain multiple languages and should be NULL terminated.
1175 * The ->language pointer of each struct usb_gadget_strings has to contain the
1176 * same amount of entries.
1177 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1178 * usb_string entry of es-ES contains the translation of the first usb_string
1179 * entry of en-US. Therefore both entries become the same id assign.
1181 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1182 struct usb_gadget_strings **sp, unsigned n_strings)
1184 struct usb_gadget_string_container *uc;
1185 struct usb_gadget_strings **n_gs;
1186 unsigned n_gstrings = 0;
1190 for (i = 0; sp[i]; i++)
1194 return ERR_PTR(-EINVAL);
1196 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1198 return ERR_CAST(uc);
1200 n_gs = get_containers_gs(uc);
1201 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1205 for (i = 1; i < n_gstrings; i++) {
1206 struct usb_string *m_s;
1207 struct usb_string *s;
1210 m_s = n_gs[0]->strings;
1211 s = n_gs[i]->strings;
1212 for (n = 0; n < n_strings; n++) {
1218 list_add_tail(&uc->list, &cdev->gstrings);
1219 return n_gs[0]->strings;
1222 return ERR_PTR(ret);
1224 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1227 * usb_string_ids_n() - allocate unused string IDs in batch
1228 * @c: the device whose string descriptor IDs are being allocated
1229 * @n: number of string IDs to allocate
1230 * Context: single threaded during gadget setup
1232 * Returns the first requested ID. This ID and next @n-1 IDs are now
1233 * valid IDs. At least provided that @n is non-zero because if it
1234 * is, returns last requested ID which is now very useful information.
1236 * @usb_string_ids_n() is called from bind() callbacks to allocate
1237 * string IDs. Drivers for functions, configurations, or gadgets will
1238 * then store that ID in the appropriate descriptors and string table.
1240 * All string identifier should be allocated using this,
1241 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1242 * example different functions don't wrongly assign different meanings
1243 * to the same identifier.
1245 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1247 unsigned next = c->next_string_id;
1248 if (unlikely(n > 254 || (unsigned)next + n > 254))
1250 c->next_string_id += n;
1253 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1255 /*-------------------------------------------------------------------------*/
1257 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1259 struct usb_composite_dev *cdev;
1261 if (req->status || req->actual != req->length)
1262 DBG((struct usb_composite_dev *) ep->driver_data,
1263 "setup complete --> %d, %d/%d\n",
1264 req->status, req->actual, req->length);
1267 * REVIST The same ep0 requests are shared with function drivers
1268 * so they don't have to maintain the same ->complete() stubs.
1270 * Because of that, we need to check for the validity of ->context
1271 * here, even though we know we've set it to something useful.
1276 cdev = req->context;
1278 if (cdev->req == req)
1279 cdev->setup_pending = false;
1280 else if (cdev->os_desc_req == req)
1281 cdev->os_desc_pending = false;
1283 WARN(1, "unknown request %p\n", req);
1286 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1287 struct usb_request *req, gfp_t gfp_flags)
1291 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1293 if (cdev->req == req)
1294 cdev->setup_pending = true;
1295 else if (cdev->os_desc_req == req)
1296 cdev->os_desc_pending = true;
1298 WARN(1, "unknown request %p\n", req);
1304 static int count_ext_compat(struct usb_configuration *c)
1309 for (i = 0; i < c->next_interface_id; ++i) {
1310 struct usb_function *f;
1313 f = c->interface[i];
1314 for (j = 0; j < f->os_desc_n; ++j) {
1315 struct usb_os_desc *d;
1317 if (i != f->os_desc_table[j].if_id)
1319 d = f->os_desc_table[j].os_desc;
1320 if (d && d->ext_compat_id)
1328 static void fill_ext_compat(struct usb_configuration *c, u8 *buf)
1333 for (i = 0; i < c->next_interface_id; ++i) {
1334 struct usb_function *f;
1337 f = c->interface[i];
1338 for (j = 0; j < f->os_desc_n; ++j) {
1339 struct usb_os_desc *d;
1341 if (i != f->os_desc_table[j].if_id)
1343 d = f->os_desc_table[j].os_desc;
1344 if (d && d->ext_compat_id) {
1347 memcpy(buf, d->ext_compat_id, 16);
1361 static int count_ext_prop(struct usb_configuration *c, int interface)
1363 struct usb_function *f;
1366 f = c->interface[interface];
1367 for (j = 0; j < f->os_desc_n; ++j) {
1368 struct usb_os_desc *d;
1370 if (interface != f->os_desc_table[j].if_id)
1372 d = f->os_desc_table[j].os_desc;
1373 if (d && d->ext_compat_id)
1374 return d->ext_prop_count;
1379 static int len_ext_prop(struct usb_configuration *c, int interface)
1381 struct usb_function *f;
1382 struct usb_os_desc *d;
1385 res = 10; /* header length */
1386 f = c->interface[interface];
1387 for (j = 0; j < f->os_desc_n; ++j) {
1388 if (interface != f->os_desc_table[j].if_id)
1390 d = f->os_desc_table[j].os_desc;
1392 return min(res + d->ext_prop_len, 4096);
1397 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1399 struct usb_function *f;
1400 struct usb_os_desc *d;
1401 struct usb_os_desc_ext_prop *ext_prop;
1402 int j, count, n, ret;
1405 f = c->interface[interface];
1406 for (j = 0; j < f->os_desc_n; ++j) {
1407 if (interface != f->os_desc_table[j].if_id)
1409 d = f->os_desc_table[j].os_desc;
1411 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1412 /* 4kB minus header length */
1417 count = ext_prop->data_len +
1418 ext_prop->name_len + 14;
1419 if (count > 4086 - n)
1421 usb_ext_prop_put_size(buf, count);
1422 usb_ext_prop_put_type(buf, ext_prop->type);
1423 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1424 ext_prop->name_len);
1427 switch (ext_prop->type) {
1428 case USB_EXT_PROP_UNICODE:
1429 case USB_EXT_PROP_UNICODE_ENV:
1430 case USB_EXT_PROP_UNICODE_LINK:
1431 usb_ext_prop_put_unicode(buf, ret,
1433 ext_prop->data_len);
1435 case USB_EXT_PROP_BINARY:
1436 usb_ext_prop_put_binary(buf, ret,
1438 ext_prop->data_len);
1440 case USB_EXT_PROP_LE32:
1441 /* not implemented */
1442 case USB_EXT_PROP_BE32:
1443 /* not implemented */
1455 * The setup() callback implements all the ep0 functionality that's
1456 * not handled lower down, in hardware or the hardware driver(like
1457 * device and endpoint feature flags, and their status). It's all
1458 * housekeeping for the gadget function we're implementing. Most of
1459 * the work is in config and function specific setup.
1462 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1464 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1465 struct usb_request *req = cdev->req;
1466 int value = -EOPNOTSUPP;
1468 u16 w_index = le16_to_cpu(ctrl->wIndex);
1469 u8 intf = w_index & 0xFF;
1470 u16 w_value = le16_to_cpu(ctrl->wValue);
1471 u16 w_length = le16_to_cpu(ctrl->wLength);
1472 struct usb_function *f = NULL;
1475 /* partial re-init of the response message; the function or the
1476 * gadget might need to intercept e.g. a control-OUT completion
1477 * when we delegate to it.
1480 req->context = cdev;
1481 req->complete = composite_setup_complete;
1483 gadget->ep0->driver_data = cdev;
1486 * Don't let non-standard requests match any of the cases below
1489 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1492 switch (ctrl->bRequest) {
1494 /* we handle all standard USB descriptors */
1495 case USB_REQ_GET_DESCRIPTOR:
1496 if (ctrl->bRequestType != USB_DIR_IN)
1498 switch (w_value >> 8) {
1501 cdev->desc.bNumConfigurations =
1502 count_configs(cdev, USB_DT_DEVICE);
1503 cdev->desc.bMaxPacketSize0 =
1504 cdev->gadget->ep0->maxpacket;
1505 if (gadget_is_superspeed(gadget)) {
1506 if (gadget->speed >= USB_SPEED_SUPER) {
1507 cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1508 cdev->desc.bMaxPacketSize0 = 9;
1510 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1513 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1516 value = min(w_length, (u16) sizeof cdev->desc);
1517 memcpy(req->buf, &cdev->desc, value);
1519 case USB_DT_DEVICE_QUALIFIER:
1520 if (!gadget_is_dualspeed(gadget) ||
1521 gadget->speed >= USB_SPEED_SUPER)
1524 value = min_t(int, w_length,
1525 sizeof(struct usb_qualifier_descriptor));
1527 case USB_DT_OTHER_SPEED_CONFIG:
1528 if (!gadget_is_dualspeed(gadget) ||
1529 gadget->speed >= USB_SPEED_SUPER)
1533 value = config_desc(cdev, w_value);
1535 value = min(w_length, (u16) value);
1538 value = get_string(cdev, req->buf,
1539 w_index, w_value & 0xff);
1541 value = min(w_length, (u16) value);
1544 if (gadget_is_superspeed(gadget)) {
1545 value = bos_desc(cdev);
1546 value = min(w_length, (u16) value);
1550 if (gadget_is_otg(gadget)) {
1551 struct usb_configuration *config;
1552 int otg_desc_len = 0;
1555 config = cdev->config;
1557 config = list_first_entry(
1559 struct usb_configuration, list);
1563 if (gadget->otg_caps &&
1564 (gadget->otg_caps->otg_rev >= 0x0200))
1565 otg_desc_len += sizeof(
1566 struct usb_otg20_descriptor);
1568 otg_desc_len += sizeof(
1569 struct usb_otg_descriptor);
1571 value = min_t(int, w_length, otg_desc_len);
1572 memcpy(req->buf, config->descriptors[0], value);
1578 /* any number of configs can work */
1579 case USB_REQ_SET_CONFIGURATION:
1580 if (ctrl->bRequestType != 0)
1582 if (gadget_is_otg(gadget)) {
1583 if (gadget->a_hnp_support)
1584 DBG(cdev, "HNP available\n");
1585 else if (gadget->a_alt_hnp_support)
1586 DBG(cdev, "HNP on another port\n");
1588 VDBG(cdev, "HNP inactive\n");
1590 spin_lock(&cdev->lock);
1591 value = set_config(cdev, ctrl, w_value);
1592 spin_unlock(&cdev->lock);
1594 case USB_REQ_GET_CONFIGURATION:
1595 if (ctrl->bRequestType != USB_DIR_IN)
1598 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1600 *(u8 *)req->buf = 0;
1601 value = min(w_length, (u16) 1);
1604 /* function drivers must handle get/set altsetting; if there's
1605 * no get() method, we know only altsetting zero works.
1607 case USB_REQ_SET_INTERFACE:
1608 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1610 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1612 f = cdev->config->interface[intf];
1615 if (w_value && !f->set_alt)
1617 value = f->set_alt(f, w_index, w_value);
1618 if (value == USB_GADGET_DELAYED_STATUS) {
1620 "%s: interface %d (%s) requested delayed status\n",
1621 __func__, intf, f->name);
1622 cdev->delayed_status++;
1623 DBG(cdev, "delayed_status count %d\n",
1624 cdev->delayed_status);
1627 case USB_REQ_GET_INTERFACE:
1628 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1630 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1632 f = cdev->config->interface[intf];
1635 /* lots of interfaces only need altsetting zero... */
1636 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1639 *((u8 *)req->buf) = value;
1640 value = min(w_length, (u16) 1);
1644 * USB 3.0 additions:
1645 * Function driver should handle get_status request. If such cb
1646 * wasn't supplied we respond with default value = 0
1647 * Note: function driver should supply such cb only for the first
1648 * interface of the function
1650 case USB_REQ_GET_STATUS:
1651 if (!gadget_is_superspeed(gadget))
1653 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1655 value = 2; /* This is the length of the get_status reply */
1656 put_unaligned_le16(0, req->buf);
1657 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1659 f = cdev->config->interface[intf];
1662 status = f->get_status ? f->get_status(f) : 0;
1665 put_unaligned_le16(status & 0x0000ffff, req->buf);
1668 * Function drivers should handle SetFeature/ClearFeature
1669 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1670 * only for the first interface of the function
1672 case USB_REQ_CLEAR_FEATURE:
1673 case USB_REQ_SET_FEATURE:
1674 if (!gadget_is_superspeed(gadget))
1676 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1679 case USB_INTRF_FUNC_SUSPEND:
1680 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1682 f = cdev->config->interface[intf];
1686 if (f->func_suspend)
1687 value = f->func_suspend(f, w_index >> 8);
1690 "func_suspend() returned error %d\n",
1700 * OS descriptors handling
1702 if (cdev->use_os_string && cdev->os_desc_config &&
1703 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1704 ctrl->bRequest == cdev->b_vendor_code) {
1705 struct usb_request *req;
1706 struct usb_configuration *os_desc_cfg;
1711 req = cdev->os_desc_req;
1712 req->context = cdev;
1713 req->complete = composite_setup_complete;
1715 os_desc_cfg = cdev->os_desc_config;
1716 memset(buf, 0, w_length);
1718 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1719 case USB_RECIP_DEVICE:
1720 if (w_index != 0x4 || (w_value >> 8))
1723 if (w_length == 0x10) {
1724 /* Number of ext compat interfaces */
1725 count = count_ext_compat(os_desc_cfg);
1727 count *= 24; /* 24 B/ext compat desc */
1728 count += 16; /* header */
1729 put_unaligned_le32(count, buf);
1732 /* "extended compatibility ID"s */
1733 count = count_ext_compat(os_desc_cfg);
1735 count *= 24; /* 24 B/ext compat desc */
1736 count += 16; /* header */
1737 put_unaligned_le32(count, buf);
1739 fill_ext_compat(os_desc_cfg, buf);
1743 case USB_RECIP_INTERFACE:
1744 if (w_index != 0x5 || (w_value >> 8))
1746 interface = w_value & 0xFF;
1748 if (w_length == 0x0A) {
1749 count = count_ext_prop(os_desc_cfg,
1751 put_unaligned_le16(count, buf + 8);
1752 count = len_ext_prop(os_desc_cfg,
1754 put_unaligned_le32(count, buf);
1758 count = count_ext_prop(os_desc_cfg,
1760 put_unaligned_le16(count, buf + 8);
1761 count = len_ext_prop(os_desc_cfg,
1763 put_unaligned_le32(count, buf);
1765 value = fill_ext_prop(os_desc_cfg,
1774 req->length = value;
1775 req->context = cdev;
1776 req->zero = value < w_length;
1777 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1779 DBG(cdev, "ep_queue --> %d\n", value);
1781 composite_setup_complete(gadget->ep0, req);
1787 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1788 ctrl->bRequestType, ctrl->bRequest,
1789 w_value, w_index, w_length);
1791 /* functions always handle their interfaces and endpoints...
1792 * punt other recipients (other, WUSB, ...) to the current
1793 * configuration code.
1795 * REVISIT it could make sense to let the composite device
1796 * take such requests too, if that's ever needed: to work
1800 list_for_each_entry(f, &cdev->config->functions, list)
1801 if (f->req_match && f->req_match(f, ctrl))
1806 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1807 case USB_RECIP_INTERFACE:
1808 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1810 f = cdev->config->interface[intf];
1813 case USB_RECIP_ENDPOINT:
1814 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1815 list_for_each_entry(f, &cdev->config->functions, list) {
1816 if (test_bit(endp, f->endpoints))
1819 if (&f->list == &cdev->config->functions)
1825 value = f->setup(f, ctrl);
1827 struct usb_configuration *c;
1833 /* try current config's setup */
1835 value = c->setup(c, ctrl);
1839 /* try the only function in the current config */
1840 if (!list_is_singular(&c->functions))
1842 f = list_first_entry(&c->functions, struct usb_function,
1845 value = f->setup(f, ctrl);
1851 /* respond with data transfer before status phase? */
1852 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1853 req->length = value;
1854 req->context = cdev;
1855 req->zero = value < w_length;
1856 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1858 DBG(cdev, "ep_queue --> %d\n", value);
1860 composite_setup_complete(gadget->ep0, req);
1862 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1864 "%s: Delayed status not supported for w_length != 0",
1869 /* device either stalls (value < 0) or reports success */
1873 void composite_disconnect(struct usb_gadget *gadget)
1875 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1876 unsigned long flags;
1878 /* REVISIT: should we have config and device level
1879 * disconnect callbacks?
1881 spin_lock_irqsave(&cdev->lock, flags);
1884 if (cdev->driver->disconnect)
1885 cdev->driver->disconnect(cdev);
1886 spin_unlock_irqrestore(&cdev->lock, flags);
1889 /*-------------------------------------------------------------------------*/
1891 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
1894 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1895 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1897 return sprintf(buf, "%d\n", cdev->suspended);
1899 static DEVICE_ATTR_RO(suspended);
1901 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1903 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1905 /* composite_disconnect() must already have been called
1906 * by the underlying peripheral controller driver!
1907 * so there's no i/o concurrency that could affect the
1908 * state protected by cdev->lock.
1910 WARN_ON(cdev->config);
1912 while (!list_empty(&cdev->configs)) {
1913 struct usb_configuration *c;
1914 c = list_first_entry(&cdev->configs,
1915 struct usb_configuration, list);
1916 remove_config(cdev, c);
1918 if (cdev->driver->unbind && unbind_driver)
1919 cdev->driver->unbind(cdev);
1921 composite_dev_cleanup(cdev);
1923 kfree(cdev->def_manufacturer);
1925 set_gadget_data(gadget, NULL);
1928 static void composite_unbind(struct usb_gadget *gadget)
1930 __composite_unbind(gadget, true);
1933 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1934 const struct usb_device_descriptor *old)
1944 * these variables may have been set in
1945 * usb_composite_overwrite_options()
1947 idVendor = new->idVendor;
1948 idProduct = new->idProduct;
1949 bcdDevice = new->bcdDevice;
1950 iSerialNumber = new->iSerialNumber;
1951 iManufacturer = new->iManufacturer;
1952 iProduct = new->iProduct;
1956 new->idVendor = idVendor;
1958 new->idProduct = idProduct;
1960 new->bcdDevice = bcdDevice;
1962 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1964 new->iSerialNumber = iSerialNumber;
1966 new->iManufacturer = iManufacturer;
1968 new->iProduct = iProduct;
1971 int composite_dev_prepare(struct usb_composite_driver *composite,
1972 struct usb_composite_dev *cdev)
1974 struct usb_gadget *gadget = cdev->gadget;
1977 /* preallocate control response and buffer */
1978 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1982 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
1983 if (!cdev->req->buf)
1986 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
1990 cdev->req->complete = composite_setup_complete;
1991 cdev->req->context = cdev;
1992 gadget->ep0->driver_data = cdev;
1994 cdev->driver = composite;
1997 * As per USB compliance update, a device that is actively drawing
1998 * more than 100mA from USB must report itself as bus-powered in
1999 * the GetStatus(DEVICE) call.
2001 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2002 usb_gadget_set_selfpowered(gadget);
2004 /* interface and string IDs start at zero via kzalloc.
2005 * we force endpoints to start unassigned; few controller
2006 * drivers will zero ep->driver_data.
2008 usb_ep_autoconfig_reset(gadget);
2011 kfree(cdev->req->buf);
2013 usb_ep_free_request(gadget->ep0, cdev->req);
2018 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2023 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2024 if (!cdev->os_desc_req) {
2025 ret = PTR_ERR(cdev->os_desc_req);
2029 /* OS feature descriptor length <= 4kB */
2030 cdev->os_desc_req->buf = kmalloc(4096, GFP_KERNEL);
2031 if (!cdev->os_desc_req->buf) {
2032 ret = PTR_ERR(cdev->os_desc_req->buf);
2033 kfree(cdev->os_desc_req);
2036 cdev->os_desc_req->context = cdev;
2037 cdev->os_desc_req->complete = composite_setup_complete;
2042 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2044 struct usb_gadget_string_container *uc, *tmp;
2046 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2047 list_del(&uc->list);
2050 if (cdev->os_desc_req) {
2051 if (cdev->os_desc_pending)
2052 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2054 kfree(cdev->os_desc_req->buf);
2055 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2058 if (cdev->setup_pending)
2059 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2061 kfree(cdev->req->buf);
2062 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2064 cdev->next_string_id = 0;
2065 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2068 static int composite_bind(struct usb_gadget *gadget,
2069 struct usb_gadget_driver *gdriver)
2071 struct usb_composite_dev *cdev;
2072 struct usb_composite_driver *composite = to_cdriver(gdriver);
2073 int status = -ENOMEM;
2075 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2079 spin_lock_init(&cdev->lock);
2080 cdev->gadget = gadget;
2081 set_gadget_data(gadget, cdev);
2082 INIT_LIST_HEAD(&cdev->configs);
2083 INIT_LIST_HEAD(&cdev->gstrings);
2085 status = composite_dev_prepare(composite, cdev);
2089 /* composite gadget needs to assign strings for whole device (like
2090 * serial number), register function drivers, potentially update
2091 * power state and consumption, etc
2093 status = composite->bind(cdev);
2097 if (cdev->use_os_string) {
2098 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2103 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2105 /* has userspace failed to provide a serial number? */
2106 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2107 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2109 INFO(cdev, "%s ready\n", composite->name);
2113 __composite_unbind(gadget, false);
2117 /*-------------------------------------------------------------------------*/
2119 void composite_suspend(struct usb_gadget *gadget)
2121 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2122 struct usb_function *f;
2124 /* REVISIT: should we have config level
2125 * suspend/resume callbacks?
2127 DBG(cdev, "suspend\n");
2129 list_for_each_entry(f, &cdev->config->functions, list) {
2134 if (cdev->driver->suspend)
2135 cdev->driver->suspend(cdev);
2137 cdev->suspended = 1;
2139 usb_gadget_vbus_draw(gadget, 2);
2142 void composite_resume(struct usb_gadget *gadget)
2144 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2145 struct usb_function *f;
2148 /* REVISIT: should we have config level
2149 * suspend/resume callbacks?
2151 DBG(cdev, "resume\n");
2152 if (cdev->driver->resume)
2153 cdev->driver->resume(cdev);
2155 list_for_each_entry(f, &cdev->config->functions, list) {
2160 maxpower = cdev->config->MaxPower;
2162 usb_gadget_vbus_draw(gadget, maxpower ?
2163 maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2166 cdev->suspended = 0;
2169 /*-------------------------------------------------------------------------*/
2171 static const struct usb_gadget_driver composite_driver_template = {
2172 .bind = composite_bind,
2173 .unbind = composite_unbind,
2175 .setup = composite_setup,
2176 .reset = composite_disconnect,
2177 .disconnect = composite_disconnect,
2179 .suspend = composite_suspend,
2180 .resume = composite_resume,
2183 .owner = THIS_MODULE,
2188 * usb_composite_probe() - register a composite driver
2189 * @driver: the driver to register
2191 * Context: single threaded during gadget setup
2193 * This function is used to register drivers using the composite driver
2194 * framework. The return value is zero, or a negative errno value.
2195 * Those values normally come from the driver's @bind method, which does
2196 * all the work of setting up the driver to match the hardware.
2198 * On successful return, the gadget is ready to respond to requests from
2199 * the host, unless one of its components invokes usb_gadget_disconnect()
2200 * while it was binding. That would usually be done in order to wait for
2201 * some userspace participation.
2203 int usb_composite_probe(struct usb_composite_driver *driver)
2205 struct usb_gadget_driver *gadget_driver;
2207 if (!driver || !driver->dev || !driver->bind)
2211 driver->name = "composite";
2213 driver->gadget_driver = composite_driver_template;
2214 gadget_driver = &driver->gadget_driver;
2216 gadget_driver->function = (char *) driver->name;
2217 gadget_driver->driver.name = driver->name;
2218 gadget_driver->max_speed = driver->max_speed;
2220 return usb_gadget_probe_driver(gadget_driver);
2222 EXPORT_SYMBOL_GPL(usb_composite_probe);
2225 * usb_composite_unregister() - unregister a composite driver
2226 * @driver: the driver to unregister
2228 * This function is used to unregister drivers using the composite
2231 void usb_composite_unregister(struct usb_composite_driver *driver)
2233 usb_gadget_unregister_driver(&driver->gadget_driver);
2235 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2238 * usb_composite_setup_continue() - Continue with the control transfer
2239 * @cdev: the composite device who's control transfer was kept waiting
2241 * This function must be called by the USB function driver to continue
2242 * with the control transfer's data/status stage in case it had requested to
2243 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2244 * can request the composite framework to delay the setup request's data/status
2245 * stages by returning USB_GADGET_DELAYED_STATUS.
2247 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2250 struct usb_request *req = cdev->req;
2251 unsigned long flags;
2253 DBG(cdev, "%s\n", __func__);
2254 spin_lock_irqsave(&cdev->lock, flags);
2256 if (cdev->delayed_status == 0) {
2257 WARN(cdev, "%s: Unexpected call\n", __func__);
2259 } else if (--cdev->delayed_status == 0) {
2260 DBG(cdev, "%s: Completing delayed status\n", __func__);
2262 req->context = cdev;
2263 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2265 DBG(cdev, "ep_queue --> %d\n", value);
2267 composite_setup_complete(cdev->gadget->ep0, req);
2271 spin_unlock_irqrestore(&cdev->lock, flags);
2273 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2275 static char *composite_default_mfr(struct usb_gadget *gadget)
2280 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2281 init_utsname()->release, gadget->name);
2283 mfr = kmalloc(len, GFP_KERNEL);
2286 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2287 init_utsname()->release, gadget->name);
2291 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2292 struct usb_composite_overwrite *covr)
2294 struct usb_device_descriptor *desc = &cdev->desc;
2295 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2296 struct usb_string *dev_str = gstr->strings;
2299 desc->idVendor = cpu_to_le16(covr->idVendor);
2301 if (covr->idProduct)
2302 desc->idProduct = cpu_to_le16(covr->idProduct);
2304 if (covr->bcdDevice)
2305 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2307 if (covr->serial_number) {
2308 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2309 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2311 if (covr->manufacturer) {
2312 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2313 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2315 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2316 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2317 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2318 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2321 if (covr->product) {
2322 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2323 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2326 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2328 MODULE_LICENSE("GPL");
2329 MODULE_AUTHOR("David Brownell");