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