blob: cb12eed547184d04087d4d98b11d6e9e50beafdd [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * composite.c - infrastructure for Composite USB Gadgets
3 *
4 * Copyright (C) 2006-2008 David Brownell
5 *
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.
10 */
11
12/* #define VERBOSE_DEBUG */
13
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>
20
21#include <linux/usb/composite.h>
22#include <linux/usb/otg.h>
23#include <asm/unaligned.h>
24
25#include "u_os_desc.h"
26
27/**
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
34 */
35struct usb_os_string {
36 __u8 bLength;
37 __u8 bDescriptorType;
38 __u8 qwSignature[OS_STRING_QW_SIGN_LEN];
39 __u8 bMS_VendorCode;
40 __u8 bPad;
41} __packed;
42
43/*
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.
48 */
49
50static struct usb_gadget_strings **get_containers_gs(
51 struct usb_gadget_string_container *uc)
52{
53 return (struct usb_gadget_strings **)uc->stash;
54}
55
56/**
57 * function_descriptors() - get function descriptors for speed
58 * @f: the function
59 * @speed: the speed
60 *
61 * Returns the descriptors or NULL if not set.
62 */
63static struct usb_descriptor_header **
64function_descriptors(struct usb_function *f,
65 enum usb_device_speed speed)
66{
67 struct usb_descriptor_header **descriptors;
68
69 /*
70 * NOTE: we try to help gadget drivers which might not be setting
71 * max_speed appropriately.
72 */
73
74 switch (speed) {
75 case USB_SPEED_SUPER_PLUS:
76 descriptors = f->ssp_descriptors;
77 if (descriptors)
78 break;
79 /* FALLTHROUGH */
80 case USB_SPEED_SUPER:
81 descriptors = f->ss_descriptors;
82 if (descriptors)
83 break;
84 /* FALLTHROUGH */
85 case USB_SPEED_HIGH:
86 descriptors = f->hs_descriptors;
87 if (descriptors)
88 break;
89 /* FALLTHROUGH */
90 default:
91 descriptors = f->fs_descriptors;
92 }
93
94 /*
95 * if we can't find any descriptors at all, then this gadget deserves to
96 * Oops with a NULL pointer dereference
97 */
98
99 return descriptors;
100}
101
102/**
103 * next_desc() - advance to the next desc_type descriptor
104 * @t: currect pointer within descriptor array
105 * @desc_type: descriptor type
106 *
107 * Return: next desc_type descriptor or NULL
108 *
109 * Iterate over @t until either desc_type descriptor found or
110 * NULL (that indicates end of list) encountered
111 */
112static struct usb_descriptor_header**
113next_desc(struct usb_descriptor_header **t, u8 desc_type)
114{
115 for (; *t; t++) {
116 if ((*t)->bDescriptorType == desc_type)
117 return t;
118 }
119 return NULL;
120}
121
122/*
123 * for_each_desc() - iterate over desc_type descriptors in the
124 * descriptors list
125 * @start: pointer within descriptor array.
126 * @iter_desc: desc_type descriptor to use as the loop cursor
127 * @desc_type: wanted descriptr type
128 */
129#define for_each_desc(start, iter_desc, desc_type) \
130 for (iter_desc = next_desc(start, desc_type); \
131 iter_desc; iter_desc = next_desc(iter_desc + 1, desc_type))
132
133/**
134 * config_ep_by_speed_and_alt() - configures the given endpoint
135 * according to gadget speed.
136 * @g: pointer to the gadget
137 * @f: usb function
138 * @_ep: the endpoint to configure
139 * @alt: alternate setting number
140 *
141 * Return: error code, 0 on success
142 *
143 * This function chooses the right descriptors for a given
144 * endpoint according to gadget speed and saves it in the
145 * endpoint desc field. If the endpoint already has a descriptor
146 * assigned to it - overwrites it with currently corresponding
147 * descriptor. The endpoint maxpacket field is updated according
148 * to the chosen descriptor.
149 * Note: the supplied function should hold all the descriptors
150 * for supported speeds
151 */
152int config_ep_by_speed_and_alt(struct usb_gadget *g,
153 struct usb_function *f,
154 struct usb_ep *_ep,
155 u8 alt)
156{
157 struct usb_endpoint_descriptor *chosen_desc = NULL;
158 struct usb_interface_descriptor *int_desc = NULL;
159 struct usb_descriptor_header **speed_desc = NULL;
160
161 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
162 int want_comp_desc = 0;
163
164 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
165
166 if (!g || !f || !_ep)
167 return -EIO;
168
169 /* select desired speed */
170 switch (g->speed) {
171 case USB_SPEED_SUPER_PLUS:
172 if (gadget_is_superspeed_plus(g)) {
173 speed_desc = f->ssp_descriptors;
174 want_comp_desc = 1;
175 break;
176 }
177 /* else: Fall trough */
178 case USB_SPEED_SUPER:
179 if (gadget_is_superspeed(g)) {
180 speed_desc = f->ss_descriptors;
181 want_comp_desc = 1;
182 break;
183 }
184 /* else: Fall trough */
185 case USB_SPEED_HIGH:
186 if (gadget_is_dualspeed(g)) {
187 speed_desc = f->hs_descriptors;
188 break;
189 }
190 /* else: fall through */
191 default:
192 speed_desc = f->fs_descriptors;
193 }
194
195 /* find correct alternate setting descriptor */
196 for_each_desc(speed_desc, d_spd, USB_DT_INTERFACE) {
197 int_desc = (struct usb_interface_descriptor *)*d_spd;
198
199 if (int_desc->bAlternateSetting == alt) {
200 speed_desc = d_spd;
201 goto intf_found;
202 }
203 }
204 return -EIO;
205
206intf_found:
207 /* find descriptors */
208 for_each_desc(speed_desc, d_spd, USB_DT_ENDPOINT) {
209 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
210 if (chosen_desc->bEndpointAddress == _ep->address)
211 goto ep_found;
212 }
213 return -EIO;
214
215ep_found:
216 /* commit results */
217 _ep->maxpacket = usb_endpoint_maxp(chosen_desc);
218 _ep->desc = chosen_desc;
219 _ep->comp_desc = NULL;
220 _ep->maxburst = 0;
221 _ep->mult = 1;
222
223 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
224 usb_endpoint_xfer_int(_ep->desc)))
225 _ep->mult = usb_endpoint_maxp_mult(_ep->desc);
226
227 if (!want_comp_desc)
228 return 0;
229
230 /*
231 * Companion descriptor should follow EP descriptor
232 * USB 3.0 spec, #9.6.7
233 */
234 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
235 if (!comp_desc ||
236 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
237 return -EIO;
238 _ep->comp_desc = comp_desc;
239 if (g->speed >= USB_SPEED_SUPER) {
240 switch (usb_endpoint_type(_ep->desc)) {
241 case USB_ENDPOINT_XFER_ISOC:
242 /* mult: bits 1:0 of bmAttributes */
243 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
244 case USB_ENDPOINT_XFER_BULK:
245 case USB_ENDPOINT_XFER_INT:
246 _ep->maxburst = comp_desc->bMaxBurst + 1;
247 break;
248 default:
249 if (comp_desc->bMaxBurst != 0) {
250 struct usb_composite_dev *cdev;
251
252 cdev = get_gadget_data(g);
253 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
254 }
255 _ep->maxburst = 1;
256 break;
257 }
258 }
259 return 0;
260}
261EXPORT_SYMBOL_GPL(config_ep_by_speed_and_alt);
262
263/**
264 * config_ep_by_speed() - configures the given endpoint
265 * according to gadget speed.
266 * @g: pointer to the gadget
267 * @f: usb function
268 * @_ep: the endpoint to configure
269 *
270 * Return: error code, 0 on success
271 *
272 * This function chooses the right descriptors for a given
273 * endpoint according to gadget speed and saves it in the
274 * endpoint desc field. If the endpoint already has a descriptor
275 * assigned to it - overwrites it with currently corresponding
276 * descriptor. The endpoint maxpacket field is updated according
277 * to the chosen descriptor.
278 * Note: the supplied function should hold all the descriptors
279 * for supported speeds
280 */
281int config_ep_by_speed(struct usb_gadget *g,
282 struct usb_function *f,
283 struct usb_ep *_ep)
284{
285 return config_ep_by_speed_and_alt(g, f, _ep, 0);
286}
287EXPORT_SYMBOL_GPL(config_ep_by_speed);
288
289/**
290 * usb_add_function() - add a function to a configuration
291 * @config: the configuration
292 * @function: the function being added
293 * Context: single threaded during gadget setup
294 *
295 * After initialization, each configuration must have one or more
296 * functions added to it. Adding a function involves calling its @bind()
297 * method to allocate resources such as interface and string identifiers
298 * and endpoints.
299 *
300 * This function returns the value of the function's bind(), which is
301 * zero for success else a negative errno value.
302 */
303int usb_add_function(struct usb_configuration *config,
304 struct usb_function *function)
305{
306 int value = -EINVAL;
307
308 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
309 function->name, function,
310 config->label, config);
311
312 if (!function->set_alt || !function->disable)
313 goto done;
314
315 function->config = config;
316 list_add_tail(&function->list, &config->functions);
317
318 if (function->bind_deactivated) {
319 value = usb_function_deactivate(function);
320 if (value)
321 goto done;
322 }
323
324 /* REVISIT *require* function->bind? */
325 if (function->bind) {
326 value = function->bind(config, function);
327 if (value < 0) {
328 list_del(&function->list);
329 function->config = NULL;
330 }
331 } else
332 value = 0;
333
334 /* We allow configurations that don't work at both speeds.
335 * If we run into a lowspeed Linux system, treat it the same
336 * as full speed ... it's the function drivers that will need
337 * to avoid bulk and ISO transfers.
338 */
339 if (!config->fullspeed && function->fs_descriptors)
340 config->fullspeed = true;
341 if (!config->highspeed && function->hs_descriptors)
342 config->highspeed = true;
343 if (!config->superspeed && function->ss_descriptors)
344 config->superspeed = true;
345 if (!config->superspeed_plus && function->ssp_descriptors)
346 config->superspeed_plus = true;
347
348done:
349 if (value)
350 DBG(config->cdev, "adding '%s'/%p --> %d\n",
351 function->name, function, value);
352 return value;
353}
354EXPORT_SYMBOL_GPL(usb_add_function);
355
356void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
357{
358 if (f->disable)
359 f->disable(f);
360
361 bitmap_zero(f->endpoints, 32);
362 list_del(&f->list);
363 if (f->unbind)
364 f->unbind(c, f);
365
366 if (f->bind_deactivated)
367 usb_function_activate(f);
368}
369EXPORT_SYMBOL_GPL(usb_remove_function);
370
371/**
372 * usb_function_deactivate - prevent function and gadget enumeration
373 * @function: the function that isn't yet ready to respond
374 *
375 * Blocks response of the gadget driver to host enumeration by
376 * preventing the data line pullup from being activated. This is
377 * normally called during @bind() processing to change from the
378 * initial "ready to respond" state, or when a required resource
379 * becomes available.
380 *
381 * For example, drivers that serve as a passthrough to a userspace
382 * daemon can block enumeration unless that daemon (such as an OBEX,
383 * MTP, or print server) is ready to handle host requests.
384 *
385 * Not all systems support software control of their USB peripheral
386 * data pullups.
387 *
388 * Returns zero on success, else negative errno.
389 */
390int usb_function_deactivate(struct usb_function *function)
391{
392 struct usb_composite_dev *cdev = function->config->cdev;
393 unsigned long flags;
394 int status = 0;
395
396 spin_lock_irqsave(&cdev->lock, flags);
397
398 if (cdev->deactivations == 0)
399 status = usb_gadget_deactivate(cdev->gadget);
400 if (status == 0)
401 cdev->deactivations++;
402
403 spin_unlock_irqrestore(&cdev->lock, flags);
404 return status;
405}
406EXPORT_SYMBOL_GPL(usb_function_deactivate);
407
408/**
409 * usb_function_activate - allow function and gadget enumeration
410 * @function: function on which usb_function_activate() was called
411 *
412 * Reverses effect of usb_function_deactivate(). If no more functions
413 * are delaying their activation, the gadget driver will respond to
414 * host enumeration procedures.
415 *
416 * Returns zero on success, else negative errno.
417 */
418int usb_function_activate(struct usb_function *function)
419{
420 struct usb_composite_dev *cdev = function->config->cdev;
421 unsigned long flags;
422 int status = 0;
423
424 spin_lock_irqsave(&cdev->lock, flags);
425
426 if (WARN_ON(cdev->deactivations == 0))
427 status = -EINVAL;
428 else {
429 cdev->deactivations--;
430 if (cdev->deactivations == 0)
431 status = usb_gadget_activate(cdev->gadget);
432 }
433
434 spin_unlock_irqrestore(&cdev->lock, flags);
435 return status;
436}
437EXPORT_SYMBOL_GPL(usb_function_activate);
438
439/**
440 * usb_interface_id() - allocate an unused interface ID
441 * @config: configuration associated with the interface
442 * @function: function handling the interface
443 * Context: single threaded during gadget setup
444 *
445 * usb_interface_id() is called from usb_function.bind() callbacks to
446 * allocate new interface IDs. The function driver will then store that
447 * ID in interface, association, CDC union, and other descriptors. It
448 * will also handle any control requests targeted at that interface,
449 * particularly changing its altsetting via set_alt(). There may
450 * also be class-specific or vendor-specific requests to handle.
451 *
452 * All interface identifier should be allocated using this routine, to
453 * ensure that for example different functions don't wrongly assign
454 * different meanings to the same identifier. Note that since interface
455 * identifiers are configuration-specific, functions used in more than
456 * one configuration (or more than once in a given configuration) need
457 * multiple versions of the relevant descriptors.
458 *
459 * Returns the interface ID which was allocated; or -ENODEV if no
460 * more interface IDs can be allocated.
461 */
462int usb_interface_id(struct usb_configuration *config,
463 struct usb_function *function)
464{
465 unsigned id = config->next_interface_id;
466
467 if (id < MAX_CONFIG_INTERFACES) {
468 config->interface[id] = function;
469 config->next_interface_id = id + 1;
470 return id;
471 }
472 return -ENODEV;
473}
474EXPORT_SYMBOL_GPL(usb_interface_id);
475
476static u8 encode_bMaxPower(enum usb_device_speed speed,
477 struct usb_configuration *c)
478{
479 unsigned val;
480
481 if (c->MaxPower)
482 val = c->MaxPower;
483 else
484 val = CONFIG_USB_GADGET_VBUS_DRAW;
485 if (!val)
486 return 0;
487 if (speed < USB_SPEED_SUPER)
488 return min(val, 500U) / 2;
489 else
490 /*
491 * USB 3.x supports up to 900mA, but since 900 isn't divisible
492 * by 8 the integral division will effectively cap to 896mA.
493 */
494 return min(val, 900U) / 8;
495}
496
497static int config_buf(struct usb_configuration *config,
498 enum usb_device_speed speed, void *buf, u8 type)
499{
500 struct usb_config_descriptor *c = buf;
501 void *next = buf + USB_DT_CONFIG_SIZE;
502 int len;
503 struct usb_function *f;
504 int status;
505
506 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
507 /* write the config descriptor */
508 c = buf;
509 c->bLength = USB_DT_CONFIG_SIZE;
510 c->bDescriptorType = type;
511 /* wTotalLength is written later */
512 c->bNumInterfaces = config->next_interface_id;
513 c->bConfigurationValue = config->bConfigurationValue;
514 c->iConfiguration = config->iConfiguration;
515 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
516 c->bMaxPower = encode_bMaxPower(speed, config);
517
518 /* There may be e.g. OTG descriptors */
519 if (config->descriptors) {
520 status = usb_descriptor_fillbuf(next, len,
521 config->descriptors);
522 if (status < 0)
523 return status;
524 len -= status;
525 next += status;
526 }
527
528 /* add each function's descriptors */
529 list_for_each_entry(f, &config->functions, list) {
530 struct usb_descriptor_header **descriptors;
531
532 descriptors = function_descriptors(f, speed);
533 if (!descriptors)
534 continue;
535 status = usb_descriptor_fillbuf(next, len,
536 (const struct usb_descriptor_header **) descriptors);
537 if (status < 0)
538 return status;
539 len -= status;
540 next += status;
541 }
542
543 len = next - buf;
544 c->wTotalLength = cpu_to_le16(len);
545 return len;
546}
547
548static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
549{
550 struct usb_gadget *gadget = cdev->gadget;
551 struct usb_configuration *c;
552 struct list_head *pos;
553 u8 type = w_value >> 8;
554 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
555
556 if (gadget->speed >= USB_SPEED_SUPER)
557 speed = gadget->speed;
558 else if (gadget_is_dualspeed(gadget)) {
559 int hs = 0;
560 if (gadget->speed == USB_SPEED_HIGH)
561 hs = 1;
562 if (type == USB_DT_OTHER_SPEED_CONFIG)
563 hs = !hs;
564 if (hs)
565 speed = USB_SPEED_HIGH;
566
567 }
568
569 /* This is a lookup by config *INDEX* */
570 w_value &= 0xff;
571
572 pos = &cdev->configs;
573 c = cdev->os_desc_config;
574 if (c)
575 goto check_config;
576
577 while ((pos = pos->next) != &cdev->configs) {
578 c = list_entry(pos, typeof(*c), list);
579
580 /* skip OS Descriptors config which is handled separately */
581 if (c == cdev->os_desc_config)
582 continue;
583
584check_config:
585 /* ignore configs that won't work at this speed */
586 switch (speed) {
587 case USB_SPEED_SUPER_PLUS:
588 if (!c->superspeed_plus)
589 continue;
590 break;
591 case USB_SPEED_SUPER:
592 if (!c->superspeed)
593 continue;
594 break;
595 case USB_SPEED_HIGH:
596 if (!c->highspeed)
597 continue;
598 break;
599 default:
600 if (!c->fullspeed)
601 continue;
602 }
603
604 if (w_value == 0)
605 return config_buf(c, speed, cdev->req->buf, type);
606 w_value--;
607 }
608 return -EINVAL;
609}
610
611static int count_configs(struct usb_composite_dev *cdev, unsigned type)
612{
613 struct usb_gadget *gadget = cdev->gadget;
614 struct usb_configuration *c;
615 unsigned count = 0;
616 int hs = 0;
617 int ss = 0;
618 int ssp = 0;
619
620 if (gadget_is_dualspeed(gadget)) {
621 if (gadget->speed == USB_SPEED_HIGH)
622 hs = 1;
623 if (gadget->speed == USB_SPEED_SUPER)
624 ss = 1;
625 if (gadget->speed == USB_SPEED_SUPER_PLUS)
626 ssp = 1;
627 if (type == USB_DT_DEVICE_QUALIFIER)
628 hs = !hs;
629 }
630 list_for_each_entry(c, &cdev->configs, list) {
631 /* ignore configs that won't work at this speed */
632 if (ssp) {
633 if (!c->superspeed_plus)
634 continue;
635 } else if (ss) {
636 if (!c->superspeed)
637 continue;
638 } else if (hs) {
639 if (!c->highspeed)
640 continue;
641 } else {
642 if (!c->fullspeed)
643 continue;
644 }
645 count++;
646 }
647 return count;
648}
649
650/**
651 * bos_desc() - prepares the BOS descriptor.
652 * @cdev: pointer to usb_composite device to generate the bos
653 * descriptor for
654 *
655 * This function generates the BOS (Binary Device Object)
656 * descriptor and its device capabilities descriptors. The BOS
657 * descriptor should be supported by a SuperSpeed device.
658 */
659static int bos_desc(struct usb_composite_dev *cdev)
660{
661 struct usb_ext_cap_descriptor *usb_ext;
662 struct usb_dcd_config_params dcd_config_params;
663 struct usb_bos_descriptor *bos = cdev->req->buf;
664
665 bos->bLength = USB_DT_BOS_SIZE;
666 bos->bDescriptorType = USB_DT_BOS;
667
668 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
669 bos->bNumDeviceCaps = 0;
670
671 /*
672 * A SuperSpeed device shall include the USB2.0 extension descriptor
673 * and shall support LPM when operating in USB2.0 HS mode.
674 */
675 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
676 bos->bNumDeviceCaps++;
677 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
678 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
679 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
680 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
681 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
682
683 /*
684 * The Superspeed USB Capability descriptor shall be implemented by all
685 * SuperSpeed devices.
686 */
687 if (gadget_is_superspeed(cdev->gadget)) {
688 struct usb_ss_cap_descriptor *ss_cap;
689
690 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
691 bos->bNumDeviceCaps++;
692 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
693 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
694 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
695 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
696 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
697 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
698 USB_FULL_SPEED_OPERATION |
699 USB_HIGH_SPEED_OPERATION |
700 USB_5GBPS_OPERATION);
701 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
702
703 /* Get Controller configuration */
704 if (cdev->gadget->ops->get_config_params) {
705 cdev->gadget->ops->get_config_params(
706 &dcd_config_params);
707 } else {
708 dcd_config_params.bU1devExitLat =
709 USB_DEFAULT_U1_DEV_EXIT_LAT;
710 dcd_config_params.bU2DevExitLat =
711 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
712 }
713 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
714 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
715 }
716
717 /* The SuperSpeedPlus USB Device Capability descriptor */
718 if (gadget_is_superspeed_plus(cdev->gadget)) {
719 struct usb_ssp_cap_descriptor *ssp_cap;
720
721 ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
722 bos->bNumDeviceCaps++;
723
724 /*
725 * Report typical values.
726 */
727
728 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
729 ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
730 ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
731 ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
732 ssp_cap->bReserved = 0;
733 ssp_cap->wReserved = 0;
734
735 /* SSAC = 1 (2 attributes) */
736 ssp_cap->bmAttributes = cpu_to_le32(1);
737
738 /* Min RX/TX Lane Count = 1 */
739 ssp_cap->wFunctionalitySupport =
740 cpu_to_le16((1 << 8) | (1 << 12));
741
742 /*
743 * bmSublinkSpeedAttr[0]:
744 * ST = Symmetric, RX
745 * LSE = 3 (Gbps)
746 * LP = 1 (SuperSpeedPlus)
747 * LSM = 10 (10 Gbps)
748 */
749 ssp_cap->bmSublinkSpeedAttr[0] =
750 cpu_to_le32((3 << 4) | (1 << 14) | (0xa << 16));
751 /*
752 * bmSublinkSpeedAttr[1] =
753 * ST = Symmetric, TX
754 * LSE = 3 (Gbps)
755 * LP = 1 (SuperSpeedPlus)
756 * LSM = 10 (10 Gbps)
757 */
758 ssp_cap->bmSublinkSpeedAttr[1] =
759 cpu_to_le32((3 << 4) | (1 << 14) |
760 (0xa << 16) | (1 << 7));
761 }
762
763 return le16_to_cpu(bos->wTotalLength);
764}
765
766static void device_qual(struct usb_composite_dev *cdev)
767{
768 struct usb_qualifier_descriptor *qual = cdev->req->buf;
769
770 qual->bLength = sizeof(*qual);
771 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
772 /* POLICY: same bcdUSB and device type info at both speeds */
773 qual->bcdUSB = cdev->desc.bcdUSB;
774 qual->bDeviceClass = cdev->desc.bDeviceClass;
775 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
776 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
777 /* ASSUME same EP0 fifo size at both speeds */
778 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
779 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
780 qual->bRESERVED = 0;
781}
782
783/*-------------------------------------------------------------------------*/
784
785static void reset_config(struct usb_composite_dev *cdev)
786{
787 struct usb_function *f;
788
789 DBG(cdev, "reset config\n");
790
791 list_for_each_entry(f, &cdev->config->functions, list) {
792 if (f->disable)
793 f->disable(f);
794
795 bitmap_zero(f->endpoints, 32);
796 }
797 cdev->config = NULL;
798 cdev->delayed_status = 0;
799}
800
801static int set_config(struct usb_composite_dev *cdev,
802 const struct usb_ctrlrequest *ctrl, unsigned number)
803{
804 struct usb_gadget *gadget = cdev->gadget;
805 struct usb_configuration *c = NULL;
806 int result = -EINVAL;
807 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
808 int tmp;
809
810 if (number) {
811 list_for_each_entry(c, &cdev->configs, list) {
812 if (c->bConfigurationValue == number) {
813 /*
814 * We disable the FDs of the previous
815 * configuration only if the new configuration
816 * is a valid one
817 */
818 if (cdev->config)
819 reset_config(cdev);
820 result = 0;
821 break;
822 }
823 }
824 if (result < 0)
825 goto done;
826 } else { /* Zero configuration value - need to reset the config */
827 if (cdev->config)
828 reset_config(cdev);
829 result = 0;
830 }
831
832 INFO(cdev, "%s config #%d: %s\n",
833 usb_speed_string(gadget->speed),
834 number, c ? c->label : "unconfigured");
835
836 if (!c)
837 goto done;
838
839 usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
840 cdev->config = c;
841
842 /* Initialize all interfaces by setting them to altsetting zero. */
843 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
844 struct usb_function *f = c->interface[tmp];
845 struct usb_descriptor_header **descriptors;
846
847 if (!f)
848 break;
849
850 /*
851 * Record which endpoints are used by the function. This is used
852 * to dispatch control requests targeted at that endpoint to the
853 * function's setup callback instead of the current
854 * configuration's setup callback.
855 */
856 descriptors = function_descriptors(f, gadget->speed);
857
858 for (; *descriptors; ++descriptors) {
859 struct usb_endpoint_descriptor *ep;
860 int addr;
861
862 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
863 continue;
864
865 ep = (struct usb_endpoint_descriptor *)*descriptors;
866 addr = ((ep->bEndpointAddress & 0x80) >> 3)
867 | (ep->bEndpointAddress & 0x0f);
868 set_bit(addr, f->endpoints);
869 }
870
871 result = f->set_alt(f, tmp, 0);
872 if (result < 0) {
873 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
874 tmp, f->name, f, result);
875
876 reset_config(cdev);
877 goto done;
878 }
879
880 if (result == USB_GADGET_DELAYED_STATUS) {
881 DBG(cdev,
882 "%s: interface %d (%s) requested delayed status\n",
883 __func__, tmp, f->name);
884 cdev->delayed_status++;
885 DBG(cdev, "delayed_status count %d\n",
886 cdev->delayed_status);
887 }
888 }
889
890 /* when we return, be sure our power usage is valid */
891 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
892 if (gadget->speed < USB_SPEED_SUPER)
893 power = min(power, 500U);
894 else
895 power = min(power, 900U);
896done:
897 if (power <= USB_SELF_POWER_VBUS_MAX_DRAW)
898 usb_gadget_set_selfpowered(gadget);
899 else
900 usb_gadget_clear_selfpowered(gadget);
901
902 usb_gadget_vbus_draw(gadget, power);
903 if (result >= 0 && cdev->delayed_status)
904 result = USB_GADGET_DELAYED_STATUS;
905 return result;
906}
907
908int usb_add_config_only(struct usb_composite_dev *cdev,
909 struct usb_configuration *config)
910{
911 struct usb_configuration *c;
912
913 if (!config->bConfigurationValue)
914 return -EINVAL;
915
916 /* Prevent duplicate configuration identifiers */
917 list_for_each_entry(c, &cdev->configs, list) {
918 if (c->bConfigurationValue == config->bConfigurationValue)
919 return -EBUSY;
920 }
921
922 config->cdev = cdev;
923 list_add_tail(&config->list, &cdev->configs);
924
925 INIT_LIST_HEAD(&config->functions);
926 config->next_interface_id = 0;
927 memset(config->interface, 0, sizeof(config->interface));
928
929 return 0;
930}
931EXPORT_SYMBOL_GPL(usb_add_config_only);
932
933/**
934 * usb_add_config() - add a configuration to a device.
935 * @cdev: wraps the USB gadget
936 * @config: the configuration, with bConfigurationValue assigned
937 * @bind: the configuration's bind function
938 * Context: single threaded during gadget setup
939 *
940 * One of the main tasks of a composite @bind() routine is to
941 * add each of the configurations it supports, using this routine.
942 *
943 * This function returns the value of the configuration's @bind(), which
944 * is zero for success else a negative errno value. Binding configurations
945 * assigns global resources including string IDs, and per-configuration
946 * resources such as interface IDs and endpoints.
947 */
948int usb_add_config(struct usb_composite_dev *cdev,
949 struct usb_configuration *config,
950 int (*bind)(struct usb_configuration *))
951{
952 int status = -EINVAL;
953
954 if (!bind)
955 goto done;
956
957 DBG(cdev, "adding config #%u '%s'/%p\n",
958 config->bConfigurationValue,
959 config->label, config);
960
961 status = usb_add_config_only(cdev, config);
962 if (status)
963 goto done;
964
965 status = bind(config);
966 if (status < 0) {
967 while (!list_empty(&config->functions)) {
968 struct usb_function *f;
969
970 f = list_first_entry(&config->functions,
971 struct usb_function, list);
972 list_del(&f->list);
973 if (f->unbind) {
974 DBG(cdev, "unbind function '%s'/%p\n",
975 f->name, f);
976 f->unbind(config, f);
977 /* may free memory for "f" */
978 }
979 }
980 list_del(&config->list);
981 config->cdev = NULL;
982 } else {
983 unsigned i;
984
985 DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
986 config->bConfigurationValue, config,
987 config->superspeed_plus ? " superplus" : "",
988 config->superspeed ? " super" : "",
989 config->highspeed ? " high" : "",
990 config->fullspeed
991 ? (gadget_is_dualspeed(cdev->gadget)
992 ? " full"
993 : " full/low")
994 : "");
995
996 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
997 struct usb_function *f = config->interface[i];
998
999 if (!f)
1000 continue;
1001 DBG(cdev, " interface %d = %s/%p\n",
1002 i, f->name, f);
1003 }
1004 }
1005
1006 /* set_alt(), or next bind(), sets up ep->claimed as needed */
1007 usb_ep_autoconfig_reset(cdev->gadget);
1008
1009done:
1010 if (status)
1011 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1012 config->bConfigurationValue, status);
1013 return status;
1014}
1015EXPORT_SYMBOL_GPL(usb_add_config);
1016
1017static void remove_config(struct usb_composite_dev *cdev,
1018 struct usb_configuration *config)
1019{
1020 while (!list_empty(&config->functions)) {
1021 struct usb_function *f;
1022
1023 f = list_first_entry(&config->functions,
1024 struct usb_function, list);
1025
1026 usb_remove_function(config, f);
1027 }
1028 list_del(&config->list);
1029 if (config->unbind) {
1030 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
1031 config->unbind(config);
1032 /* may free memory for "c" */
1033 }
1034}
1035
1036/**
1037 * usb_remove_config() - remove a configuration from a device.
1038 * @cdev: wraps the USB gadget
1039 * @config: the configuration
1040 *
1041 * Drivers must call usb_gadget_disconnect before calling this function
1042 * to disconnect the device from the host and make sure the host will not
1043 * try to enumerate the device while we are changing the config list.
1044 */
1045void usb_remove_config(struct usb_composite_dev *cdev,
1046 struct usb_configuration *config)
1047{
1048 unsigned long flags;
1049
1050 spin_lock_irqsave(&cdev->lock, flags);
1051
1052 if (cdev->config == config)
1053 reset_config(cdev);
1054
1055 spin_unlock_irqrestore(&cdev->lock, flags);
1056
1057 remove_config(cdev, config);
1058}
1059
1060/*-------------------------------------------------------------------------*/
1061
1062/* We support strings in multiple languages ... string descriptor zero
1063 * says which languages are supported. The typical case will be that
1064 * only one language (probably English) is used, with i18n handled on
1065 * the host side.
1066 */
1067
1068static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1069{
1070 const struct usb_gadget_strings *s;
1071 __le16 language;
1072 __le16 *tmp;
1073
1074 while (*sp) {
1075 s = *sp;
1076 language = cpu_to_le16(s->language);
1077 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
1078 if (*tmp == language)
1079 goto repeat;
1080 }
1081 *tmp++ = language;
1082repeat:
1083 sp++;
1084 }
1085}
1086
1087static int lookup_string(
1088 struct usb_gadget_strings **sp,
1089 void *buf,
1090 u16 language,
1091 int id
1092)
1093{
1094 struct usb_gadget_strings *s;
1095 int value;
1096
1097 while (*sp) {
1098 s = *sp++;
1099 if (s->language != language)
1100 continue;
1101 value = usb_gadget_get_string(s, id, buf);
1102 if (value > 0)
1103 return value;
1104 }
1105 return -EINVAL;
1106}
1107
1108static int get_string(struct usb_composite_dev *cdev,
1109 void *buf, u16 language, int id)
1110{
1111 struct usb_composite_driver *composite = cdev->driver;
1112 struct usb_gadget_string_container *uc;
1113 struct usb_configuration *c;
1114 struct usb_function *f;
1115 int len;
1116
1117 /* Yes, not only is USB's i18n support probably more than most
1118 * folk will ever care about ... also, it's all supported here.
1119 * (Except for UTF8 support for Unicode's "Astral Planes".)
1120 */
1121
1122 /* 0 == report all available language codes */
1123 if (id == 0) {
1124 struct usb_string_descriptor *s = buf;
1125 struct usb_gadget_strings **sp;
1126
1127 memset(s, 0, 256);
1128 s->bDescriptorType = USB_DT_STRING;
1129
1130 sp = composite->strings;
1131 if (sp)
1132 collect_langs(sp, s->wData);
1133
1134 list_for_each_entry(c, &cdev->configs, list) {
1135 sp = c->strings;
1136 if (sp)
1137 collect_langs(sp, s->wData);
1138
1139 list_for_each_entry(f, &c->functions, list) {
1140 sp = f->strings;
1141 if (sp)
1142 collect_langs(sp, s->wData);
1143 }
1144 }
1145 list_for_each_entry(uc, &cdev->gstrings, list) {
1146 struct usb_gadget_strings **sp;
1147
1148 sp = get_containers_gs(uc);
1149 collect_langs(sp, s->wData);
1150 }
1151
1152 for (len = 0; len <= 126 && s->wData[len]; len++)
1153 continue;
1154 if (!len)
1155 return -EINVAL;
1156
1157 s->bLength = 2 * (len + 1);
1158 return s->bLength;
1159 }
1160
1161 if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1162 struct usb_os_string *b = buf;
1163 b->bLength = sizeof(*b);
1164 b->bDescriptorType = USB_DT_STRING;
1165 compiletime_assert(
1166 sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1167 "qwSignature size must be equal to qw_sign");
1168 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1169 b->bMS_VendorCode = cdev->b_vendor_code;
1170 b->bPad = 0;
1171 return sizeof(*b);
1172 }
1173
1174 list_for_each_entry(uc, &cdev->gstrings, list) {
1175 struct usb_gadget_strings **sp;
1176
1177 sp = get_containers_gs(uc);
1178 len = lookup_string(sp, buf, language, id);
1179 if (len > 0)
1180 return len;
1181 }
1182
1183 /* String IDs are device-scoped, so we look up each string
1184 * table we're told about. These lookups are infrequent;
1185 * simpler-is-better here.
1186 */
1187 if (composite->strings) {
1188 len = lookup_string(composite->strings, buf, language, id);
1189 if (len > 0)
1190 return len;
1191 }
1192 list_for_each_entry(c, &cdev->configs, list) {
1193 if (c->strings) {
1194 len = lookup_string(c->strings, buf, language, id);
1195 if (len > 0)
1196 return len;
1197 }
1198 list_for_each_entry(f, &c->functions, list) {
1199 if (!f->strings)
1200 continue;
1201 len = lookup_string(f->strings, buf, language, id);
1202 if (len > 0)
1203 return len;
1204 }
1205 }
1206 return -EINVAL;
1207}
1208
1209/**
1210 * usb_string_id() - allocate an unused string ID
1211 * @cdev: the device whose string descriptor IDs are being allocated
1212 * Context: single threaded during gadget setup
1213 *
1214 * @usb_string_id() is called from bind() callbacks to allocate
1215 * string IDs. Drivers for functions, configurations, or gadgets will
1216 * then store that ID in the appropriate descriptors and string table.
1217 *
1218 * All string identifier should be allocated using this,
1219 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1220 * that for example different functions don't wrongly assign different
1221 * meanings to the same identifier.
1222 */
1223int usb_string_id(struct usb_composite_dev *cdev)
1224{
1225 if (cdev->next_string_id < 254) {
1226 /* string id 0 is reserved by USB spec for list of
1227 * supported languages */
1228 /* 255 reserved as well? -- mina86 */
1229 cdev->next_string_id++;
1230 return cdev->next_string_id;
1231 }
1232 return -ENODEV;
1233}
1234EXPORT_SYMBOL_GPL(usb_string_id);
1235
1236/**
1237 * usb_string_ids() - allocate unused string IDs in batch
1238 * @cdev: the device whose string descriptor IDs are being allocated
1239 * @str: an array of usb_string objects to assign numbers to
1240 * Context: single threaded during gadget setup
1241 *
1242 * @usb_string_ids() is called from bind() callbacks to allocate
1243 * string IDs. Drivers for functions, configurations, or gadgets will
1244 * then copy IDs from the string table to the appropriate descriptors
1245 * and string table for other languages.
1246 *
1247 * All string identifier should be allocated using this,
1248 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1249 * example different functions don't wrongly assign different meanings
1250 * to the same identifier.
1251 */
1252int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1253{
1254 int next = cdev->next_string_id;
1255
1256 for (; str->s; ++str) {
1257 if (unlikely(next >= 254))
1258 return -ENODEV;
1259 str->id = ++next;
1260 }
1261
1262 cdev->next_string_id = next;
1263
1264 return 0;
1265}
1266EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1267
1268static struct usb_gadget_string_container *copy_gadget_strings(
1269 struct usb_gadget_strings **sp, unsigned n_gstrings,
1270 unsigned n_strings)
1271{
1272 struct usb_gadget_string_container *uc;
1273 struct usb_gadget_strings **gs_array;
1274 struct usb_gadget_strings *gs;
1275 struct usb_string *s;
1276 unsigned mem;
1277 unsigned n_gs;
1278 unsigned n_s;
1279 void *stash;
1280
1281 mem = sizeof(*uc);
1282 mem += sizeof(void *) * (n_gstrings + 1);
1283 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1284 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1285 uc = kmalloc(mem, GFP_KERNEL);
1286 if (!uc)
1287 return ERR_PTR(-ENOMEM);
1288 gs_array = get_containers_gs(uc);
1289 stash = uc->stash;
1290 stash += sizeof(void *) * (n_gstrings + 1);
1291 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1292 struct usb_string *org_s;
1293
1294 gs_array[n_gs] = stash;
1295 gs = gs_array[n_gs];
1296 stash += sizeof(struct usb_gadget_strings);
1297 gs->language = sp[n_gs]->language;
1298 gs->strings = stash;
1299 org_s = sp[n_gs]->strings;
1300
1301 for (n_s = 0; n_s < n_strings; n_s++) {
1302 s = stash;
1303 stash += sizeof(struct usb_string);
1304 if (org_s->s)
1305 s->s = org_s->s;
1306 else
1307 s->s = "";
1308 org_s++;
1309 }
1310 s = stash;
1311 s->s = NULL;
1312 stash += sizeof(struct usb_string);
1313
1314 }
1315 gs_array[n_gs] = NULL;
1316 return uc;
1317}
1318
1319/**
1320 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1321 * @cdev: the device whose string descriptor IDs are being allocated
1322 * and attached.
1323 * @sp: an array of usb_gadget_strings to attach.
1324 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1325 *
1326 * This function will create a deep copy of usb_gadget_strings and usb_string
1327 * and attach it to the cdev. The actual string (usb_string.s) will not be
1328 * copied but only a referenced will be made. The struct usb_gadget_strings
1329 * array may contain multiple languages and should be NULL terminated.
1330 * The ->language pointer of each struct usb_gadget_strings has to contain the
1331 * same amount of entries.
1332 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1333 * usb_string entry of es-ES contains the translation of the first usb_string
1334 * entry of en-US. Therefore both entries become the same id assign.
1335 */
1336struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1337 struct usb_gadget_strings **sp, unsigned n_strings)
1338{
1339 struct usb_gadget_string_container *uc;
1340 struct usb_gadget_strings **n_gs;
1341 unsigned n_gstrings = 0;
1342 unsigned i;
1343 int ret;
1344
1345 for (i = 0; sp[i]; i++)
1346 n_gstrings++;
1347
1348 if (!n_gstrings)
1349 return ERR_PTR(-EINVAL);
1350
1351 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1352 if (IS_ERR(uc))
1353 return ERR_CAST(uc);
1354
1355 n_gs = get_containers_gs(uc);
1356 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1357 if (ret)
1358 goto err;
1359
1360 for (i = 1; i < n_gstrings; i++) {
1361 struct usb_string *m_s;
1362 struct usb_string *s;
1363 unsigned n;
1364
1365 m_s = n_gs[0]->strings;
1366 s = n_gs[i]->strings;
1367 for (n = 0; n < n_strings; n++) {
1368 s->id = m_s->id;
1369 s++;
1370 m_s++;
1371 }
1372 }
1373 list_add_tail(&uc->list, &cdev->gstrings);
1374 return n_gs[0]->strings;
1375err:
1376 kfree(uc);
1377 return ERR_PTR(ret);
1378}
1379EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1380
1381/**
1382 * usb_string_ids_n() - allocate unused string IDs in batch
1383 * @c: the device whose string descriptor IDs are being allocated
1384 * @n: number of string IDs to allocate
1385 * Context: single threaded during gadget setup
1386 *
1387 * Returns the first requested ID. This ID and next @n-1 IDs are now
1388 * valid IDs. At least provided that @n is non-zero because if it
1389 * is, returns last requested ID which is now very useful information.
1390 *
1391 * @usb_string_ids_n() is called from bind() callbacks to allocate
1392 * string IDs. Drivers for functions, configurations, or gadgets will
1393 * then store that ID in the appropriate descriptors and string table.
1394 *
1395 * All string identifier should be allocated using this,
1396 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1397 * example different functions don't wrongly assign different meanings
1398 * to the same identifier.
1399 */
1400int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1401{
1402 unsigned next = c->next_string_id;
1403 if (unlikely(n > 254 || (unsigned)next + n > 254))
1404 return -ENODEV;
1405 c->next_string_id += n;
1406 return next + 1;
1407}
1408EXPORT_SYMBOL_GPL(usb_string_ids_n);
1409
1410/*-------------------------------------------------------------------------*/
1411
1412static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1413{
1414 struct usb_composite_dev *cdev;
1415
1416 if (req->status || req->actual != req->length)
1417 DBG((struct usb_composite_dev *) ep->driver_data,
1418 "setup complete --> %d, %d/%d\n",
1419 req->status, req->actual, req->length);
1420
1421 /*
1422 * REVIST The same ep0 requests are shared with function drivers
1423 * so they don't have to maintain the same ->complete() stubs.
1424 *
1425 * Because of that, we need to check for the validity of ->context
1426 * here, even though we know we've set it to something useful.
1427 */
1428 if (!req->context)
1429 return;
1430
1431 cdev = req->context;
1432
1433 if (cdev->req == req)
1434 cdev->setup_pending = false;
1435 else if (cdev->os_desc_req == req)
1436 cdev->os_desc_pending = false;
1437 else
1438 WARN(1, "unknown request %p\n", req);
1439}
1440
1441static int composite_ep0_queue(struct usb_composite_dev *cdev,
1442 struct usb_request *req, gfp_t gfp_flags)
1443{
1444 int ret;
1445
1446 ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1447 if (ret == 0) {
1448 if (cdev->req == req)
1449 cdev->setup_pending = true;
1450 else if (cdev->os_desc_req == req)
1451 cdev->os_desc_pending = true;
1452 else
1453 WARN(1, "unknown request %p\n", req);
1454 }
1455
1456 return ret;
1457}
1458
1459static int count_ext_compat(struct usb_configuration *c)
1460{
1461 int i, res;
1462
1463 res = 0;
1464 for (i = 0; i < c->next_interface_id; ++i) {
1465 struct usb_function *f;
1466 int j;
1467
1468 f = c->interface[i];
1469 for (j = 0; j < f->os_desc_n; ++j) {
1470 struct usb_os_desc *d;
1471
1472 if (i != f->os_desc_table[j].if_id)
1473 continue;
1474 d = f->os_desc_table[j].os_desc;
1475 if (d && d->ext_compat_id)
1476 ++res;
1477 }
1478 }
1479 BUG_ON(res > 255);
1480 return res;
1481}
1482
1483static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1484{
1485 int i, count;
1486
1487 count = 16;
1488 for (i = 0; i < c->next_interface_id; ++i) {
1489 struct usb_function *f;
1490 int j;
1491
1492 f = c->interface[i];
1493 for (j = 0; j < f->os_desc_n; ++j) {
1494 struct usb_os_desc *d;
1495
1496 if (i != f->os_desc_table[j].if_id)
1497 continue;
1498 d = f->os_desc_table[j].os_desc;
1499 if (d && d->ext_compat_id) {
1500 *buf++ = i;
1501 *buf++ = 0x01;
1502 memcpy(buf, d->ext_compat_id, 16);
1503 buf += 22;
1504 } else {
1505 ++buf;
1506 *buf = 0x01;
1507 buf += 23;
1508 }
1509 count += 24;
1510 if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1511 return count;
1512 }
1513 }
1514
1515 return count;
1516}
1517
1518static int count_ext_prop(struct usb_configuration *c, int interface)
1519{
1520 struct usb_function *f;
1521 int j;
1522
1523 f = c->interface[interface];
1524 for (j = 0; j < f->os_desc_n; ++j) {
1525 struct usb_os_desc *d;
1526
1527 if (interface != f->os_desc_table[j].if_id)
1528 continue;
1529 d = f->os_desc_table[j].os_desc;
1530 if (d && d->ext_compat_id)
1531 return d->ext_prop_count;
1532 }
1533 return 0;
1534}
1535
1536static int len_ext_prop(struct usb_configuration *c, int interface)
1537{
1538 struct usb_function *f;
1539 struct usb_os_desc *d;
1540 int j, res;
1541
1542 res = 10; /* header length */
1543 f = c->interface[interface];
1544 for (j = 0; j < f->os_desc_n; ++j) {
1545 if (interface != f->os_desc_table[j].if_id)
1546 continue;
1547 d = f->os_desc_table[j].os_desc;
1548 if (d)
1549 return min(res + d->ext_prop_len, 4096);
1550 }
1551 return res;
1552}
1553
1554static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1555{
1556 struct usb_function *f;
1557 struct usb_os_desc *d;
1558 struct usb_os_desc_ext_prop *ext_prop;
1559 int j, count, n, ret;
1560
1561 f = c->interface[interface];
1562 count = 10; /* header length */
1563 for (j = 0; j < f->os_desc_n; ++j) {
1564 if (interface != f->os_desc_table[j].if_id)
1565 continue;
1566 d = f->os_desc_table[j].os_desc;
1567 if (d)
1568 list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1569 n = ext_prop->data_len +
1570 ext_prop->name_len + 14;
1571 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1572 return count;
1573 usb_ext_prop_put_size(buf, n);
1574 usb_ext_prop_put_type(buf, ext_prop->type);
1575 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1576 ext_prop->name_len);
1577 if (ret < 0)
1578 return ret;
1579 switch (ext_prop->type) {
1580 case USB_EXT_PROP_UNICODE:
1581 case USB_EXT_PROP_UNICODE_ENV:
1582 case USB_EXT_PROP_UNICODE_LINK:
1583 usb_ext_prop_put_unicode(buf, ret,
1584 ext_prop->data,
1585 ext_prop->data_len);
1586 break;
1587 case USB_EXT_PROP_BINARY:
1588 usb_ext_prop_put_binary(buf, ret,
1589 ext_prop->data,
1590 ext_prop->data_len);
1591 break;
1592 case USB_EXT_PROP_LE32:
1593 /* not implemented */
1594 case USB_EXT_PROP_BE32:
1595 /* not implemented */
1596 default:
1597 return -EINVAL;
1598 }
1599 buf += n;
1600 count += n;
1601 }
1602 }
1603
1604 return count;
1605}
1606
1607/*
1608 * The setup() callback implements all the ep0 functionality that's
1609 * not handled lower down, in hardware or the hardware driver(like
1610 * device and endpoint feature flags, and their status). It's all
1611 * housekeeping for the gadget function we're implementing. Most of
1612 * the work is in config and function specific setup.
1613 */
1614int
1615composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1616{
1617 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1618 struct usb_request *req = cdev->req;
1619 int value = -EOPNOTSUPP;
1620 int status = 0;
1621 u16 w_index = le16_to_cpu(ctrl->wIndex);
1622 u8 intf = w_index & 0xFF;
1623 u16 w_value = le16_to_cpu(ctrl->wValue);
1624 u16 w_length = le16_to_cpu(ctrl->wLength);
1625 struct usb_function *f = NULL;
1626 u8 endp;
1627
1628 /* partial re-init of the response message; the function or the
1629 * gadget might need to intercept e.g. a control-OUT completion
1630 * when we delegate to it.
1631 */
1632 req->zero = 0;
1633 req->context = cdev;
1634 req->complete = composite_setup_complete;
1635 req->length = 0;
1636 gadget->ep0->driver_data = cdev;
1637
1638 /*
1639 * Don't let non-standard requests match any of the cases below
1640 * by accident.
1641 */
1642 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1643 goto unknown;
1644
1645 switch (ctrl->bRequest) {
1646
1647 /* we handle all standard USB descriptors */
1648 case USB_REQ_GET_DESCRIPTOR:
1649 if (ctrl->bRequestType != USB_DIR_IN)
1650 goto unknown;
1651 switch (w_value >> 8) {
1652
1653 case USB_DT_DEVICE:
1654 cdev->desc.bNumConfigurations =
1655 count_configs(cdev, USB_DT_DEVICE);
1656 cdev->desc.bMaxPacketSize0 =
1657 cdev->gadget->ep0->maxpacket;
1658 if (gadget_is_superspeed(gadget)) {
1659 if (gadget->speed >= USB_SPEED_SUPER) {
1660 cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1661 cdev->desc.bMaxPacketSize0 = 9;
1662 } else {
1663 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1664 }
1665 } else {
1666 if (gadget->lpm_capable)
1667 cdev->desc.bcdUSB = cpu_to_le16(0x0201);
1668 else
1669 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1670 }
1671
1672 value = min(w_length, (u16) sizeof cdev->desc);
1673 memcpy(req->buf, &cdev->desc, value);
1674 break;
1675 case USB_DT_DEVICE_QUALIFIER:
1676 if (!gadget_is_dualspeed(gadget) ||
1677 gadget->speed >= USB_SPEED_SUPER)
1678 break;
1679 device_qual(cdev);
1680 value = min_t(int, w_length,
1681 sizeof(struct usb_qualifier_descriptor));
1682 break;
1683 case USB_DT_OTHER_SPEED_CONFIG:
1684 if (!gadget_is_dualspeed(gadget) ||
1685 gadget->speed >= USB_SPEED_SUPER)
1686 break;
1687 /* FALLTHROUGH */
1688 case USB_DT_CONFIG:
1689 value = config_desc(cdev, w_value);
1690 if (value >= 0)
1691 value = min(w_length, (u16) value);
1692 break;
1693 case USB_DT_STRING:
1694 value = get_string(cdev, req->buf,
1695 w_index, w_value & 0xff);
1696 if (value >= 0)
1697 value = min(w_length, (u16) value);
1698 break;
1699 case USB_DT_BOS:
1700 if (gadget_is_superspeed(gadget) ||
1701 gadget->lpm_capable) {
1702 value = bos_desc(cdev);
1703 value = min(w_length, (u16) value);
1704 }
1705 break;
1706 case USB_DT_OTG:
1707 if (gadget_is_otg(gadget)) {
1708 struct usb_configuration *config;
1709 int otg_desc_len = 0;
1710
1711 if (cdev->config)
1712 config = cdev->config;
1713 else
1714 config = list_first_entry(
1715 &cdev->configs,
1716 struct usb_configuration, list);
1717 if (!config)
1718 goto done;
1719
1720 if (gadget->otg_caps &&
1721 (gadget->otg_caps->otg_rev >= 0x0200))
1722 otg_desc_len += sizeof(
1723 struct usb_otg20_descriptor);
1724 else
1725 otg_desc_len += sizeof(
1726 struct usb_otg_descriptor);
1727
1728 value = min_t(int, w_length, otg_desc_len);
1729 memcpy(req->buf, config->descriptors[0], value);
1730 }
1731 break;
1732 }
1733 break;
1734
1735 /* any number of configs can work */
1736 case USB_REQ_SET_CONFIGURATION:
1737 if (ctrl->bRequestType != 0)
1738 goto unknown;
1739 if (gadget_is_otg(gadget)) {
1740 if (gadget->a_hnp_support)
1741 DBG(cdev, "HNP available\n");
1742 else if (gadget->a_alt_hnp_support)
1743 DBG(cdev, "HNP on another port\n");
1744 else
1745 VDBG(cdev, "HNP inactive\n");
1746 }
1747 spin_lock(&cdev->lock);
1748 value = set_config(cdev, ctrl, w_value);
1749 spin_unlock(&cdev->lock);
1750 break;
1751 case USB_REQ_GET_CONFIGURATION:
1752 if (ctrl->bRequestType != USB_DIR_IN)
1753 goto unknown;
1754 if (cdev->config)
1755 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1756 else
1757 *(u8 *)req->buf = 0;
1758 value = min(w_length, (u16) 1);
1759 break;
1760
1761 /* function drivers must handle get/set altsetting */
1762 case USB_REQ_SET_INTERFACE:
1763 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1764 goto unknown;
1765 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1766 break;
1767 f = cdev->config->interface[intf];
1768 if (!f)
1769 break;
1770
1771 /*
1772 * If there's no get_alt() method, we know only altsetting zero
1773 * works. There is no need to check if set_alt() is not NULL
1774 * as we check this in usb_add_function().
1775 */
1776 if (w_value && !f->get_alt)
1777 break;
1778
1779 spin_lock(&cdev->lock);
1780 value = f->set_alt(f, w_index, w_value);
1781 if (value == USB_GADGET_DELAYED_STATUS) {
1782 DBG(cdev,
1783 "%s: interface %d (%s) requested delayed status\n",
1784 __func__, intf, f->name);
1785 cdev->delayed_status++;
1786 DBG(cdev, "delayed_status count %d\n",
1787 cdev->delayed_status);
1788 }
1789 spin_unlock(&cdev->lock);
1790 break;
1791 case USB_REQ_GET_INTERFACE:
1792 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1793 goto unknown;
1794 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1795 break;
1796 f = cdev->config->interface[intf];
1797 if (!f)
1798 break;
1799 /* lots of interfaces only need altsetting zero... */
1800 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1801 if (value < 0)
1802 break;
1803 *((u8 *)req->buf) = value;
1804 value = min(w_length, (u16) 1);
1805 break;
1806 case USB_REQ_GET_STATUS:
1807 if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1808 (w_index == OTG_STS_SELECTOR)) {
1809 if (ctrl->bRequestType != (USB_DIR_IN |
1810 USB_RECIP_DEVICE))
1811 goto unknown;
1812 *((u8 *)req->buf) = gadget->host_request_flag;
1813 value = 1;
1814 break;
1815 }
1816
1817 /*
1818 * USB 3.0 additions:
1819 * Function driver should handle get_status request. If such cb
1820 * wasn't supplied we respond with default value = 0
1821 * Note: function driver should supply such cb only for the
1822 * first interface of the function
1823 */
1824 if (!gadget_is_superspeed(gadget))
1825 goto unknown;
1826 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1827 goto unknown;
1828 value = 2; /* This is the length of the get_status reply */
1829 put_unaligned_le16(0, req->buf);
1830 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1831 break;
1832 f = cdev->config->interface[intf];
1833 if (!f)
1834 break;
1835 status = f->get_status ? f->get_status(f) : 0;
1836 if (status < 0)
1837 break;
1838 put_unaligned_le16(status & 0x0000ffff, req->buf);
1839 break;
1840 /*
1841 * Function drivers should handle SetFeature/ClearFeature
1842 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1843 * only for the first interface of the function
1844 */
1845 case USB_REQ_CLEAR_FEATURE:
1846 case USB_REQ_SET_FEATURE:
1847 if (!gadget_is_superspeed(gadget))
1848 goto unknown;
1849 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1850 goto unknown;
1851 switch (w_value) {
1852 case USB_INTRF_FUNC_SUSPEND:
1853 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1854 break;
1855 f = cdev->config->interface[intf];
1856 if (!f)
1857 break;
1858 value = 0;
1859 if (f->func_suspend)
1860 value = f->func_suspend(f, w_index >> 8);
1861 if (value < 0) {
1862 ERROR(cdev,
1863 "func_suspend() returned error %d\n",
1864 value);
1865 value = 0;
1866 }
1867 break;
1868 }
1869 break;
1870 default:
1871unknown:
1872 /*
1873 * OS descriptors handling
1874 */
1875 if (cdev->use_os_string && cdev->os_desc_config &&
1876 (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1877 ctrl->bRequest == cdev->b_vendor_code) {
1878 struct usb_request *req;
1879 struct usb_configuration *os_desc_cfg;
1880 u8 *buf;
1881 int interface;
1882 int count = 0;
1883
1884 req = cdev->os_desc_req;
1885 req->context = cdev;
1886 req->complete = composite_setup_complete;
1887 buf = req->buf;
1888 os_desc_cfg = cdev->os_desc_config;
1889 w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1890 memset(buf, 0, w_length);
1891 buf[5] = 0x01;
1892 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1893 case USB_RECIP_DEVICE:
1894 if (w_index != 0x4 || (w_value >> 8))
1895 break;
1896 buf[6] = w_index;
1897 if (w_length == 0x10) {
1898 /* Number of ext compat interfaces */
1899 count = count_ext_compat(os_desc_cfg);
1900 buf[8] = count;
1901 count *= 24; /* 24 B/ext compat desc */
1902 count += 16; /* header */
1903 put_unaligned_le32(count, buf);
1904 value = w_length;
1905 } else {
1906 /* "extended compatibility ID"s */
1907 count = count_ext_compat(os_desc_cfg);
1908 buf[8] = count;
1909 count *= 24; /* 24 B/ext compat desc */
1910 count += 16; /* header */
1911 put_unaligned_le32(count, buf);
1912 buf += 16;
1913 value = fill_ext_compat(os_desc_cfg, buf);
1914 value = min_t(u16, w_length, value);
1915 }
1916 break;
1917 case USB_RECIP_INTERFACE:
1918 if (w_index != 0x5 || (w_value >> 8))
1919 break;
1920 interface = w_value & 0xFF;
1921 buf[6] = w_index;
1922 if (w_length == 0x0A) {
1923 count = count_ext_prop(os_desc_cfg,
1924 interface);
1925 put_unaligned_le16(count, buf + 8);
1926 count = len_ext_prop(os_desc_cfg,
1927 interface);
1928 put_unaligned_le32(count, buf);
1929
1930 value = w_length;
1931 } else {
1932 count = count_ext_prop(os_desc_cfg,
1933 interface);
1934 put_unaligned_le16(count, buf + 8);
1935 count = len_ext_prop(os_desc_cfg,
1936 interface);
1937 put_unaligned_le32(count, buf);
1938 buf += 10;
1939 value = fill_ext_prop(os_desc_cfg,
1940 interface, buf);
1941 if (value < 0)
1942 return value;
1943 value = min_t(u16, w_length, value);
1944 }
1945 break;
1946 }
1947
1948 if (value >= 0) {
1949 req->length = value;
1950 req->context = cdev;
1951 req->zero = value < w_length;
1952 value = composite_ep0_queue(cdev, req,
1953 GFP_ATOMIC);
1954 if (value < 0) {
1955 DBG(cdev, "ep_queue --> %d\n", value);
1956 req->status = 0;
1957 composite_setup_complete(gadget->ep0,
1958 req);
1959 }
1960 }
1961 return value;
1962 }
1963
1964 VDBG(cdev,
1965 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1966 ctrl->bRequestType, ctrl->bRequest,
1967 w_value, w_index, w_length);
1968
1969 /* functions always handle their interfaces and endpoints...
1970 * punt other recipients (other, WUSB, ...) to the current
1971 * configuration code.
1972 */
1973 if (cdev->config) {
1974 list_for_each_entry(f, &cdev->config->functions, list)
1975 if (f->req_match &&
1976 f->req_match(f, ctrl, false))
1977 goto try_fun_setup;
1978 } else {
1979 struct usb_configuration *c;
1980 list_for_each_entry(c, &cdev->configs, list)
1981 list_for_each_entry(f, &c->functions, list)
1982 if (f->req_match &&
1983 f->req_match(f, ctrl, true))
1984 goto try_fun_setup;
1985 }
1986 f = NULL;
1987
1988 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1989 case USB_RECIP_INTERFACE:
1990 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1991 break;
1992 f = cdev->config->interface[intf];
1993 break;
1994
1995 case USB_RECIP_ENDPOINT:
1996 if (!cdev->config)
1997 break;
1998 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1999 list_for_each_entry(f, &cdev->config->functions, list) {
2000 if (test_bit(endp, f->endpoints))
2001 break;
2002 }
2003 if (&f->list == &cdev->config->functions)
2004 f = NULL;
2005 break;
2006 }
2007try_fun_setup:
2008 if (f && f->setup)
2009 value = f->setup(f, ctrl);
2010 else {
2011 struct usb_configuration *c;
2012
2013 c = cdev->config;
2014 if (!c)
2015 goto done;
2016
2017 /* try current config's setup */
2018 if (c->setup) {
2019 value = c->setup(c, ctrl);
2020 goto done;
2021 }
2022
2023 /* try the only function in the current config */
2024 if (!list_is_singular(&c->functions))
2025 goto done;
2026 f = list_first_entry(&c->functions, struct usb_function,
2027 list);
2028 if (f->setup)
2029 value = f->setup(f, ctrl);
2030 }
2031
2032 goto done;
2033 }
2034
2035 /* respond with data transfer before status phase? */
2036 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2037 req->length = value;
2038 req->context = cdev;
2039 req->zero = value < w_length;
2040 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2041 if (value < 0) {
2042 DBG(cdev, "ep_queue --> %d\n", value);
2043 req->status = 0;
2044 composite_setup_complete(gadget->ep0, req);
2045 }
2046 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2047 WARN(cdev,
2048 "%s: Delayed status not supported for w_length != 0",
2049 __func__);
2050 }
2051
2052done:
2053 /* device either stalls (value < 0) or reports success */
2054 return value;
2055}
2056
2057void composite_disconnect(struct usb_gadget *gadget)
2058{
2059 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2060 unsigned long flags;
2061
2062 if (cdev == NULL) {
2063 WARN(1, "%s: Calling disconnect on a Gadget that is \
2064 not connected\n", __func__);
2065 return;
2066 }
2067
2068 /* REVISIT: should we have config and device level
2069 * disconnect callbacks?
2070 */
2071 spin_lock_irqsave(&cdev->lock, flags);
2072 cdev->suspended = 0;
2073 if (cdev->config)
2074 reset_config(cdev);
2075 if (cdev->driver->disconnect)
2076 cdev->driver->disconnect(cdev);
2077 spin_unlock_irqrestore(&cdev->lock, flags);
2078}
2079
2080/*-------------------------------------------------------------------------*/
2081
2082static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2083 char *buf)
2084{
2085 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2086 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2087
2088 return sprintf(buf, "%d\n", cdev->suspended);
2089}
2090static DEVICE_ATTR_RO(suspended);
2091
2092static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2093{
2094 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2095 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2096 struct usb_string *dev_str = gstr->strings;
2097
2098 /* composite_disconnect() must already have been called
2099 * by the underlying peripheral controller driver!
2100 * so there's no i/o concurrency that could affect the
2101 * state protected by cdev->lock.
2102 */
2103 WARN_ON(cdev->config);
2104
2105 while (!list_empty(&cdev->configs)) {
2106 struct usb_configuration *c;
2107 c = list_first_entry(&cdev->configs,
2108 struct usb_configuration, list);
2109 remove_config(cdev, c);
2110 }
2111 if (cdev->driver->unbind && unbind_driver)
2112 cdev->driver->unbind(cdev);
2113
2114 composite_dev_cleanup(cdev);
2115
2116 if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2117 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2118
2119 kfree(cdev->def_manufacturer);
2120 kfree(cdev);
2121 set_gadget_data(gadget, NULL);
2122}
2123
2124static void composite_unbind(struct usb_gadget *gadget)
2125{
2126 __composite_unbind(gadget, true);
2127}
2128
2129static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2130 const struct usb_device_descriptor *old)
2131{
2132 __le16 idVendor;
2133 __le16 idProduct;
2134 __le16 bcdDevice;
2135 u8 iSerialNumber;
2136 u8 iManufacturer;
2137 u8 iProduct;
2138
2139 /*
2140 * these variables may have been set in
2141 * usb_composite_overwrite_options()
2142 */
2143 idVendor = new->idVendor;
2144 idProduct = new->idProduct;
2145 bcdDevice = new->bcdDevice;
2146 iSerialNumber = new->iSerialNumber;
2147 iManufacturer = new->iManufacturer;
2148 iProduct = new->iProduct;
2149
2150 *new = *old;
2151 if (idVendor)
2152 new->idVendor = idVendor;
2153 if (idProduct)
2154 new->idProduct = idProduct;
2155 if (bcdDevice)
2156 new->bcdDevice = bcdDevice;
2157 else
2158 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2159 if (iSerialNumber)
2160 new->iSerialNumber = iSerialNumber;
2161 if (iManufacturer)
2162 new->iManufacturer = iManufacturer;
2163 if (iProduct)
2164 new->iProduct = iProduct;
2165}
2166
2167int composite_dev_prepare(struct usb_composite_driver *composite,
2168 struct usb_composite_dev *cdev)
2169{
2170 struct usb_gadget *gadget = cdev->gadget;
2171 int ret = -ENOMEM;
2172
2173 /* preallocate control response and buffer */
2174 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2175 if (!cdev->req)
2176 return -ENOMEM;
2177
2178 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2179 if (!cdev->req->buf)
2180 goto fail;
2181
2182 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2183 if (ret)
2184 goto fail_dev;
2185
2186 cdev->req->complete = composite_setup_complete;
2187 cdev->req->context = cdev;
2188 gadget->ep0->driver_data = cdev;
2189
2190 cdev->driver = composite;
2191
2192 /*
2193 * As per USB compliance update, a device that is actively drawing
2194 * more than 100mA from USB must report itself as bus-powered in
2195 * the GetStatus(DEVICE) call.
2196 */
2197 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2198 usb_gadget_set_selfpowered(gadget);
2199
2200 /* interface and string IDs start at zero via kzalloc.
2201 * we force endpoints to start unassigned; few controller
2202 * drivers will zero ep->driver_data.
2203 */
2204 usb_ep_autoconfig_reset(gadget);
2205 return 0;
2206fail_dev:
2207 kfree(cdev->req->buf);
2208fail:
2209 usb_ep_free_request(gadget->ep0, cdev->req);
2210 cdev->req = NULL;
2211 return ret;
2212}
2213
2214int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2215 struct usb_ep *ep0)
2216{
2217 int ret = 0;
2218
2219 cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2220 if (!cdev->os_desc_req) {
2221 ret = -ENOMEM;
2222 goto end;
2223 }
2224
2225 cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2226 GFP_KERNEL);
2227 if (!cdev->os_desc_req->buf) {
2228 ret = -ENOMEM;
2229 usb_ep_free_request(ep0, cdev->os_desc_req);
2230 goto end;
2231 }
2232 cdev->os_desc_req->context = cdev;
2233 cdev->os_desc_req->complete = composite_setup_complete;
2234end:
2235 return ret;
2236}
2237
2238void composite_dev_cleanup(struct usb_composite_dev *cdev)
2239{
2240 struct usb_gadget_string_container *uc, *tmp;
2241
2242 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2243 list_del(&uc->list);
2244 kfree(uc);
2245 }
2246 if (cdev->os_desc_req) {
2247 if (cdev->os_desc_pending)
2248 usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2249
2250 kfree(cdev->os_desc_req->buf);
2251 cdev->os_desc_req->buf = NULL;
2252 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2253 cdev->os_desc_req = NULL;
2254 }
2255 if (cdev->req) {
2256 if (cdev->setup_pending)
2257 usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2258
2259 kfree(cdev->req->buf);
2260 cdev->req->buf = NULL;
2261 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2262 cdev->req = NULL;
2263 }
2264 cdev->next_string_id = 0;
2265 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2266}
2267
2268static int composite_bind(struct usb_gadget *gadget,
2269 struct usb_gadget_driver *gdriver)
2270{
2271 struct usb_composite_dev *cdev;
2272 struct usb_composite_driver *composite = to_cdriver(gdriver);
2273 int status = -ENOMEM;
2274
2275 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2276 if (!cdev)
2277 return status;
2278
2279 spin_lock_init(&cdev->lock);
2280 cdev->gadget = gadget;
2281 set_gadget_data(gadget, cdev);
2282 INIT_LIST_HEAD(&cdev->configs);
2283 INIT_LIST_HEAD(&cdev->gstrings);
2284
2285 status = composite_dev_prepare(composite, cdev);
2286 if (status)
2287 goto fail;
2288
2289 /* composite gadget needs to assign strings for whole device (like
2290 * serial number), register function drivers, potentially update
2291 * power state and consumption, etc
2292 */
2293 status = composite->bind(cdev);
2294 if (status < 0)
2295 goto fail;
2296
2297 if (cdev->use_os_string) {
2298 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2299 if (status)
2300 goto fail;
2301 }
2302
2303 update_unchanged_dev_desc(&cdev->desc, composite->dev);
2304
2305 /* has userspace failed to provide a serial number? */
2306 if (composite->needs_serial && !cdev->desc.iSerialNumber)
2307 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2308
2309 INFO(cdev, "%s ready\n", composite->name);
2310 return 0;
2311
2312fail:
2313 __composite_unbind(gadget, false);
2314 return status;
2315}
2316
2317/*-------------------------------------------------------------------------*/
2318
2319void composite_suspend(struct usb_gadget *gadget)
2320{
2321 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2322 struct usb_function *f;
2323
2324 /* REVISIT: should we have config level
2325 * suspend/resume callbacks?
2326 */
2327 DBG(cdev, "suspend\n");
2328 if (cdev->config) {
2329 list_for_each_entry(f, &cdev->config->functions, list) {
2330 if (f->suspend)
2331 f->suspend(f);
2332 }
2333 }
2334 if (cdev->driver->suspend)
2335 cdev->driver->suspend(cdev);
2336
2337 cdev->suspended = 1;
2338
2339 usb_gadget_set_selfpowered(gadget);
2340 usb_gadget_vbus_draw(gadget, 2);
2341}
2342
2343void composite_resume(struct usb_gadget *gadget)
2344{
2345 struct usb_composite_dev *cdev = get_gadget_data(gadget);
2346 struct usb_function *f;
2347 unsigned maxpower;
2348
2349 /* REVISIT: should we have config level
2350 * suspend/resume callbacks?
2351 */
2352 DBG(cdev, "resume\n");
2353 if (cdev->driver->resume)
2354 cdev->driver->resume(cdev);
2355 if (cdev->config) {
2356 list_for_each_entry(f, &cdev->config->functions, list) {
2357 if (f->resume)
2358 f->resume(f);
2359 }
2360
2361 maxpower = cdev->config->MaxPower ?
2362 cdev->config->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
2363 if (gadget->speed < USB_SPEED_SUPER)
2364 maxpower = min(maxpower, 500U);
2365 else
2366 maxpower = min(maxpower, 900U);
2367
2368 if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2369 usb_gadget_clear_selfpowered(gadget);
2370
2371 usb_gadget_vbus_draw(gadget, maxpower);
2372 }
2373
2374 cdev->suspended = 0;
2375}
2376
2377/*-------------------------------------------------------------------------*/
2378
2379static const struct usb_gadget_driver composite_driver_template = {
2380 .bind = composite_bind,
2381 .unbind = composite_unbind,
2382
2383 .setup = composite_setup,
2384 .reset = composite_disconnect,
2385 .disconnect = composite_disconnect,
2386
2387 .suspend = composite_suspend,
2388 .resume = composite_resume,
2389
2390 .driver = {
2391 .owner = THIS_MODULE,
2392 },
2393};
2394
2395/**
2396 * usb_composite_probe() - register a composite driver
2397 * @driver: the driver to register
2398 *
2399 * Context: single threaded during gadget setup
2400 *
2401 * This function is used to register drivers using the composite driver
2402 * framework. The return value is zero, or a negative errno value.
2403 * Those values normally come from the driver's @bind method, which does
2404 * all the work of setting up the driver to match the hardware.
2405 *
2406 * On successful return, the gadget is ready to respond to requests from
2407 * the host, unless one of its components invokes usb_gadget_disconnect()
2408 * while it was binding. That would usually be done in order to wait for
2409 * some userspace participation.
2410 */
2411int usb_composite_probe(struct usb_composite_driver *driver)
2412{
2413 struct usb_gadget_driver *gadget_driver;
2414
2415 if (!driver || !driver->dev || !driver->bind)
2416 return -EINVAL;
2417
2418 if (!driver->name)
2419 driver->name = "composite";
2420
2421 driver->gadget_driver = composite_driver_template;
2422 gadget_driver = &driver->gadget_driver;
2423
2424 gadget_driver->function = (char *) driver->name;
2425 gadget_driver->driver.name = driver->name;
2426 gadget_driver->max_speed = driver->max_speed;
2427
2428 return usb_gadget_probe_driver(gadget_driver);
2429}
2430EXPORT_SYMBOL_GPL(usb_composite_probe);
2431
2432/**
2433 * usb_composite_unregister() - unregister a composite driver
2434 * @driver: the driver to unregister
2435 *
2436 * This function is used to unregister drivers using the composite
2437 * driver framework.
2438 */
2439void usb_composite_unregister(struct usb_composite_driver *driver)
2440{
2441 usb_gadget_unregister_driver(&driver->gadget_driver);
2442}
2443EXPORT_SYMBOL_GPL(usb_composite_unregister);
2444
2445/**
2446 * usb_composite_setup_continue() - Continue with the control transfer
2447 * @cdev: the composite device who's control transfer was kept waiting
2448 *
2449 * This function must be called by the USB function driver to continue
2450 * with the control transfer's data/status stage in case it had requested to
2451 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2452 * can request the composite framework to delay the setup request's data/status
2453 * stages by returning USB_GADGET_DELAYED_STATUS.
2454 */
2455void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2456{
2457 int value;
2458 struct usb_request *req = cdev->req;
2459 unsigned long flags;
2460
2461 DBG(cdev, "%s\n", __func__);
2462 spin_lock_irqsave(&cdev->lock, flags);
2463
2464 if (cdev->delayed_status == 0) {
2465 WARN(cdev, "%s: Unexpected call\n", __func__);
2466
2467 } else if (--cdev->delayed_status == 0) {
2468 DBG(cdev, "%s: Completing delayed status\n", __func__);
2469 req->length = 0;
2470 req->context = cdev;
2471 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2472 if (value < 0) {
2473 DBG(cdev, "ep_queue --> %d\n", value);
2474 req->status = 0;
2475 composite_setup_complete(cdev->gadget->ep0, req);
2476 }
2477 }
2478
2479 spin_unlock_irqrestore(&cdev->lock, flags);
2480}
2481EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2482
2483static char *composite_default_mfr(struct usb_gadget *gadget)
2484{
2485 return kasprintf(GFP_KERNEL, "%s %s with %s", init_utsname()->sysname,
2486 init_utsname()->release, gadget->name);
2487}
2488
2489void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2490 struct usb_composite_overwrite *covr)
2491{
2492 struct usb_device_descriptor *desc = &cdev->desc;
2493 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
2494 struct usb_string *dev_str = gstr->strings;
2495
2496 if (covr->idVendor)
2497 desc->idVendor = cpu_to_le16(covr->idVendor);
2498
2499 if (covr->idProduct)
2500 desc->idProduct = cpu_to_le16(covr->idProduct);
2501
2502 if (covr->bcdDevice)
2503 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2504
2505 if (covr->serial_number) {
2506 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2507 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2508 }
2509 if (covr->manufacturer) {
2510 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2511 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2512
2513 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2514 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2515 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2516 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2517 }
2518
2519 if (covr->product) {
2520 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2521 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2522 }
2523}
2524EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2525
2526MODULE_LICENSE("GPL");
2527MODULE_AUTHOR("David Brownell");