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