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);
148 _ep->desc = chosen_desc;
149 _ep->comp_desc = NULL;
156 * Companion descriptor should follow EP descriptor
157 * USB 3.0 spec, #9.6.7
159 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
161 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
163 _ep->comp_desc = comp_desc;
164 if (g->speed == USB_SPEED_SUPER) {
165 switch (usb_endpoint_type(_ep->desc)) {
166 case USB_ENDPOINT_XFER_ISOC:
167 /* mult: bits 1:0 of bmAttributes */
168 _ep->mult = comp_desc->bmAttributes & 0x3;
169 case USB_ENDPOINT_XFER_BULK:
170 case USB_ENDPOINT_XFER_INT:
171 _ep->maxburst = comp_desc->bMaxBurst + 1;
174 if (comp_desc->bMaxBurst != 0)
175 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
182 EXPORT_SYMBOL_GPL(config_ep_by_speed);
185 * usb_add_function() - add a function to a configuration
186 * @config: the configuration
187 * @function: the function being added
188 * Context: single threaded during gadget setup
190 * After initialization, each configuration must have one or more
191 * functions added to it. Adding a function involves calling its @bind()
192 * method to allocate resources such as interface and string identifiers
195 * This function returns the value of the function's bind(), which is
196 * zero for success else a negative errno value.
198 int usb_add_function(struct usb_configuration *config,
199 struct usb_function *function)
203 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
204 function->name, function,
205 config->label, config);
207 if (!function->set_alt || !function->disable)
210 function->config = config;
211 list_add_tail(&function->list, &config->functions);
213 if (function->bind_deactivated) {
214 value = usb_function_deactivate(function);
219 /* REVISIT *require* function->bind? */
220 if (function->bind) {
221 value = function->bind(config, function);
223 list_del(&function->list);
224 function->config = NULL;
229 /* We allow configurations that don't work at both speeds.
230 * If we run into a lowspeed Linux system, treat it the same
231 * as full speed ... it's the function drivers that will need
232 * to avoid bulk and ISO transfers.
234 if (!config->fullspeed && function->fs_descriptors)
235 config->fullspeed = true;
236 if (!config->highspeed && function->hs_descriptors)
237 config->highspeed = true;
238 if (!config->superspeed && function->ss_descriptors)
239 config->superspeed = true;
243 DBG(config->cdev, "adding '%s'/%p --> %d\n",
244 function->name, function, value);
247 EXPORT_SYMBOL_GPL(usb_add_function);
249 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
254 bitmap_zero(f->endpoints, 32);
259 EXPORT_SYMBOL_GPL(usb_remove_function);
262 * usb_function_deactivate - prevent function and gadget enumeration
263 * @function: the function that isn't yet ready to respond
265 * Blocks response of the gadget driver to host enumeration by
266 * preventing the data line pullup from being activated. This is
267 * normally called during @bind() processing to change from the
268 * initial "ready to respond" state, or when a required resource
271 * For example, drivers that serve as a passthrough to a userspace
272 * daemon can block enumeration unless that daemon (such as an OBEX,
273 * MTP, or print server) is ready to handle host requests.
275 * Not all systems support software control of their USB peripheral
278 * Returns zero on success, else negative errno.
280 int usb_function_deactivate(struct usb_function *function)
282 struct usb_composite_dev *cdev = function->config->cdev;
286 spin_lock_irqsave(&cdev->lock, flags);
288 if (cdev->deactivations == 0)
289 status = usb_gadget_deactivate(cdev->gadget);
291 cdev->deactivations++;
293 spin_unlock_irqrestore(&cdev->lock, flags);
296 EXPORT_SYMBOL_GPL(usb_function_deactivate);
299 * usb_function_activate - allow function and gadget enumeration
300 * @function: function on which usb_function_activate() was called
302 * Reverses effect of usb_function_deactivate(). If no more functions
303 * are delaying their activation, the gadget driver will respond to
304 * host enumeration procedures.
306 * Returns zero on success, else negative errno.
308 int usb_function_activate(struct usb_function *function)
310 struct usb_composite_dev *cdev = function->config->cdev;
314 spin_lock_irqsave(&cdev->lock, flags);
316 if (WARN_ON(cdev->deactivations == 0))
319 cdev->deactivations--;
320 if (cdev->deactivations == 0)
321 status = usb_gadget_activate(cdev->gadget);
324 spin_unlock_irqrestore(&cdev->lock, flags);
327 EXPORT_SYMBOL_GPL(usb_function_activate);
330 * usb_interface_id() - allocate an unused interface ID
331 * @config: configuration associated with the interface
332 * @function: function handling the interface
333 * Context: single threaded during gadget setup
335 * usb_interface_id() is called from usb_function.bind() callbacks to
336 * allocate new interface IDs. The function driver will then store that
337 * ID in interface, association, CDC union, and other descriptors. It
338 * will also handle any control requests targeted at that interface,
339 * particularly changing its altsetting via set_alt(). There may
340 * also be class-specific or vendor-specific requests to handle.
342 * All interface identifier should be allocated using this routine, to
343 * ensure that for example different functions don't wrongly assign
344 * different meanings to the same identifier. Note that since interface
345 * identifiers are configuration-specific, functions used in more than
346 * one configuration (or more than once in a given configuration) need
347 * multiple versions of the relevant descriptors.
349 * Returns the interface ID which was allocated; or -ENODEV if no
350 * more interface IDs can be allocated.
352 int usb_interface_id(struct usb_configuration *config,
353 struct usb_function *function)
355 unsigned id = config->next_interface_id;
357 if (id < MAX_CONFIG_INTERFACES) {
358 config->interface[id] = function;
359 config->next_interface_id = id + 1;
364 EXPORT_SYMBOL_GPL(usb_interface_id);
366 static u8 encode_bMaxPower(enum usb_device_speed speed,
367 struct usb_configuration *c)
374 val = CONFIG_USB_GADGET_VBUS_DRAW;
378 case USB_SPEED_SUPER:
379 return DIV_ROUND_UP(val, 8);
381 return DIV_ROUND_UP(val, 2);
385 static int config_buf(struct usb_configuration *config,
386 enum usb_device_speed speed, void *buf, u8 type)
388 struct usb_config_descriptor *c = buf;
389 void *next = buf + USB_DT_CONFIG_SIZE;
391 struct usb_function *f;
394 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
395 /* write the config descriptor */
397 c->bLength = USB_DT_CONFIG_SIZE;
398 c->bDescriptorType = type;
399 /* wTotalLength is written later */
400 c->bNumInterfaces = config->next_interface_id;
401 c->bConfigurationValue = config->bConfigurationValue;
402 c->iConfiguration = config->iConfiguration;
403 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
404 c->bMaxPower = encode_bMaxPower(speed, config);
406 /* There may be e.g. OTG descriptors */
407 if (config->descriptors) {
408 status = usb_descriptor_fillbuf(next, len,
409 config->descriptors);
416 /* add each function's descriptors */
417 list_for_each_entry(f, &config->functions, list) {
418 struct usb_descriptor_header **descriptors;
421 case USB_SPEED_SUPER:
422 descriptors = f->ss_descriptors;
425 descriptors = f->hs_descriptors;
428 descriptors = f->fs_descriptors;
433 status = usb_descriptor_fillbuf(next, len,
434 (const struct usb_descriptor_header **) descriptors);
442 c->wTotalLength = cpu_to_le16(len);
446 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
448 struct usb_gadget *gadget = cdev->gadget;
449 struct usb_configuration *c;
450 struct list_head *pos;
451 u8 type = w_value >> 8;
452 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
454 if (gadget->speed == USB_SPEED_SUPER)
455 speed = gadget->speed;
456 else if (gadget_is_dualspeed(gadget)) {
458 if (gadget->speed == USB_SPEED_HIGH)
460 if (type == USB_DT_OTHER_SPEED_CONFIG)
463 speed = USB_SPEED_HIGH;
467 /* This is a lookup by config *INDEX* */
470 pos = &cdev->configs;
471 c = cdev->os_desc_config;
475 while ((pos = pos->next) != &cdev->configs) {
476 c = list_entry(pos, typeof(*c), list);
478 /* skip OS Descriptors config which is handled separately */
479 if (c == cdev->os_desc_config)
483 /* ignore configs that won't work at this speed */
485 case USB_SPEED_SUPER:
499 return config_buf(c, speed, cdev->req->buf, type);
505 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
507 struct usb_gadget *gadget = cdev->gadget;
508 struct usb_configuration *c;
513 if (gadget_is_dualspeed(gadget)) {
514 if (gadget->speed == USB_SPEED_HIGH)
516 if (gadget->speed == USB_SPEED_SUPER)
518 if (type == USB_DT_DEVICE_QUALIFIER)
521 list_for_each_entry(c, &cdev->configs, list) {
522 /* ignore configs that won't work at this speed */
539 * bos_desc() - prepares the BOS descriptor.
540 * @cdev: pointer to usb_composite device to generate the bos
543 * This function generates the BOS (Binary Device Object)
544 * descriptor and its device capabilities descriptors. The BOS
545 * descriptor should be supported by a SuperSpeed device.
547 static int bos_desc(struct usb_composite_dev *cdev)
549 struct usb_ext_cap_descriptor *usb_ext;
550 struct usb_ss_cap_descriptor *ss_cap;
551 struct usb_dcd_config_params dcd_config_params;
552 struct usb_bos_descriptor *bos = cdev->req->buf;
554 bos->bLength = USB_DT_BOS_SIZE;
555 bos->bDescriptorType = USB_DT_BOS;
557 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
558 bos->bNumDeviceCaps = 0;
561 * A SuperSpeed device shall include the USB2.0 extension descriptor
562 * and shall support LPM when operating in USB2.0 HS mode.
564 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
565 bos->bNumDeviceCaps++;
566 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
567 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
568 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
569 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
570 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
573 * The Superspeed USB Capability descriptor shall be implemented by all
574 * SuperSpeed devices.
576 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
577 bos->bNumDeviceCaps++;
578 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
579 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
580 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
581 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
582 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
583 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
584 USB_FULL_SPEED_OPERATION |
585 USB_HIGH_SPEED_OPERATION |
586 USB_5GBPS_OPERATION);
587 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
589 /* Get Controller configuration */
590 if (cdev->gadget->ops->get_config_params)
591 cdev->gadget->ops->get_config_params(&dcd_config_params);
593 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
594 dcd_config_params.bU2DevExitLat =
595 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
597 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
598 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
600 return le16_to_cpu(bos->wTotalLength);
603 static void device_qual(struct usb_composite_dev *cdev)
605 struct usb_qualifier_descriptor *qual = cdev->req->buf;
607 qual->bLength = sizeof(*qual);
608 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
609 /* POLICY: same bcdUSB and device type info at both speeds */
610 qual->bcdUSB = cdev->desc.bcdUSB;
611 qual->bDeviceClass = cdev->desc.bDeviceClass;
612 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
613 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
614 /* ASSUME same EP0 fifo size at both speeds */
615 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
616 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
620 /*-------------------------------------------------------------------------*/
622 static void reset_config(struct usb_composite_dev *cdev)
624 struct usb_function *f;
626 DBG(cdev, "reset config\n");
628 list_for_each_entry(f, &cdev->config->functions, list) {
632 bitmap_zero(f->endpoints, 32);
635 cdev->delayed_status = 0;
638 static int set_config(struct usb_composite_dev *cdev,
639 const struct usb_ctrlrequest *ctrl, unsigned number)
641 struct usb_gadget *gadget = cdev->gadget;
642 struct usb_configuration *c = NULL;
643 int result = -EINVAL;
644 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
648 list_for_each_entry(c, &cdev->configs, list) {
649 if (c->bConfigurationValue == number) {
651 * We disable the FDs of the previous
652 * configuration only if the new configuration
663 } else { /* Zero configuration value - need to reset the config */
669 INFO(cdev, "%s config #%d: %s\n",
670 usb_speed_string(gadget->speed),
671 number, c ? c->label : "unconfigured");
676 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
679 /* Initialize all interfaces by setting them to altsetting zero. */
680 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
681 struct usb_function *f = c->interface[tmp];
682 struct usb_descriptor_header **descriptors;
688 * Record which endpoints are used by the function. This is used
689 * to dispatch control requests targeted at that endpoint to the
690 * function's setup callback instead of the current
691 * configuration's setup callback.
693 switch (gadget->speed) {
694 case USB_SPEED_SUPER:
695 descriptors = f->ss_descriptors;
698 descriptors = f->hs_descriptors;
701 descriptors = f->fs_descriptors;
704 for (; *descriptors; ++descriptors) {
705 struct usb_endpoint_descriptor *ep;
708 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
711 ep = (struct usb_endpoint_descriptor *)*descriptors;
712 addr = ((ep->bEndpointAddress & 0x80) >> 3)
713 | (ep->bEndpointAddress & 0x0f);
714 set_bit(addr, f->endpoints);
717 result = f->set_alt(f, tmp, 0);
719 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
720 tmp, f->name, f, result);
726 if (result == USB_GADGET_DELAYED_STATUS) {
728 "%s: interface %d (%s) requested delayed status\n",
729 __func__, tmp, f->name);
730 cdev->delayed_status++;
731 DBG(cdev, "delayed_status count %d\n",
732 cdev->delayed_status);
736 /* when we return, be sure our power usage is valid */
737 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
739 usb_gadget_vbus_draw(gadget, power);
740 if (result >= 0 && cdev->delayed_status)
741 result = USB_GADGET_DELAYED_STATUS;
745 int usb_add_config_only(struct usb_composite_dev *cdev,
746 struct usb_configuration *config)
748 struct usb_configuration *c;
750 if (!config->bConfigurationValue)
753 /* Prevent duplicate configuration identifiers */
754 list_for_each_entry(c, &cdev->configs, list) {
755 if (c->bConfigurationValue == config->bConfigurationValue)
760 list_add_tail(&config->list, &cdev->configs);
762 INIT_LIST_HEAD(&config->functions);
763 config->next_interface_id = 0;
764 memset(config->interface, 0, sizeof(config->interface));
768 EXPORT_SYMBOL_GPL(usb_add_config_only);
771 * usb_add_config() - add a configuration to a device.
772 * @cdev: wraps the USB gadget
773 * @config: the configuration, with bConfigurationValue assigned
774 * @bind: the configuration's bind function
775 * Context: single threaded during gadget setup
777 * One of the main tasks of a composite @bind() routine is to
778 * add each of the configurations it supports, using this routine.
780 * This function returns the value of the configuration's @bind(), which
781 * is zero for success else a negative errno value. Binding configurations
782 * assigns global resources including string IDs, and per-configuration
783 * resources such as interface IDs and endpoints.
785 int usb_add_config(struct usb_composite_dev *cdev,
786 struct usb_configuration *config,
787 int (*bind)(struct usb_configuration *))
789 int status = -EINVAL;
794 DBG(cdev, "adding config #%u '%s'/%p\n",
795 config->bConfigurationValue,
796 config->label, config);
798 status = usb_add_config_only(cdev, config);
802 status = bind(config);
804 while (!list_empty(&config->functions)) {
805 struct usb_function *f;
807 f = list_first_entry(&config->functions,
808 struct usb_function, list);
811 DBG(cdev, "unbind function '%s'/%p\n",
813 f->unbind(config, f);
814 /* may free memory for "f" */
817 list_del(&config->list);
822 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
823 config->bConfigurationValue, config,
824 config->superspeed ? " super" : "",
825 config->highspeed ? " high" : "",
827 ? (gadget_is_dualspeed(cdev->gadget)
832 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
833 struct usb_function *f = config->interface[i];
837 DBG(cdev, " interface %d = %s/%p\n",
842 /* set_alt(), or next bind(), sets up ep->claimed as needed */
843 usb_ep_autoconfig_reset(cdev->gadget);
847 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
848 config->bConfigurationValue, status);
851 EXPORT_SYMBOL_GPL(usb_add_config);
853 static void remove_config(struct usb_composite_dev *cdev,
854 struct usb_configuration *config)
856 while (!list_empty(&config->functions)) {
857 struct usb_function *f;
859 f = list_first_entry(&config->functions,
860 struct usb_function, list);
863 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
864 f->unbind(config, f);
865 /* may free memory for "f" */
868 list_del(&config->list);
869 if (config->unbind) {
870 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
871 config->unbind(config);
872 /* may free memory for "c" */
877 * usb_remove_config() - remove a configuration from a device.
878 * @cdev: wraps the USB gadget
879 * @config: the configuration
881 * Drivers must call usb_gadget_disconnect before calling this function
882 * to disconnect the device from the host and make sure the host will not
883 * try to enumerate the device while we are changing the config list.
885 void usb_remove_config(struct usb_composite_dev *cdev,
886 struct usb_configuration *config)
890 spin_lock_irqsave(&cdev->lock, flags);
892 if (cdev->config == config)
895 spin_unlock_irqrestore(&cdev->lock, flags);
897 remove_config(cdev, config);
900 /*-------------------------------------------------------------------------*/
902 /* We support strings in multiple languages ... string descriptor zero
903 * says which languages are supported. The typical case will be that
904 * only one language (probably English) is used, with i18n handled on
908 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
910 const struct usb_gadget_strings *s;
916 language = cpu_to_le16(s->language);
917 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
918 if (*tmp == language)
927 static int lookup_string(
928 struct usb_gadget_strings **sp,
934 struct usb_gadget_strings *s;
939 if (s->language != language)
941 value = usb_gadget_get_string(s, id, buf);
948 static int get_string(struct usb_composite_dev *cdev,
949 void *buf, u16 language, int id)
951 struct usb_composite_driver *composite = cdev->driver;
952 struct usb_gadget_string_container *uc;
953 struct usb_configuration *c;
954 struct usb_function *f;
957 /* Yes, not only is USB's i18n support probably more than most
958 * folk will ever care about ... also, it's all supported here.
959 * (Except for UTF8 support for Unicode's "Astral Planes".)
962 /* 0 == report all available language codes */
964 struct usb_string_descriptor *s = buf;
965 struct usb_gadget_strings **sp;
968 s->bDescriptorType = USB_DT_STRING;
970 sp = composite->strings;
972 collect_langs(sp, s->wData);
974 list_for_each_entry(c, &cdev->configs, list) {
977 collect_langs(sp, s->wData);
979 list_for_each_entry(f, &c->functions, list) {
982 collect_langs(sp, s->wData);
985 list_for_each_entry(uc, &cdev->gstrings, list) {
986 struct usb_gadget_strings **sp;
988 sp = get_containers_gs(uc);
989 collect_langs(sp, s->wData);
992 for (len = 0; len <= 126 && s->wData[len]; len++)
997 s->bLength = 2 * (len + 1);
1001 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1002 struct usb_os_string *b = buf;
1003 b->bLength = sizeof(*b);
1004 b->bDescriptorType = USB_DT_STRING;
1006 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1007 "qwSignature size must be equal to qw_sign");
1008 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1009 b->bMS_VendorCode = cdev->b_vendor_code;
1014 list_for_each_entry(uc, &cdev->gstrings, list) {
1015 struct usb_gadget_strings **sp;
1017 sp = get_containers_gs(uc);
1018 len = lookup_string(sp, buf, language, id);
1023 /* String IDs are device-scoped, so we look up each string
1024 * table we're told about. These lookups are infrequent;
1025 * simpler-is-better here.
1027 if (composite->strings) {
1028 len = lookup_string(composite->strings, buf, language, id);
1032 list_for_each_entry(c, &cdev->configs, list) {
1034 len = lookup_string(c->strings, buf, language, id);
1038 list_for_each_entry(f, &c->functions, list) {
1041 len = lookup_string(f->strings, buf, language, id);
1050 * usb_string_id() - allocate an unused string ID
1051 * @cdev: the device whose string descriptor IDs are being allocated
1052 * Context: single threaded during gadget setup
1054 * @usb_string_id() is called from bind() callbacks to allocate
1055 * string IDs. Drivers for functions, configurations, or gadgets will
1056 * then store that ID in the appropriate descriptors and string table.
1058 * All string identifier should be allocated using this,
1059 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1060 * that for example different functions don't wrongly assign different
1061 * meanings to the same identifier.
1063 int usb_string_id(struct usb_composite_dev *cdev)
1065 if (cdev->next_string_id < 254) {
1066 /* string id 0 is reserved by USB spec for list of
1067 * supported languages */
1068 /* 255 reserved as well? -- mina86 */
1069 cdev->next_string_id++;
1070 return cdev->next_string_id;
1074 EXPORT_SYMBOL_GPL(usb_string_id);
1077 * usb_string_ids() - allocate unused string IDs in batch
1078 * @cdev: the device whose string descriptor IDs are being allocated
1079 * @str: an array of usb_string objects to assign numbers to
1080 * Context: single threaded during gadget setup
1082 * @usb_string_ids() is called from bind() callbacks to allocate
1083 * string IDs. Drivers for functions, configurations, or gadgets will
1084 * then copy IDs from the string table to the appropriate descriptors
1085 * and string table for other languages.
1087 * All string identifier should be allocated using this,
1088 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1089 * example different functions don't wrongly assign different meanings
1090 * to the same identifier.
1092 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1094 int next = cdev->next_string_id;
1096 for (; str->s; ++str) {
1097 if (unlikely(next >= 254))
1102 cdev->next_string_id = next;
1106 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1108 static struct usb_gadget_string_container *copy_gadget_strings(
1109 struct usb_gadget_strings **sp, unsigned n_gstrings,
1112 struct usb_gadget_string_container *uc;
1113 struct usb_gadget_strings **gs_array;
1114 struct usb_gadget_strings *gs;
1115 struct usb_string *s;
1122 mem += sizeof(void *) * (n_gstrings + 1);
1123 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1124 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1125 uc = kmalloc(mem, GFP_KERNEL);
1127 return ERR_PTR(-ENOMEM);
1128 gs_array = get_containers_gs(uc);
1130 stash += sizeof(void *) * (n_gstrings + 1);
1131 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1132 struct usb_string *org_s;
1134 gs_array[n_gs] = stash;
1135 gs = gs_array[n_gs];
1136 stash += sizeof(struct usb_gadget_strings);
1137 gs->language = sp[n_gs]->language;
1138 gs->strings = stash;
1139 org_s = sp[n_gs]->strings;
1141 for (n_s = 0; n_s < n_strings; n_s++) {
1143 stash += sizeof(struct usb_string);
1152 stash += sizeof(struct usb_string);
1155 gs_array[n_gs] = NULL;
1160 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1161 * @cdev: the device whose string descriptor IDs are being allocated
1163 * @sp: an array of usb_gadget_strings to attach.
1164 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1166 * This function will create a deep copy of usb_gadget_strings and usb_string
1167 * and attach it to the cdev. The actual string (usb_string.s) will not be
1168 * copied but only a referenced will be made. The struct usb_gadget_strings
1169 * array may contain multiple languages and should be NULL terminated.
1170 * The ->language pointer of each struct usb_gadget_strings has to contain the
1171 * same amount of entries.
1172 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1173 * usb_string entry of es-ES contains the translation of the first usb_string
1174 * entry of en-US. Therefore both entries become the same id assign.
1176 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1177 struct usb_gadget_strings **sp, unsigned n_strings)
1179 struct usb_gadget_string_container *uc;
1180 struct usb_gadget_strings **n_gs;
1181 unsigned n_gstrings = 0;
1185 for (i = 0; sp[i]; i++)
1189 return ERR_PTR(-EINVAL);
1191 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1193 return ERR_CAST(uc);
1195 n_gs = get_containers_gs(uc);
1196 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1200 for (i = 1; i < n_gstrings; i++) {
1201 struct usb_string *m_s;
1202 struct usb_string *s;
1205 m_s = n_gs[0]->strings;
1206 s = n_gs[i]->strings;
1207 for (n = 0; n < n_strings; n++) {
1213 list_add_tail(&uc->list, &cdev->gstrings);
1214 return n_gs[0]->strings;
1217 return ERR_PTR(ret);
1219 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1222 * usb_string_ids_n() - allocate unused string IDs in batch
1223 * @c: the device whose string descriptor IDs are being allocated
1224 * @n: number of string IDs to allocate
1225 * Context: single threaded during gadget setup
1227 * Returns the first requested ID. This ID and next @n-1 IDs are now
1228 * valid IDs. At least provided that @n is non-zero because if it
1229 * is, returns last requested ID which is now very useful information.
1231 * @usb_string_ids_n() is called from bind() callbacks to allocate
1232 * string IDs. Drivers for functions, configurations, or gadgets will
1233 * then store that ID in the appropriate descriptors and string table.
1235 * All string identifier should be allocated using this,
1236 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1237 * example different functions don't wrongly assign different meanings
1238 * to the same identifier.
1240 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1242 unsigned next = c->next_string_id;
1243 if (unlikely(n > 254 || (unsigned)next + n > 254))
1245 c->next_string_id += n;
1248 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1250 /*-------------------------------------------------------------------------*/
1252 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1254 struct usb_composite_dev *cdev;
1256 if (req->status || req->actual != req->length)
1257 DBG((struct usb_composite_dev *) ep->driver_data,
1258 "setup complete --> %d, %d/%d\n",
1259 req->status, req->actual, req->length);
1262 * REVIST The same ep0 requests are shared with function drivers
1263 * so they don't have to maintain the same ->complete() stubs.
1265 * Because of that, we need to check for the validity of ->context
1266 * here, even though we know we've set it to something useful.
1271 cdev = req->context;
1273 if (cdev->req == req)
1274 cdev->setup_pending = false;
1275 else if (cdev->os_desc_req == req)
1276 cdev->os_desc_pending = false;
1278 WARN(1, "unknown request %p\n", req);
1281 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1282 struct usb_request *req, gfp_t gfp_flags)
1286 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1288 if (cdev->req == req)
1289 cdev->setup_pending = true;
1290 else if (cdev->os_desc_req == req)
1291 cdev->os_desc_pending = true;
1293 WARN(1, "unknown request %p\n", req);
1299 static int count_ext_compat(struct usb_configuration *c)
1304 for (i = 0; i < c->next_interface_id; ++i) {
1305 struct usb_function *f;
1308 f = c->interface[i];
1309 for (j = 0; j < f->os_desc_n; ++j) {
1310 struct usb_os_desc *d;
1312 if (i != f->os_desc_table[j].if_id)
1314 d = f->os_desc_table[j].os_desc;
1315 if (d && d->ext_compat_id)
1323 static void fill_ext_compat(struct usb_configuration *c, u8 *buf)
1328 for (i = 0; i < c->next_interface_id; ++i) {
1329 struct usb_function *f;
1332 f = c->interface[i];
1333 for (j = 0; j < f->os_desc_n; ++j) {
1334 struct usb_os_desc *d;
1336 if (i != f->os_desc_table[j].if_id)
1338 d = f->os_desc_table[j].os_desc;
1339 if (d && d->ext_compat_id) {
1342 memcpy(buf, d->ext_compat_id, 16);
1356 static int count_ext_prop(struct usb_configuration *c, int interface)
1358 struct usb_function *f;
1361 f = c->interface[interface];
1362 for (j = 0; j < f->os_desc_n; ++j) {
1363 struct usb_os_desc *d;
1365 if (interface != f->os_desc_table[j].if_id)
1367 d = f->os_desc_table[j].os_desc;
1368 if (d && d->ext_compat_id)
1369 return d->ext_prop_count;
1374 static int len_ext_prop(struct usb_configuration *c, int interface)
1376 struct usb_function *f;
1377 struct usb_os_desc *d;
1380 res = 10; /* header length */
1381 f = c->interface[interface];
1382 for (j = 0; j < f->os_desc_n; ++j) {
1383 if (interface != f->os_desc_table[j].if_id)
1385 d = f->os_desc_table[j].os_desc;
1387 return min(res + d->ext_prop_len, 4096);
1392 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1394 struct usb_function *f;
1395 struct usb_os_desc *d;
1396 struct usb_os_desc_ext_prop *ext_prop;
1397 int j, count, n, ret;
1400 f = c->interface[interface];
1401 for (j = 0; j < f->os_desc_n; ++j) {
1402 if (interface != f->os_desc_table[j].if_id)
1404 d = f->os_desc_table[j].os_desc;
1406 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1407 /* 4kB minus header length */
1412 count = ext_prop->data_len +
1413 ext_prop->name_len + 14;
1414 if (count > 4086 - n)
1416 usb_ext_prop_put_size(buf, count);
1417 usb_ext_prop_put_type(buf, ext_prop->type);
1418 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1419 ext_prop->name_len);
1422 switch (ext_prop->type) {
1423 case USB_EXT_PROP_UNICODE:
1424 case USB_EXT_PROP_UNICODE_ENV:
1425 case USB_EXT_PROP_UNICODE_LINK:
1426 usb_ext_prop_put_unicode(buf, ret,
1428 ext_prop->data_len);
1430 case USB_EXT_PROP_BINARY:
1431 usb_ext_prop_put_binary(buf, ret,
1433 ext_prop->data_len);
1435 case USB_EXT_PROP_LE32:
1436 /* not implemented */
1437 case USB_EXT_PROP_BE32:
1438 /* not implemented */
1450 * The setup() callback implements all the ep0 functionality that's
1451 * not handled lower down, in hardware or the hardware driver(like
1452 * device and endpoint feature flags, and their status). It's all
1453 * housekeeping for the gadget function we're implementing. Most of
1454 * the work is in config and function specific setup.
1457 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1459 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1460 struct usb_request *req = cdev->req;
1461 int value = -EOPNOTSUPP;
1463 u16 w_index = le16_to_cpu(ctrl->wIndex);
1464 u8 intf = w_index & 0xFF;
1465 u16 w_value = le16_to_cpu(ctrl->wValue);
1466 u16 w_length = le16_to_cpu(ctrl->wLength);
1467 struct usb_function *f = NULL;
1470 /* partial re-init of the response message; the function or the
1471 * gadget might need to intercept e.g. a control-OUT completion
1472 * when we delegate to it.
1475 req->context = cdev;
1476 req->complete = composite_setup_complete;
1478 gadget->ep0->driver_data = cdev;
1481 * Don't let non-standard requests match any of the cases below
1484 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1487 switch (ctrl->bRequest) {
1489 /* we handle all standard USB descriptors */
1490 case USB_REQ_GET_DESCRIPTOR:
1491 if (ctrl->bRequestType != USB_DIR_IN)
1493 switch (w_value >> 8) {
1496 cdev->desc.bNumConfigurations =
1497 count_configs(cdev, USB_DT_DEVICE);
1498 cdev->desc.bMaxPacketSize0 =
1499 cdev->gadget->ep0->maxpacket;
1500 if (gadget_is_superspeed(gadget)) {
1501 if (gadget->speed >= USB_SPEED_SUPER) {
1502 cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1503 cdev->desc.bMaxPacketSize0 = 9;
1505 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1508 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1511 value = min(w_length, (u16) sizeof cdev->desc);
1512 memcpy(req->buf, &cdev->desc, value);
1514 case USB_DT_DEVICE_QUALIFIER:
1515 if (!gadget_is_dualspeed(gadget) ||
1516 gadget->speed >= USB_SPEED_SUPER)
1519 value = min_t(int, w_length,
1520 sizeof(struct usb_qualifier_descriptor));
1522 case USB_DT_OTHER_SPEED_CONFIG:
1523 if (!gadget_is_dualspeed(gadget) ||
1524 gadget->speed >= USB_SPEED_SUPER)
1528 value = config_desc(cdev, w_value);
1530 value = min(w_length, (u16) value);
1533 value = get_string(cdev, req->buf,
1534 w_index, w_value & 0xff);
1536 value = min(w_length, (u16) value);
1539 if (gadget_is_superspeed(gadget)) {
1540 value = bos_desc(cdev);
1541 value = min(w_length, (u16) value);
1545 if (gadget_is_otg(gadget)) {
1546 struct usb_configuration *config;
1547 int otg_desc_len = 0;
1550 config = cdev->config;
1552 config = list_first_entry(
1554 struct usb_configuration, list);
1558 if (gadget->otg_caps &&
1559 (gadget->otg_caps->otg_rev >= 0x0200))
1560 otg_desc_len += sizeof(
1561 struct usb_otg20_descriptor);
1563 otg_desc_len += sizeof(
1564 struct usb_otg_descriptor);
1566 value = min_t(int, w_length, otg_desc_len);
1567 memcpy(req->buf, config->descriptors[0], value);
1573 /* any number of configs can work */
1574 case USB_REQ_SET_CONFIGURATION:
1575 if (ctrl->bRequestType != 0)
1577 if (gadget_is_otg(gadget)) {
1578 if (gadget->a_hnp_support)
1579 DBG(cdev, "HNP available\n");
1580 else if (gadget->a_alt_hnp_support)
1581 DBG(cdev, "HNP on another port\n");
1583 VDBG(cdev, "HNP inactive\n");
1585 spin_lock(&cdev->lock);
1586 value = set_config(cdev, ctrl, w_value);
1587 spin_unlock(&cdev->lock);
1589 case USB_REQ_GET_CONFIGURATION:
1590 if (ctrl->bRequestType != USB_DIR_IN)
1593 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1595 *(u8 *)req->buf = 0;
1596 value = min(w_length, (u16) 1);
1599 /* function drivers must handle get/set altsetting; if there's
1600 * no get() method, we know only altsetting zero works.
1602 case USB_REQ_SET_INTERFACE:
1603 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1605 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1607 f = cdev->config->interface[intf];
1610 if (w_value && !f->set_alt)
1612 value = f->set_alt(f, w_index, w_value);
1613 if (value == USB_GADGET_DELAYED_STATUS) {
1615 "%s: interface %d (%s) requested delayed status\n",
1616 __func__, intf, f->name);
1617 cdev->delayed_status++;
1618 DBG(cdev, "delayed_status count %d\n",
1619 cdev->delayed_status);
1622 case USB_REQ_GET_INTERFACE:
1623 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1625 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1627 f = cdev->config->interface[intf];
1630 /* lots of interfaces only need altsetting zero... */
1631 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1634 *((u8 *)req->buf) = value;
1635 value = min(w_length, (u16) 1);
1639 * USB 3.0 additions:
1640 * Function driver should handle get_status request. If such cb
1641 * wasn't supplied we respond with default value = 0
1642 * Note: function driver should supply such cb only for the first
1643 * interface of the function
1645 case USB_REQ_GET_STATUS:
1646 if (!gadget_is_superspeed(gadget))
1648 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1650 value = 2; /* This is the length of the get_status reply */
1651 put_unaligned_le16(0, req->buf);
1652 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1654 f = cdev->config->interface[intf];
1657 status = f->get_status ? f->get_status(f) : 0;
1660 put_unaligned_le16(status & 0x0000ffff, req->buf);
1663 * Function drivers should handle SetFeature/ClearFeature
1664 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1665 * only for the first interface of the function
1667 case USB_REQ_CLEAR_FEATURE:
1668 case USB_REQ_SET_FEATURE:
1669 if (!gadget_is_superspeed(gadget))
1671 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1674 case USB_INTRF_FUNC_SUSPEND:
1675 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1677 f = cdev->config->interface[intf];
1681 if (f->func_suspend)
1682 value = f->func_suspend(f, w_index >> 8);
1685 "func_suspend() returned error %d\n",
1695 * OS descriptors handling
1697 if (cdev->use_os_string && cdev->os_desc_config &&
1698 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1699 ctrl->bRequest == cdev->b_vendor_code) {
1700 struct usb_request *req;
1701 struct usb_configuration *os_desc_cfg;
1706 req = cdev->os_desc_req;
1707 req->context = cdev;
1708 req->complete = composite_setup_complete;
1710 os_desc_cfg = cdev->os_desc_config;
1711 memset(buf, 0, w_length);
1713 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1714 case USB_RECIP_DEVICE:
1715 if (w_index != 0x4 || (w_value >> 8))
1718 if (w_length == 0x10) {
1719 /* Number of ext compat interfaces */
1720 count = count_ext_compat(os_desc_cfg);
1722 count *= 24; /* 24 B/ext compat desc */
1723 count += 16; /* header */
1724 put_unaligned_le32(count, buf);
1727 /* "extended compatibility ID"s */
1728 count = count_ext_compat(os_desc_cfg);
1730 count *= 24; /* 24 B/ext compat desc */
1731 count += 16; /* header */
1732 put_unaligned_le32(count, buf);
1734 fill_ext_compat(os_desc_cfg, buf);
1738 case USB_RECIP_INTERFACE:
1739 if (w_index != 0x5 || (w_value >> 8))
1741 interface = w_value & 0xFF;
1743 if (w_length == 0x0A) {
1744 count = count_ext_prop(os_desc_cfg,
1746 put_unaligned_le16(count, buf + 8);
1747 count = len_ext_prop(os_desc_cfg,
1749 put_unaligned_le32(count, buf);
1753 count = count_ext_prop(os_desc_cfg,
1755 put_unaligned_le16(count, buf + 8);
1756 count = len_ext_prop(os_desc_cfg,
1758 put_unaligned_le32(count, buf);
1760 value = fill_ext_prop(os_desc_cfg,
1769 req->length = value;
1770 req->context = cdev;
1771 req->zero = value < w_length;
1772 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1774 DBG(cdev, "ep_queue --> %d\n", value);
1776 composite_setup_complete(gadget->ep0, req);
1782 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1783 ctrl->bRequestType, ctrl->bRequest,
1784 w_value, w_index, w_length);
1786 /* functions always handle their interfaces and endpoints...
1787 * punt other recipients (other, WUSB, ...) to the current
1788 * configuration code.
1790 * REVISIT it could make sense to let the composite device
1791 * take such requests too, if that's ever needed: to work
1795 list_for_each_entry(f, &cdev->config->functions, list)
1796 if (f->req_match && f->req_match(f, ctrl))
1801 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1802 case USB_RECIP_INTERFACE:
1803 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1805 f = cdev->config->interface[intf];
1808 case USB_RECIP_ENDPOINT:
1809 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1810 list_for_each_entry(f, &cdev->config->functions, list) {
1811 if (test_bit(endp, f->endpoints))
1814 if (&f->list == &cdev->config->functions)
1820 value = f->setup(f, ctrl);
1822 struct usb_configuration *c;
1828 /* try current config's setup */
1830 value = c->setup(c, ctrl);
1834 /* try the only function in the current config */
1835 if (!list_is_singular(&c->functions))
1837 f = list_first_entry(&c->functions, struct usb_function,
1840 value = f->setup(f, ctrl);
1846 /* respond with data transfer before status phase? */
1847 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1848 req->length = value;
1849 req->context = cdev;
1850 req->zero = value < w_length;
1851 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1853 DBG(cdev, "ep_queue --> %d\n", value);
1855 composite_setup_complete(gadget->ep0, req);
1857 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1859 "%s: Delayed status not supported for w_length != 0",
1864 /* device either stalls (value < 0) or reports success */
1868 void composite_disconnect(struct usb_gadget *gadget)
1870 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1871 unsigned long flags;
1874 WARN(1, "%s: Calling disconnect on a Gadget that is \
1875 not connected\n", __func__);
1879 /* REVISIT: should we have config and device level
1880 * disconnect callbacks?
1882 spin_lock_irqsave(&cdev->lock, flags);
1885 if (cdev->driver->disconnect)
1886 cdev->driver->disconnect(cdev);
1887 spin_unlock_irqrestore(&cdev->lock, flags);
1890 /*-------------------------------------------------------------------------*/
1892 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
1895 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1896 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1898 return sprintf(buf, "%d\n", cdev->suspended);
1900 static DEVICE_ATTR_RO(suspended);
1902 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1904 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1906 /* composite_disconnect() must already have been called
1907 * by the underlying peripheral controller driver!
1908 * so there's no i/o concurrency that could affect the
1909 * state protected by cdev->lock.
1911 WARN_ON(cdev->config);
1913 while (!list_empty(&cdev->configs)) {
1914 struct usb_configuration *c;
1915 c = list_first_entry(&cdev->configs,
1916 struct usb_configuration, list);
1917 remove_config(cdev, c);
1919 if (cdev->driver->unbind && unbind_driver)
1920 cdev->driver->unbind(cdev);
1922 composite_dev_cleanup(cdev);
1924 kfree(cdev->def_manufacturer);
1926 set_gadget_data(gadget, NULL);
1929 static void composite_unbind(struct usb_gadget *gadget)
1931 __composite_unbind(gadget, true);
1934 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1935 const struct usb_device_descriptor *old)
1945 * these variables may have been set in
1946 * usb_composite_overwrite_options()
1948 idVendor = new->idVendor;
1949 idProduct = new->idProduct;
1950 bcdDevice = new->bcdDevice;
1951 iSerialNumber = new->iSerialNumber;
1952 iManufacturer = new->iManufacturer;
1953 iProduct = new->iProduct;
1957 new->idVendor = idVendor;
1959 new->idProduct = idProduct;
1961 new->bcdDevice = bcdDevice;
1963 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1965 new->iSerialNumber = iSerialNumber;
1967 new->iManufacturer = iManufacturer;
1969 new->iProduct = iProduct;
1972 int composite_dev_prepare(struct usb_composite_driver *composite,
1973 struct usb_composite_dev *cdev)
1975 struct usb_gadget *gadget = cdev->gadget;
1978 /* preallocate control response and buffer */
1979 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1983 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
1984 if (!cdev->req->buf)
1987 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
1991 cdev->req->complete = composite_setup_complete;
1992 cdev->req->context = cdev;
1993 gadget->ep0->driver_data = cdev;
1995 cdev->driver = composite;
1998 * As per USB compliance update, a device that is actively drawing
1999 * more than 100mA from USB must report itself as bus-powered in
2000 * the GetStatus(DEVICE) call.
2002 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2003 usb_gadget_set_selfpowered(gadget);
2005 /* interface and string IDs start at zero via kzalloc.
2006 * we force endpoints to start unassigned; few controller
2007 * drivers will zero ep->driver_data.
2009 usb_ep_autoconfig_reset(gadget);
2012 kfree(cdev->req->buf);
2014 usb_ep_free_request(gadget->ep0, cdev->req);
2019 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2024 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2025 if (!cdev->os_desc_req) {
2026 ret = PTR_ERR(cdev->os_desc_req);
2030 /* OS feature descriptor length <= 4kB */
2031 cdev->os_desc_req->buf = kmalloc(4096, GFP_KERNEL);
2032 if (!cdev->os_desc_req->buf) {
2033 ret = PTR_ERR(cdev->os_desc_req->buf);
2034 kfree(cdev->os_desc_req);
2037 cdev->os_desc_req->context = cdev;
2038 cdev->os_desc_req->complete = composite_setup_complete;
2043 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2045 struct usb_gadget_string_container *uc, *tmp;
2047 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2048 list_del(&uc->list);
2051 if (cdev->os_desc_req) {
2052 if (cdev->os_desc_pending)
2053 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2055 kfree(cdev->os_desc_req->buf);
2056 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2059 if (cdev->setup_pending)
2060 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2062 kfree(cdev->req->buf);
2063 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2065 cdev->next_string_id = 0;
2066 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2069 static int composite_bind(struct usb_gadget *gadget,
2070 struct usb_gadget_driver *gdriver)
2072 struct usb_composite_dev *cdev;
2073 struct usb_composite_driver *composite = to_cdriver(gdriver);
2074 int status = -ENOMEM;
2076 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2080 spin_lock_init(&cdev->lock);
2081 cdev->gadget = gadget;
2082 set_gadget_data(gadget, cdev);
2083 INIT_LIST_HEAD(&cdev->configs);
2084 INIT_LIST_HEAD(&cdev->gstrings);
2086 status = composite_dev_prepare(composite, cdev);
2090 /* composite gadget needs to assign strings for whole device (like
2091 * serial number), register function drivers, potentially update
2092 * power state and consumption, etc
2094 status = composite->bind(cdev);
2098 if (cdev->use_os_string) {
2099 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2104 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2106 /* has userspace failed to provide a serial number? */
2107 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2108 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2110 INFO(cdev, "%s ready\n", composite->name);
2114 __composite_unbind(gadget, false);
2118 /*-------------------------------------------------------------------------*/
2120 void composite_suspend(struct usb_gadget *gadget)
2122 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2123 struct usb_function *f;
2125 /* REVISIT: should we have config level
2126 * suspend/resume callbacks?
2128 DBG(cdev, "suspend\n");
2130 list_for_each_entry(f, &cdev->config->functions, list) {
2135 if (cdev->driver->suspend)
2136 cdev->driver->suspend(cdev);
2138 cdev->suspended = 1;
2140 usb_gadget_vbus_draw(gadget, 2);
2143 void composite_resume(struct usb_gadget *gadget)
2145 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2146 struct usb_function *f;
2149 /* REVISIT: should we have config level
2150 * suspend/resume callbacks?
2152 DBG(cdev, "resume\n");
2153 if (cdev->driver->resume)
2154 cdev->driver->resume(cdev);
2156 list_for_each_entry(f, &cdev->config->functions, list) {
2161 maxpower = cdev->config->MaxPower;
2163 usb_gadget_vbus_draw(gadget, maxpower ?
2164 maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2167 cdev->suspended = 0;
2170 /*-------------------------------------------------------------------------*/
2172 static const struct usb_gadget_driver composite_driver_template = {
2173 .bind = composite_bind,
2174 .unbind = composite_unbind,
2176 .setup = composite_setup,
2177 .reset = composite_disconnect,
2178 .disconnect = composite_disconnect,
2180 .suspend = composite_suspend,
2181 .resume = composite_resume,
2184 .owner = THIS_MODULE,
2189 * usb_composite_probe() - register a composite driver
2190 * @driver: the driver to register
2192 * Context: single threaded during gadget setup
2194 * This function is used to register drivers using the composite driver
2195 * framework. The return value is zero, or a negative errno value.
2196 * Those values normally come from the driver's @bind method, which does
2197 * all the work of setting up the driver to match the hardware.
2199 * On successful return, the gadget is ready to respond to requests from
2200 * the host, unless one of its components invokes usb_gadget_disconnect()
2201 * while it was binding. That would usually be done in order to wait for
2202 * some userspace participation.
2204 int usb_composite_probe(struct usb_composite_driver *driver)
2206 struct usb_gadget_driver *gadget_driver;
2208 if (!driver || !driver->dev || !driver->bind)
2212 driver->name = "composite";
2214 driver->gadget_driver = composite_driver_template;
2215 gadget_driver = &driver->gadget_driver;
2217 gadget_driver->function = (char *) driver->name;
2218 gadget_driver->driver.name = driver->name;
2219 gadget_driver->max_speed = driver->max_speed;
2221 return usb_gadget_probe_driver(gadget_driver);
2223 EXPORT_SYMBOL_GPL(usb_composite_probe);
2226 * usb_composite_unregister() - unregister a composite driver
2227 * @driver: the driver to unregister
2229 * This function is used to unregister drivers using the composite
2232 void usb_composite_unregister(struct usb_composite_driver *driver)
2234 usb_gadget_unregister_driver(&driver->gadget_driver);
2236 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2239 * usb_composite_setup_continue() - Continue with the control transfer
2240 * @cdev: the composite device who's control transfer was kept waiting
2242 * This function must be called by the USB function driver to continue
2243 * with the control transfer's data/status stage in case it had requested to
2244 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2245 * can request the composite framework to delay the setup request's data/status
2246 * stages by returning USB_GADGET_DELAYED_STATUS.
2248 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2251 struct usb_request *req = cdev->req;
2252 unsigned long flags;
2254 DBG(cdev, "%s\n", __func__);
2255 spin_lock_irqsave(&cdev->lock, flags);
2257 if (cdev->delayed_status == 0) {
2258 WARN(cdev, "%s: Unexpected call\n", __func__);
2260 } else if (--cdev->delayed_status == 0) {
2261 DBG(cdev, "%s: Completing delayed status\n", __func__);
2263 req->context = cdev;
2264 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2266 DBG(cdev, "ep_queue --> %d\n", value);
2268 composite_setup_complete(cdev->gadget->ep0, req);
2272 spin_unlock_irqrestore(&cdev->lock, flags);
2274 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2276 static char *composite_default_mfr(struct usb_gadget *gadget)
2281 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2282 init_utsname()->release, gadget->name);
2284 mfr = kmalloc(len, GFP_KERNEL);
2287 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2288 init_utsname()->release, gadget->name);
2292 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2293 struct usb_composite_overwrite *covr)
2295 struct usb_device_descriptor *desc = &cdev->desc;
2296 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2297 struct usb_string *dev_str = gstr->strings;
2300 desc->idVendor = cpu_to_le16(covr->idVendor);
2302 if (covr->idProduct)
2303 desc->idProduct = cpu_to_le16(covr->idProduct);
2305 if (covr->bcdDevice)
2306 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2308 if (covr->serial_number) {
2309 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2310 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2312 if (covr->manufacturer) {
2313 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2314 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2316 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2317 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2318 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2319 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2322 if (covr->product) {
2323 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2324 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2327 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2329 MODULE_LICENSE("GPL");
2330 MODULE_AUTHOR("David Brownell");