usb: gadget: composite: correctly initialize ep->maxpacket
[GitHub/mt8127/android_kernel_alcatel_ttab.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 <asm/unaligned.h>
23
24 /*
25 * The code in this file is utility code, used to build a gadget driver
26 * from one or more "function" drivers, one or more "configuration"
27 * objects, and a "usb_composite_driver" by gluing them together along
28 * with the relevant device-wide data.
29 */
30
31 static struct usb_gadget_strings **get_containers_gs(
32 struct usb_gadget_string_container *uc)
33 {
34 return (struct usb_gadget_strings **)uc->stash;
35 }
36
37 /**
38 * next_ep_desc() - advance to the next EP descriptor
39 * @t: currect pointer within descriptor array
40 *
41 * Return: next EP descriptor or NULL
42 *
43 * Iterate over @t until either EP descriptor found or
44 * NULL (that indicates end of list) encountered
45 */
46 static struct usb_descriptor_header**
47 next_ep_desc(struct usb_descriptor_header **t)
48 {
49 for (; *t; t++) {
50 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
51 return t;
52 }
53 return NULL;
54 }
55
56 /*
57 * for_each_ep_desc()- iterate over endpoint descriptors in the
58 * descriptors list
59 * @start: pointer within descriptor array.
60 * @ep_desc: endpoint descriptor to use as the loop cursor
61 */
62 #define for_each_ep_desc(start, ep_desc) \
63 for (ep_desc = next_ep_desc(start); \
64 ep_desc; ep_desc = next_ep_desc(ep_desc+1))
65
66 /**
67 * config_ep_by_speed() - configures the given endpoint
68 * according to gadget speed.
69 * @g: pointer to the gadget
70 * @f: usb function
71 * @_ep: the endpoint to configure
72 *
73 * Return: error code, 0 on success
74 *
75 * This function chooses the right descriptors for a given
76 * endpoint according to gadget speed and saves it in the
77 * endpoint desc field. If the endpoint already has a descriptor
78 * assigned to it - overwrites it with currently corresponding
79 * descriptor. The endpoint maxpacket field is updated according
80 * to the chosen descriptor.
81 * Note: the supplied function should hold all the descriptors
82 * for supported speeds
83 */
84 int config_ep_by_speed(struct usb_gadget *g,
85 struct usb_function *f,
86 struct usb_ep *_ep)
87 {
88 struct usb_composite_dev *cdev = get_gadget_data(g);
89 struct usb_endpoint_descriptor *chosen_desc = NULL;
90 struct usb_descriptor_header **speed_desc = NULL;
91
92 struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
93 int want_comp_desc = 0;
94
95 struct usb_descriptor_header **d_spd; /* cursor for speed desc */
96
97 if (!g || !f || !_ep)
98 return -EIO;
99
100 /* select desired speed */
101 switch (g->speed) {
102 case USB_SPEED_SUPER:
103 if (gadget_is_superspeed(g)) {
104 speed_desc = f->ss_descriptors;
105 want_comp_desc = 1;
106 break;
107 }
108 /* else: Fall trough */
109 case USB_SPEED_HIGH:
110 if (gadget_is_dualspeed(g)) {
111 speed_desc = f->hs_descriptors;
112 break;
113 }
114 /* else: fall through */
115 default:
116 speed_desc = f->fs_descriptors;
117 }
118 /* find descriptors */
119 for_each_ep_desc(speed_desc, d_spd) {
120 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
121 if (chosen_desc->bEndpointAddress == _ep->address)
122 goto ep_found;
123 }
124 return -EIO;
125
126 ep_found:
127 /* commit results */
128 _ep->maxpacket = usb_endpoint_maxp(chosen_desc) & 0x7ff;
129 _ep->desc = chosen_desc;
130 _ep->comp_desc = NULL;
131 _ep->maxburst = 0;
132 _ep->mult = 1;
133
134 if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
135 usb_endpoint_xfer_int(_ep->desc)))
136 _ep->mult = ((usb_endpoint_maxp(_ep->desc) & 0x1800) >> 11) + 1;
137
138 if (!want_comp_desc)
139 return 0;
140
141 /*
142 * Companion descriptor should follow EP descriptor
143 * USB 3.0 spec, #9.6.7
144 */
145 comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
146 if (!comp_desc ||
147 (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
148 return -EIO;
149 _ep->comp_desc = comp_desc;
150 if (g->speed == USB_SPEED_SUPER) {
151 switch (usb_endpoint_type(_ep->desc)) {
152 case USB_ENDPOINT_XFER_ISOC:
153 /* mult: bits 1:0 of bmAttributes */
154 _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
155 case USB_ENDPOINT_XFER_BULK:
156 case USB_ENDPOINT_XFER_INT:
157 _ep->maxburst = comp_desc->bMaxBurst + 1;
158 break;
159 default:
160 if (comp_desc->bMaxBurst != 0)
161 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
162 _ep->maxburst = 1;
163 break;
164 }
165 }
166 return 0;
167 }
168 EXPORT_SYMBOL_GPL(config_ep_by_speed);
169
170 /**
171 * usb_add_function() - add a function to a configuration
172 * @config: the configuration
173 * @function: the function being added
174 * Context: single threaded during gadget setup
175 *
176 * After initialization, each configuration must have one or more
177 * functions added to it. Adding a function involves calling its @bind()
178 * method to allocate resources such as interface and string identifiers
179 * and endpoints.
180 *
181 * This function returns the value of the function's bind(), which is
182 * zero for success else a negative errno value.
183 */
184 int usb_add_function(struct usb_configuration *config,
185 struct usb_function *function)
186 {
187 int value = -EINVAL;
188
189 DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
190 function->name, function,
191 config->label, config);
192
193 if (!function->set_alt || !function->disable)
194 goto done;
195
196 function->config = config;
197 list_add_tail(&function->list, &config->functions);
198
199 /* REVISIT *require* function->bind? */
200 if (function->bind) {
201 value = function->bind(config, function);
202 if (value < 0) {
203 list_del(&function->list);
204 function->config = NULL;
205 }
206 } else
207 value = 0;
208
209 /* We allow configurations that don't work at both speeds.
210 * If we run into a lowspeed Linux system, treat it the same
211 * as full speed ... it's the function drivers that will need
212 * to avoid bulk and ISO transfers.
213 */
214 if (!config->fullspeed && function->fs_descriptors)
215 config->fullspeed = true;
216 if (!config->highspeed && function->hs_descriptors)
217 config->highspeed = true;
218 if (!config->superspeed && function->ss_descriptors)
219 config->superspeed = true;
220
221 done:
222 if (value)
223 DBG(config->cdev, "adding '%s'/%p --> %d\n",
224 function->name, function, value);
225 return value;
226 }
227 EXPORT_SYMBOL_GPL(usb_add_function);
228
229 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
230 {
231 if (f->disable)
232 f->disable(f);
233
234 bitmap_zero(f->endpoints, 32);
235 list_del(&f->list);
236 if (f->unbind)
237 f->unbind(c, f);
238 }
239 EXPORT_SYMBOL_GPL(usb_remove_function);
240
241 /**
242 * usb_function_deactivate - prevent function and gadget enumeration
243 * @function: the function that isn't yet ready to respond
244 *
245 * Blocks response of the gadget driver to host enumeration by
246 * preventing the data line pullup from being activated. This is
247 * normally called during @bind() processing to change from the
248 * initial "ready to respond" state, or when a required resource
249 * becomes available.
250 *
251 * For example, drivers that serve as a passthrough to a userspace
252 * daemon can block enumeration unless that daemon (such as an OBEX,
253 * MTP, or print server) is ready to handle host requests.
254 *
255 * Not all systems support software control of their USB peripheral
256 * data pullups.
257 *
258 * Returns zero on success, else negative errno.
259 */
260 int usb_function_deactivate(struct usb_function *function)
261 {
262 struct usb_composite_dev *cdev = function->config->cdev;
263 unsigned long flags;
264 int status = 0;
265
266 spin_lock_irqsave(&cdev->lock, flags);
267
268 if (cdev->deactivations == 0)
269 status = usb_gadget_disconnect(cdev->gadget);
270 if (status == 0)
271 cdev->deactivations++;
272
273 spin_unlock_irqrestore(&cdev->lock, flags);
274 return status;
275 }
276 EXPORT_SYMBOL_GPL(usb_function_deactivate);
277
278 /**
279 * usb_function_activate - allow function and gadget enumeration
280 * @function: function on which usb_function_activate() was called
281 *
282 * Reverses effect of usb_function_deactivate(). If no more functions
283 * are delaying their activation, the gadget driver will respond to
284 * host enumeration procedures.
285 *
286 * Returns zero on success, else negative errno.
287 */
288 int usb_function_activate(struct usb_function *function)
289 {
290 struct usb_composite_dev *cdev = function->config->cdev;
291 unsigned long flags;
292 int status = 0;
293
294 spin_lock_irqsave(&cdev->lock, flags);
295
296 if (WARN_ON(cdev->deactivations == 0))
297 status = -EINVAL;
298 else {
299 cdev->deactivations--;
300 if (cdev->deactivations == 0)
301 status = usb_gadget_connect(cdev->gadget);
302 }
303
304 spin_unlock_irqrestore(&cdev->lock, flags);
305 return status;
306 }
307 EXPORT_SYMBOL_GPL(usb_function_activate);
308
309 /**
310 * usb_interface_id() - allocate an unused interface ID
311 * @config: configuration associated with the interface
312 * @function: function handling the interface
313 * Context: single threaded during gadget setup
314 *
315 * usb_interface_id() is called from usb_function.bind() callbacks to
316 * allocate new interface IDs. The function driver will then store that
317 * ID in interface, association, CDC union, and other descriptors. It
318 * will also handle any control requests targeted at that interface,
319 * particularly changing its altsetting via set_alt(). There may
320 * also be class-specific or vendor-specific requests to handle.
321 *
322 * All interface identifier should be allocated using this routine, to
323 * ensure that for example different functions don't wrongly assign
324 * different meanings to the same identifier. Note that since interface
325 * identifiers are configuration-specific, functions used in more than
326 * one configuration (or more than once in a given configuration) need
327 * multiple versions of the relevant descriptors.
328 *
329 * Returns the interface ID which was allocated; or -ENODEV if no
330 * more interface IDs can be allocated.
331 */
332 int usb_interface_id(struct usb_configuration *config,
333 struct usb_function *function)
334 {
335 unsigned id = config->next_interface_id;
336
337 if (id < MAX_CONFIG_INTERFACES) {
338 config->interface[id] = function;
339 config->next_interface_id = id + 1;
340 return id;
341 }
342 return -ENODEV;
343 }
344 EXPORT_SYMBOL_GPL(usb_interface_id);
345
346 static u8 encode_bMaxPower(enum usb_device_speed speed,
347 struct usb_configuration *c)
348 {
349 unsigned val;
350
351 if (c->MaxPower)
352 val = c->MaxPower;
353 else
354 val = CONFIG_USB_GADGET_VBUS_DRAW;
355 if (!val)
356 return 0;
357 switch (speed) {
358 case USB_SPEED_SUPER:
359 return DIV_ROUND_UP(val, 8);
360 default:
361 return DIV_ROUND_UP(val, 2);
362 };
363 }
364
365 static int config_buf(struct usb_configuration *config,
366 enum usb_device_speed speed, void *buf, u8 type)
367 {
368 struct usb_config_descriptor *c = buf;
369 void *next = buf + USB_DT_CONFIG_SIZE;
370 int len;
371 struct usb_function *f;
372 int status;
373
374 len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
375 /* write the config descriptor */
376 c = buf;
377 c->bLength = USB_DT_CONFIG_SIZE;
378 c->bDescriptorType = type;
379 /* wTotalLength is written later */
380 c->bNumInterfaces = config->next_interface_id;
381 c->bConfigurationValue = config->bConfigurationValue;
382 c->iConfiguration = config->iConfiguration;
383 c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
384 c->bMaxPower = encode_bMaxPower(speed, config);
385
386 /* There may be e.g. OTG descriptors */
387 if (config->descriptors) {
388 status = usb_descriptor_fillbuf(next, len,
389 config->descriptors);
390 if (status < 0)
391 return status;
392 len -= status;
393 next += status;
394 }
395
396 /* add each function's descriptors */
397 list_for_each_entry(f, &config->functions, list) {
398 struct usb_descriptor_header **descriptors;
399
400 switch (speed) {
401 case USB_SPEED_SUPER:
402 descriptors = f->ss_descriptors;
403 break;
404 case USB_SPEED_HIGH:
405 descriptors = f->hs_descriptors;
406 break;
407 default:
408 descriptors = f->fs_descriptors;
409 }
410
411 if (!descriptors)
412 continue;
413 status = usb_descriptor_fillbuf(next, len,
414 (const struct usb_descriptor_header **) descriptors);
415 if (status < 0)
416 return status;
417 len -= status;
418 next += status;
419 }
420
421 len = next - buf;
422 c->wTotalLength = cpu_to_le16(len);
423 return len;
424 }
425
426 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
427 {
428 struct usb_gadget *gadget = cdev->gadget;
429 struct usb_configuration *c;
430 u8 type = w_value >> 8;
431 enum usb_device_speed speed = USB_SPEED_UNKNOWN;
432
433 if (gadget->speed == USB_SPEED_SUPER)
434 speed = gadget->speed;
435 else if (gadget_is_dualspeed(gadget)) {
436 int hs = 0;
437 if (gadget->speed == USB_SPEED_HIGH)
438 hs = 1;
439 if (type == USB_DT_OTHER_SPEED_CONFIG)
440 hs = !hs;
441 if (hs)
442 speed = USB_SPEED_HIGH;
443
444 }
445
446 /* This is a lookup by config *INDEX* */
447 w_value &= 0xff;
448 list_for_each_entry(c, &cdev->configs, list) {
449 /* ignore configs that won't work at this speed */
450 switch (speed) {
451 case USB_SPEED_SUPER:
452 if (!c->superspeed)
453 continue;
454 break;
455 case USB_SPEED_HIGH:
456 if (!c->highspeed)
457 continue;
458 break;
459 default:
460 if (!c->fullspeed)
461 continue;
462 }
463
464 if (w_value == 0)
465 return config_buf(c, speed, cdev->req->buf, type);
466 w_value--;
467 }
468 return -EINVAL;
469 }
470
471 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
472 {
473 struct usb_gadget *gadget = cdev->gadget;
474 struct usb_configuration *c;
475 unsigned count = 0;
476 int hs = 0;
477 int ss = 0;
478
479 if (gadget_is_dualspeed(gadget)) {
480 if (gadget->speed == USB_SPEED_HIGH)
481 hs = 1;
482 if (gadget->speed == USB_SPEED_SUPER)
483 ss = 1;
484 if (type == USB_DT_DEVICE_QUALIFIER)
485 hs = !hs;
486 }
487 list_for_each_entry(c, &cdev->configs, list) {
488 /* ignore configs that won't work at this speed */
489 if (ss) {
490 if (!c->superspeed)
491 continue;
492 } else if (hs) {
493 if (!c->highspeed)
494 continue;
495 } else {
496 if (!c->fullspeed)
497 continue;
498 }
499 count++;
500 }
501 return count;
502 }
503
504 /**
505 * bos_desc() - prepares the BOS descriptor.
506 * @cdev: pointer to usb_composite device to generate the bos
507 * descriptor for
508 *
509 * This function generates the BOS (Binary Device Object)
510 * descriptor and its device capabilities descriptors. The BOS
511 * descriptor should be supported by a SuperSpeed device.
512 */
513 static int bos_desc(struct usb_composite_dev *cdev)
514 {
515 struct usb_ext_cap_descriptor *usb_ext;
516 struct usb_ss_cap_descriptor *ss_cap;
517 struct usb_dcd_config_params dcd_config_params;
518 struct usb_bos_descriptor *bos = cdev->req->buf;
519
520 bos->bLength = USB_DT_BOS_SIZE;
521 bos->bDescriptorType = USB_DT_BOS;
522
523 bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
524 bos->bNumDeviceCaps = 0;
525
526 /*
527 * A SuperSpeed device shall include the USB2.0 extension descriptor
528 * and shall support LPM when operating in USB2.0 HS mode.
529 */
530 usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
531 bos->bNumDeviceCaps++;
532 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
533 usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
534 usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
535 usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
536 usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
537
538 /*
539 * The Superspeed USB Capability descriptor shall be implemented by all
540 * SuperSpeed devices.
541 */
542 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
543 bos->bNumDeviceCaps++;
544 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
545 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
546 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
547 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
548 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
549 ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
550 USB_FULL_SPEED_OPERATION |
551 USB_HIGH_SPEED_OPERATION |
552 USB_5GBPS_OPERATION);
553 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
554
555 /* Get Controller configuration */
556 if (cdev->gadget->ops->get_config_params)
557 cdev->gadget->ops->get_config_params(&dcd_config_params);
558 else {
559 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
560 dcd_config_params.bU2DevExitLat =
561 cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
562 }
563 ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
564 ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
565
566 return le16_to_cpu(bos->wTotalLength);
567 }
568
569 static void device_qual(struct usb_composite_dev *cdev)
570 {
571 struct usb_qualifier_descriptor *qual = cdev->req->buf;
572
573 qual->bLength = sizeof(*qual);
574 qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
575 /* POLICY: same bcdUSB and device type info at both speeds */
576 qual->bcdUSB = cdev->desc.bcdUSB;
577 qual->bDeviceClass = cdev->desc.bDeviceClass;
578 qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
579 qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
580 /* ASSUME same EP0 fifo size at both speeds */
581 qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
582 qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
583 qual->bRESERVED = 0;
584 }
585
586 /*-------------------------------------------------------------------------*/
587
588 static void reset_config(struct usb_composite_dev *cdev)
589 {
590 struct usb_function *f;
591
592 DBG(cdev, "reset config\n");
593
594 list_for_each_entry(f, &cdev->config->functions, list) {
595 if (f->disable)
596 f->disable(f);
597
598 bitmap_zero(f->endpoints, 32);
599 }
600 cdev->config = NULL;
601 cdev->delayed_status = 0;
602 }
603
604 static int set_config(struct usb_composite_dev *cdev,
605 const struct usb_ctrlrequest *ctrl, unsigned number)
606 {
607 struct usb_gadget *gadget = cdev->gadget;
608 struct usb_configuration *c = NULL;
609 int result = -EINVAL;
610 unsigned power = gadget_is_otg(gadget) ? 8 : 100;
611 int tmp;
612
613 if (number) {
614 list_for_each_entry(c, &cdev->configs, list) {
615 if (c->bConfigurationValue == number) {
616 /*
617 * We disable the FDs of the previous
618 * configuration only if the new configuration
619 * is a valid one
620 */
621 if (cdev->config)
622 reset_config(cdev);
623 result = 0;
624 break;
625 }
626 }
627 if (result < 0)
628 goto done;
629 } else { /* Zero configuration value - need to reset the config */
630 if (cdev->config)
631 reset_config(cdev);
632 result = 0;
633 }
634
635 INFO(cdev, "%s config #%d: %s\n",
636 usb_speed_string(gadget->speed),
637 number, c ? c->label : "unconfigured");
638
639 if (!c)
640 goto done;
641
642 cdev->config = c;
643
644 /* Initialize all interfaces by setting them to altsetting zero. */
645 for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
646 struct usb_function *f = c->interface[tmp];
647 struct usb_descriptor_header **descriptors;
648
649 if (!f)
650 break;
651
652 /*
653 * Record which endpoints are used by the function. This is used
654 * to dispatch control requests targeted at that endpoint to the
655 * function's setup callback instead of the current
656 * configuration's setup callback.
657 */
658 switch (gadget->speed) {
659 case USB_SPEED_SUPER:
660 descriptors = f->ss_descriptors;
661 break;
662 case USB_SPEED_HIGH:
663 descriptors = f->hs_descriptors;
664 break;
665 default:
666 descriptors = f->fs_descriptors;
667 }
668
669 for (; *descriptors; ++descriptors) {
670 struct usb_endpoint_descriptor *ep;
671 int addr;
672
673 if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
674 continue;
675
676 ep = (struct usb_endpoint_descriptor *)*descriptors;
677 addr = ((ep->bEndpointAddress & 0x80) >> 3)
678 | (ep->bEndpointAddress & 0x0f);
679 set_bit(addr, f->endpoints);
680 }
681
682 result = f->set_alt(f, tmp, 0);
683 if (result < 0) {
684 DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
685 tmp, f->name, f, result);
686
687 reset_config(cdev);
688 goto done;
689 }
690
691 if (result == USB_GADGET_DELAYED_STATUS) {
692 DBG(cdev,
693 "%s: interface %d (%s) requested delayed status\n",
694 __func__, tmp, f->name);
695 cdev->delayed_status++;
696 DBG(cdev, "delayed_status count %d\n",
697 cdev->delayed_status);
698 }
699 }
700
701 /* when we return, be sure our power usage is valid */
702 power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
703 done:
704 usb_gadget_vbus_draw(gadget, power);
705 if (result >= 0 && cdev->delayed_status)
706 result = USB_GADGET_DELAYED_STATUS;
707 return result;
708 }
709
710 int usb_add_config_only(struct usb_composite_dev *cdev,
711 struct usb_configuration *config)
712 {
713 struct usb_configuration *c;
714
715 if (!config->bConfigurationValue)
716 return -EINVAL;
717
718 /* Prevent duplicate configuration identifiers */
719 list_for_each_entry(c, &cdev->configs, list) {
720 if (c->bConfigurationValue == config->bConfigurationValue)
721 return -EBUSY;
722 }
723
724 config->cdev = cdev;
725 list_add_tail(&config->list, &cdev->configs);
726
727 INIT_LIST_HEAD(&config->functions);
728 config->next_interface_id = 0;
729 memset(config->interface, 0, sizeof(config->interface));
730
731 return 0;
732 }
733 EXPORT_SYMBOL_GPL(usb_add_config_only);
734
735 /**
736 * usb_add_config() - add a configuration to a device.
737 * @cdev: wraps the USB gadget
738 * @config: the configuration, with bConfigurationValue assigned
739 * @bind: the configuration's bind function
740 * Context: single threaded during gadget setup
741 *
742 * One of the main tasks of a composite @bind() routine is to
743 * add each of the configurations it supports, using this routine.
744 *
745 * This function returns the value of the configuration's @bind(), which
746 * is zero for success else a negative errno value. Binding configurations
747 * assigns global resources including string IDs, and per-configuration
748 * resources such as interface IDs and endpoints.
749 */
750 int usb_add_config(struct usb_composite_dev *cdev,
751 struct usb_configuration *config,
752 int (*bind)(struct usb_configuration *))
753 {
754 int status = -EINVAL;
755
756 if (!bind)
757 goto done;
758
759 DBG(cdev, "adding config #%u '%s'/%p\n",
760 config->bConfigurationValue,
761 config->label, config);
762
763 status = usb_add_config_only(cdev, config);
764 if (status)
765 goto done;
766
767 status = bind(config);
768 if (status < 0) {
769 while (!list_empty(&config->functions)) {
770 struct usb_function *f;
771
772 f = list_first_entry(&config->functions,
773 struct usb_function, list);
774 list_del(&f->list);
775 if (f->unbind) {
776 DBG(cdev, "unbind function '%s'/%p\n",
777 f->name, f);
778 f->unbind(config, f);
779 /* may free memory for "f" */
780 }
781 }
782 list_del(&config->list);
783 config->cdev = NULL;
784 } else {
785 unsigned i;
786
787 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
788 config->bConfigurationValue, config,
789 config->superspeed ? " super" : "",
790 config->highspeed ? " high" : "",
791 config->fullspeed
792 ? (gadget_is_dualspeed(cdev->gadget)
793 ? " full"
794 : " full/low")
795 : "");
796
797 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
798 struct usb_function *f = config->interface[i];
799
800 if (!f)
801 continue;
802 DBG(cdev, " interface %d = %s/%p\n",
803 i, f->name, f);
804 }
805 }
806
807 /* set_alt(), or next bind(), sets up
808 * ep->driver_data as needed.
809 */
810 usb_ep_autoconfig_reset(cdev->gadget);
811
812 done:
813 if (status)
814 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
815 config->bConfigurationValue, status);
816 return status;
817 }
818 EXPORT_SYMBOL_GPL(usb_add_config);
819
820 static void remove_config(struct usb_composite_dev *cdev,
821 struct usb_configuration *config)
822 {
823 while (!list_empty(&config->functions)) {
824 struct usb_function *f;
825
826 f = list_first_entry(&config->functions,
827 struct usb_function, list);
828 list_del(&f->list);
829 if (f->unbind) {
830 DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
831 f->unbind(config, f);
832 /* may free memory for "f" */
833 }
834 }
835 list_del(&config->list);
836 if (config->unbind) {
837 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
838 config->unbind(config);
839 /* may free memory for "c" */
840 }
841 }
842
843 /**
844 * usb_remove_config() - remove a configuration from a device.
845 * @cdev: wraps the USB gadget
846 * @config: the configuration
847 *
848 * Drivers must call usb_gadget_disconnect before calling this function
849 * to disconnect the device from the host and make sure the host will not
850 * try to enumerate the device while we are changing the config list.
851 */
852 void usb_remove_config(struct usb_composite_dev *cdev,
853 struct usb_configuration *config)
854 {
855 unsigned long flags;
856
857 spin_lock_irqsave(&cdev->lock, flags);
858
859 if (cdev->config == config)
860 reset_config(cdev);
861
862 spin_unlock_irqrestore(&cdev->lock, flags);
863
864 remove_config(cdev, config);
865 }
866
867 /*-------------------------------------------------------------------------*/
868
869 /* We support strings in multiple languages ... string descriptor zero
870 * says which languages are supported. The typical case will be that
871 * only one language (probably English) is used, with I18N handled on
872 * the host side.
873 */
874
875 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
876 {
877 const struct usb_gadget_strings *s;
878 __le16 language;
879 __le16 *tmp;
880
881 while (*sp) {
882 s = *sp;
883 language = cpu_to_le16(s->language);
884 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
885 if (*tmp == language)
886 goto repeat;
887 }
888 *tmp++ = language;
889 repeat:
890 sp++;
891 }
892 }
893
894 static int lookup_string(
895 struct usb_gadget_strings **sp,
896 void *buf,
897 u16 language,
898 int id
899 )
900 {
901 struct usb_gadget_strings *s;
902 int value;
903
904 while (*sp) {
905 s = *sp++;
906 if (s->language != language)
907 continue;
908 value = usb_gadget_get_string(s, id, buf);
909 if (value > 0)
910 return value;
911 }
912 return -EINVAL;
913 }
914
915 static int get_string(struct usb_composite_dev *cdev,
916 void *buf, u16 language, int id)
917 {
918 struct usb_composite_driver *composite = cdev->driver;
919 struct usb_gadget_string_container *uc;
920 struct usb_configuration *c;
921 struct usb_function *f;
922 int len;
923
924 /* Yes, not only is USB's I18N support probably more than most
925 * folk will ever care about ... also, it's all supported here.
926 * (Except for UTF8 support for Unicode's "Astral Planes".)
927 */
928
929 /* 0 == report all available language codes */
930 if (id == 0) {
931 struct usb_string_descriptor *s = buf;
932 struct usb_gadget_strings **sp;
933
934 memset(s, 0, 256);
935 s->bDescriptorType = USB_DT_STRING;
936
937 sp = composite->strings;
938 if (sp)
939 collect_langs(sp, s->wData);
940
941 list_for_each_entry(c, &cdev->configs, list) {
942 sp = c->strings;
943 if (sp)
944 collect_langs(sp, s->wData);
945
946 list_for_each_entry(f, &c->functions, list) {
947 sp = f->strings;
948 if (sp)
949 collect_langs(sp, s->wData);
950 }
951 }
952 list_for_each_entry(uc, &cdev->gstrings, list) {
953 struct usb_gadget_strings **sp;
954
955 sp = get_containers_gs(uc);
956 collect_langs(sp, s->wData);
957 }
958
959 for (len = 0; len <= 126 && s->wData[len]; len++)
960 continue;
961 if (!len)
962 return -EINVAL;
963
964 s->bLength = 2 * (len + 1);
965 return s->bLength;
966 }
967
968 list_for_each_entry(uc, &cdev->gstrings, list) {
969 struct usb_gadget_strings **sp;
970
971 sp = get_containers_gs(uc);
972 len = lookup_string(sp, buf, language, id);
973 if (len > 0)
974 return len;
975 }
976
977 /* String IDs are device-scoped, so we look up each string
978 * table we're told about. These lookups are infrequent;
979 * simpler-is-better here.
980 */
981 if (composite->strings) {
982 len = lookup_string(composite->strings, buf, language, id);
983 if (len > 0)
984 return len;
985 }
986 list_for_each_entry(c, &cdev->configs, list) {
987 if (c->strings) {
988 len = lookup_string(c->strings, buf, language, id);
989 if (len > 0)
990 return len;
991 }
992 list_for_each_entry(f, &c->functions, list) {
993 if (!f->strings)
994 continue;
995 len = lookup_string(f->strings, buf, language, id);
996 if (len > 0)
997 return len;
998 }
999 }
1000 return -EINVAL;
1001 }
1002
1003 /**
1004 * usb_string_id() - allocate an unused string ID
1005 * @cdev: the device whose string descriptor IDs are being allocated
1006 * Context: single threaded during gadget setup
1007 *
1008 * @usb_string_id() is called from bind() callbacks to allocate
1009 * string IDs. Drivers for functions, configurations, or gadgets will
1010 * then store that ID in the appropriate descriptors and string table.
1011 *
1012 * All string identifier should be allocated using this,
1013 * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1014 * that for example different functions don't wrongly assign different
1015 * meanings to the same identifier.
1016 */
1017 int usb_string_id(struct usb_composite_dev *cdev)
1018 {
1019 if (cdev->next_string_id < 254) {
1020 /* string id 0 is reserved by USB spec for list of
1021 * supported languages */
1022 /* 255 reserved as well? -- mina86 */
1023 cdev->next_string_id++;
1024 return cdev->next_string_id;
1025 }
1026 return -ENODEV;
1027 }
1028 EXPORT_SYMBOL_GPL(usb_string_id);
1029
1030 /**
1031 * usb_string_ids() - allocate unused string IDs in batch
1032 * @cdev: the device whose string descriptor IDs are being allocated
1033 * @str: an array of usb_string objects to assign numbers to
1034 * Context: single threaded during gadget setup
1035 *
1036 * @usb_string_ids() is called from bind() callbacks to allocate
1037 * string IDs. Drivers for functions, configurations, or gadgets will
1038 * then copy IDs from the string table to the appropriate descriptors
1039 * and string table for other languages.
1040 *
1041 * All string identifier should be allocated using this,
1042 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1043 * example different functions don't wrongly assign different meanings
1044 * to the same identifier.
1045 */
1046 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1047 {
1048 int next = cdev->next_string_id;
1049
1050 for (; str->s; ++str) {
1051 if (unlikely(next >= 254))
1052 return -ENODEV;
1053 str->id = ++next;
1054 }
1055
1056 cdev->next_string_id = next;
1057
1058 return 0;
1059 }
1060 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1061
1062 static struct usb_gadget_string_container *copy_gadget_strings(
1063 struct usb_gadget_strings **sp, unsigned n_gstrings,
1064 unsigned n_strings)
1065 {
1066 struct usb_gadget_string_container *uc;
1067 struct usb_gadget_strings **gs_array;
1068 struct usb_gadget_strings *gs;
1069 struct usb_string *s;
1070 unsigned mem;
1071 unsigned n_gs;
1072 unsigned n_s;
1073 void *stash;
1074
1075 mem = sizeof(*uc);
1076 mem += sizeof(void *) * (n_gstrings + 1);
1077 mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1078 mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1079 uc = kmalloc(mem, GFP_KERNEL);
1080 if (!uc)
1081 return ERR_PTR(-ENOMEM);
1082 gs_array = get_containers_gs(uc);
1083 stash = uc->stash;
1084 stash += sizeof(void *) * (n_gstrings + 1);
1085 for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1086 struct usb_string *org_s;
1087
1088 gs_array[n_gs] = stash;
1089 gs = gs_array[n_gs];
1090 stash += sizeof(struct usb_gadget_strings);
1091 gs->language = sp[n_gs]->language;
1092 gs->strings = stash;
1093 org_s = sp[n_gs]->strings;
1094
1095 for (n_s = 0; n_s < n_strings; n_s++) {
1096 s = stash;
1097 stash += sizeof(struct usb_string);
1098 if (org_s->s)
1099 s->s = org_s->s;
1100 else
1101 s->s = "";
1102 org_s++;
1103 }
1104 s = stash;
1105 s->s = NULL;
1106 stash += sizeof(struct usb_string);
1107
1108 }
1109 gs_array[n_gs] = NULL;
1110 return uc;
1111 }
1112
1113 /**
1114 * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1115 * @cdev: the device whose string descriptor IDs are being allocated
1116 * and attached.
1117 * @sp: an array of usb_gadget_strings to attach.
1118 * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1119 *
1120 * This function will create a deep copy of usb_gadget_strings and usb_string
1121 * and attach it to the cdev. The actual string (usb_string.s) will not be
1122 * copied but only a referenced will be made. The struct usb_gadget_strings
1123 * array may contain multiple languges and should be NULL terminated.
1124 * The ->language pointer of each struct usb_gadget_strings has to contain the
1125 * same amount of entries.
1126 * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1127 * usb_string entry of es-ES containts the translation of the first usb_string
1128 * entry of en-US. Therefore both entries become the same id assign.
1129 */
1130 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1131 struct usb_gadget_strings **sp, unsigned n_strings)
1132 {
1133 struct usb_gadget_string_container *uc;
1134 struct usb_gadget_strings **n_gs;
1135 unsigned n_gstrings = 0;
1136 unsigned i;
1137 int ret;
1138
1139 for (i = 0; sp[i]; i++)
1140 n_gstrings++;
1141
1142 if (!n_gstrings)
1143 return ERR_PTR(-EINVAL);
1144
1145 uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1146 if (IS_ERR(uc))
1147 return ERR_PTR(PTR_ERR(uc));
1148
1149 n_gs = get_containers_gs(uc);
1150 ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1151 if (ret)
1152 goto err;
1153
1154 for (i = 1; i < n_gstrings; i++) {
1155 struct usb_string *m_s;
1156 struct usb_string *s;
1157 unsigned n;
1158
1159 m_s = n_gs[0]->strings;
1160 s = n_gs[i]->strings;
1161 for (n = 0; n < n_strings; n++) {
1162 s->id = m_s->id;
1163 s++;
1164 m_s++;
1165 }
1166 }
1167 list_add_tail(&uc->list, &cdev->gstrings);
1168 return n_gs[0]->strings;
1169 err:
1170 kfree(uc);
1171 return ERR_PTR(ret);
1172 }
1173 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1174
1175 /**
1176 * usb_string_ids_n() - allocate unused string IDs in batch
1177 * @c: the device whose string descriptor IDs are being allocated
1178 * @n: number of string IDs to allocate
1179 * Context: single threaded during gadget setup
1180 *
1181 * Returns the first requested ID. This ID and next @n-1 IDs are now
1182 * valid IDs. At least provided that @n is non-zero because if it
1183 * is, returns last requested ID which is now very useful information.
1184 *
1185 * @usb_string_ids_n() is called from bind() callbacks to allocate
1186 * string IDs. Drivers for functions, configurations, or gadgets will
1187 * then store that ID in the appropriate descriptors and string table.
1188 *
1189 * All string identifier should be allocated using this,
1190 * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1191 * example different functions don't wrongly assign different meanings
1192 * to the same identifier.
1193 */
1194 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1195 {
1196 unsigned next = c->next_string_id;
1197 if (unlikely(n > 254 || (unsigned)next + n > 254))
1198 return -ENODEV;
1199 c->next_string_id += n;
1200 return next + 1;
1201 }
1202 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1203
1204 /*-------------------------------------------------------------------------*/
1205
1206 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1207 {
1208 if (req->status || req->actual != req->length)
1209 DBG((struct usb_composite_dev *) ep->driver_data,
1210 "setup complete --> %d, %d/%d\n",
1211 req->status, req->actual, req->length);
1212 }
1213
1214 /*
1215 * The setup() callback implements all the ep0 functionality that's
1216 * not handled lower down, in hardware or the hardware driver(like
1217 * device and endpoint feature flags, and their status). It's all
1218 * housekeeping for the gadget function we're implementing. Most of
1219 * the work is in config and function specific setup.
1220 */
1221 int
1222 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1223 {
1224 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1225 struct usb_request *req = cdev->req;
1226 int value = -EOPNOTSUPP;
1227 int status = 0;
1228 u16 w_index = le16_to_cpu(ctrl->wIndex);
1229 u8 intf = w_index & 0xFF;
1230 u16 w_value = le16_to_cpu(ctrl->wValue);
1231 u16 w_length = le16_to_cpu(ctrl->wLength);
1232 struct usb_function *f = NULL;
1233 u8 endp;
1234
1235 /* partial re-init of the response message; the function or the
1236 * gadget might need to intercept e.g. a control-OUT completion
1237 * when we delegate to it.
1238 */
1239 req->zero = 0;
1240 req->complete = composite_setup_complete;
1241 req->length = 0;
1242 gadget->ep0->driver_data = cdev;
1243
1244 switch (ctrl->bRequest) {
1245
1246 /* we handle all standard USB descriptors */
1247 case USB_REQ_GET_DESCRIPTOR:
1248 if (ctrl->bRequestType != USB_DIR_IN)
1249 goto unknown;
1250 switch (w_value >> 8) {
1251
1252 case USB_DT_DEVICE:
1253 cdev->desc.bNumConfigurations =
1254 count_configs(cdev, USB_DT_DEVICE);
1255 cdev->desc.bMaxPacketSize0 =
1256 cdev->gadget->ep0->maxpacket;
1257 if (gadget_is_superspeed(gadget)) {
1258 if (gadget->speed >= USB_SPEED_SUPER) {
1259 cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1260 cdev->desc.bMaxPacketSize0 = 9;
1261 } else {
1262 cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1263 }
1264 }
1265
1266 value = min(w_length, (u16) sizeof cdev->desc);
1267 memcpy(req->buf, &cdev->desc, value);
1268 break;
1269 case USB_DT_DEVICE_QUALIFIER:
1270 if (!gadget_is_dualspeed(gadget) ||
1271 gadget->speed >= USB_SPEED_SUPER)
1272 break;
1273 device_qual(cdev);
1274 value = min_t(int, w_length,
1275 sizeof(struct usb_qualifier_descriptor));
1276 break;
1277 case USB_DT_OTHER_SPEED_CONFIG:
1278 if (!gadget_is_dualspeed(gadget) ||
1279 gadget->speed >= USB_SPEED_SUPER)
1280 break;
1281 /* FALLTHROUGH */
1282 case USB_DT_CONFIG:
1283 value = config_desc(cdev, w_value);
1284 if (value >= 0)
1285 value = min(w_length, (u16) value);
1286 break;
1287 case USB_DT_STRING:
1288 value = get_string(cdev, req->buf,
1289 w_index, w_value & 0xff);
1290 if (value >= 0)
1291 value = min(w_length, (u16) value);
1292 break;
1293 case USB_DT_BOS:
1294 if (gadget_is_superspeed(gadget)) {
1295 value = bos_desc(cdev);
1296 value = min(w_length, (u16) value);
1297 }
1298 break;
1299 }
1300 break;
1301
1302 /* any number of configs can work */
1303 case USB_REQ_SET_CONFIGURATION:
1304 if (ctrl->bRequestType != 0)
1305 goto unknown;
1306 if (gadget_is_otg(gadget)) {
1307 if (gadget->a_hnp_support)
1308 DBG(cdev, "HNP available\n");
1309 else if (gadget->a_alt_hnp_support)
1310 DBG(cdev, "HNP on another port\n");
1311 else
1312 VDBG(cdev, "HNP inactive\n");
1313 }
1314 spin_lock(&cdev->lock);
1315 value = set_config(cdev, ctrl, w_value);
1316 spin_unlock(&cdev->lock);
1317 break;
1318 case USB_REQ_GET_CONFIGURATION:
1319 if (ctrl->bRequestType != USB_DIR_IN)
1320 goto unknown;
1321 if (cdev->config)
1322 *(u8 *)req->buf = cdev->config->bConfigurationValue;
1323 else
1324 *(u8 *)req->buf = 0;
1325 value = min(w_length, (u16) 1);
1326 break;
1327
1328 /* function drivers must handle get/set altsetting */
1329 case USB_REQ_SET_INTERFACE:
1330 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1331 goto unknown;
1332 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1333 break;
1334 f = cdev->config->interface[intf];
1335 if (!f)
1336 break;
1337
1338 /*
1339 * If there's no get_alt() method, we know only altsetting zero
1340 * works. There is no need to check if set_alt() is not NULL
1341 * as we check this in usb_add_function().
1342 */
1343 if (w_value && !f->get_alt)
1344 break;
1345 value = f->set_alt(f, w_index, w_value);
1346 if (value == USB_GADGET_DELAYED_STATUS) {
1347 DBG(cdev,
1348 "%s: interface %d (%s) requested delayed status\n",
1349 __func__, intf, f->name);
1350 cdev->delayed_status++;
1351 DBG(cdev, "delayed_status count %d\n",
1352 cdev->delayed_status);
1353 }
1354 break;
1355 case USB_REQ_GET_INTERFACE:
1356 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1357 goto unknown;
1358 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1359 break;
1360 f = cdev->config->interface[intf];
1361 if (!f)
1362 break;
1363 /* lots of interfaces only need altsetting zero... */
1364 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1365 if (value < 0)
1366 break;
1367 *((u8 *)req->buf) = value;
1368 value = min(w_length, (u16) 1);
1369 break;
1370
1371 /*
1372 * USB 3.0 additions:
1373 * Function driver should handle get_status request. If such cb
1374 * wasn't supplied we respond with default value = 0
1375 * Note: function driver should supply such cb only for the first
1376 * interface of the function
1377 */
1378 case USB_REQ_GET_STATUS:
1379 if (!gadget_is_superspeed(gadget))
1380 goto unknown;
1381 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1382 goto unknown;
1383 value = 2; /* This is the length of the get_status reply */
1384 put_unaligned_le16(0, req->buf);
1385 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1386 break;
1387 f = cdev->config->interface[intf];
1388 if (!f)
1389 break;
1390 status = f->get_status ? f->get_status(f) : 0;
1391 if (status < 0)
1392 break;
1393 put_unaligned_le16(status & 0x0000ffff, req->buf);
1394 break;
1395 /*
1396 * Function drivers should handle SetFeature/ClearFeature
1397 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1398 * only for the first interface of the function
1399 */
1400 case USB_REQ_CLEAR_FEATURE:
1401 case USB_REQ_SET_FEATURE:
1402 if (!gadget_is_superspeed(gadget))
1403 goto unknown;
1404 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1405 goto unknown;
1406 switch (w_value) {
1407 case USB_INTRF_FUNC_SUSPEND:
1408 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1409 break;
1410 f = cdev->config->interface[intf];
1411 if (!f)
1412 break;
1413 value = 0;
1414 if (f->func_suspend)
1415 value = f->func_suspend(f, w_index >> 8);
1416 if (value < 0) {
1417 ERROR(cdev,
1418 "func_suspend() returned error %d\n",
1419 value);
1420 value = 0;
1421 }
1422 break;
1423 }
1424 break;
1425 default:
1426 unknown:
1427 VDBG(cdev,
1428 "non-core control req%02x.%02x v%04x i%04x l%d\n",
1429 ctrl->bRequestType, ctrl->bRequest,
1430 w_value, w_index, w_length);
1431
1432 /* functions always handle their interfaces and endpoints...
1433 * punt other recipients (other, WUSB, ...) to the current
1434 * configuration code.
1435 *
1436 * REVISIT it could make sense to let the composite device
1437 * take such requests too, if that's ever needed: to work
1438 * in config 0, etc.
1439 */
1440 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1441 case USB_RECIP_INTERFACE:
1442 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1443 break;
1444 f = cdev->config->interface[intf];
1445 break;
1446
1447 case USB_RECIP_ENDPOINT:
1448 endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1449 list_for_each_entry(f, &cdev->config->functions, list) {
1450 if (test_bit(endp, f->endpoints))
1451 break;
1452 }
1453 if (&f->list == &cdev->config->functions)
1454 f = NULL;
1455 break;
1456 }
1457
1458 if (f && f->setup)
1459 value = f->setup(f, ctrl);
1460 else {
1461 struct usb_configuration *c;
1462
1463 c = cdev->config;
1464 if (c && c->setup)
1465 value = c->setup(c, ctrl);
1466 }
1467
1468 goto done;
1469 }
1470
1471 /* respond with data transfer before status phase? */
1472 if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1473 req->length = value;
1474 req->zero = value < w_length;
1475 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1476 if (value < 0) {
1477 DBG(cdev, "ep_queue --> %d\n", value);
1478 req->status = 0;
1479 composite_setup_complete(gadget->ep0, req);
1480 }
1481 } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1482 WARN(cdev,
1483 "%s: Delayed status not supported for w_length != 0",
1484 __func__);
1485 }
1486
1487 done:
1488 /* device either stalls (value < 0) or reports success */
1489 return value;
1490 }
1491
1492 void composite_disconnect(struct usb_gadget *gadget)
1493 {
1494 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1495 unsigned long flags;
1496
1497 /* REVISIT: should we have config and device level
1498 * disconnect callbacks?
1499 */
1500 spin_lock_irqsave(&cdev->lock, flags);
1501 if (cdev->config)
1502 reset_config(cdev);
1503 if (cdev->driver->disconnect)
1504 cdev->driver->disconnect(cdev);
1505 spin_unlock_irqrestore(&cdev->lock, flags);
1506 }
1507
1508 /*-------------------------------------------------------------------------*/
1509
1510 static ssize_t composite_show_suspended(struct device *dev,
1511 struct device_attribute *attr,
1512 char *buf)
1513 {
1514 struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1515 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1516
1517 return sprintf(buf, "%d\n", cdev->suspended);
1518 }
1519
1520 static DEVICE_ATTR(suspended, 0444, composite_show_suspended, NULL);
1521
1522 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1523 {
1524 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1525
1526 /* composite_disconnect() must already have been called
1527 * by the underlying peripheral controller driver!
1528 * so there's no i/o concurrency that could affect the
1529 * state protected by cdev->lock.
1530 */
1531 WARN_ON(cdev->config);
1532
1533 while (!list_empty(&cdev->configs)) {
1534 struct usb_configuration *c;
1535 c = list_first_entry(&cdev->configs,
1536 struct usb_configuration, list);
1537 remove_config(cdev, c);
1538 }
1539 if (cdev->driver->unbind && unbind_driver)
1540 cdev->driver->unbind(cdev);
1541
1542 composite_dev_cleanup(cdev);
1543
1544 kfree(cdev->def_manufacturer);
1545 kfree(cdev);
1546 set_gadget_data(gadget, NULL);
1547 }
1548
1549 static void composite_unbind(struct usb_gadget *gadget)
1550 {
1551 __composite_unbind(gadget, true);
1552 }
1553
1554 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1555 const struct usb_device_descriptor *old)
1556 {
1557 __le16 idVendor;
1558 __le16 idProduct;
1559 __le16 bcdDevice;
1560 u8 iSerialNumber;
1561 u8 iManufacturer;
1562 u8 iProduct;
1563
1564 /*
1565 * these variables may have been set in
1566 * usb_composite_overwrite_options()
1567 */
1568 idVendor = new->idVendor;
1569 idProduct = new->idProduct;
1570 bcdDevice = new->bcdDevice;
1571 iSerialNumber = new->iSerialNumber;
1572 iManufacturer = new->iManufacturer;
1573 iProduct = new->iProduct;
1574
1575 *new = *old;
1576 if (idVendor)
1577 new->idVendor = idVendor;
1578 if (idProduct)
1579 new->idProduct = idProduct;
1580 if (bcdDevice)
1581 new->bcdDevice = bcdDevice;
1582 else
1583 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1584 if (iSerialNumber)
1585 new->iSerialNumber = iSerialNumber;
1586 if (iManufacturer)
1587 new->iManufacturer = iManufacturer;
1588 if (iProduct)
1589 new->iProduct = iProduct;
1590 }
1591
1592 int composite_dev_prepare(struct usb_composite_driver *composite,
1593 struct usb_composite_dev *cdev)
1594 {
1595 struct usb_gadget *gadget = cdev->gadget;
1596 int ret = -ENOMEM;
1597
1598 /* preallocate control response and buffer */
1599 cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1600 if (!cdev->req)
1601 return -ENOMEM;
1602
1603 cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
1604 if (!cdev->req->buf)
1605 goto fail;
1606
1607 ret = device_create_file(&gadget->dev, &dev_attr_suspended);
1608 if (ret)
1609 goto fail_dev;
1610
1611 cdev->req->complete = composite_setup_complete;
1612 gadget->ep0->driver_data = cdev;
1613
1614 cdev->driver = composite;
1615
1616 /*
1617 * As per USB compliance update, a device that is actively drawing
1618 * more than 100mA from USB must report itself as bus-powered in
1619 * the GetStatus(DEVICE) call.
1620 */
1621 if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
1622 usb_gadget_set_selfpowered(gadget);
1623
1624 /* interface and string IDs start at zero via kzalloc.
1625 * we force endpoints to start unassigned; few controller
1626 * drivers will zero ep->driver_data.
1627 */
1628 usb_ep_autoconfig_reset(gadget);
1629 return 0;
1630 fail_dev:
1631 kfree(cdev->req->buf);
1632 fail:
1633 usb_ep_free_request(gadget->ep0, cdev->req);
1634 cdev->req = NULL;
1635 return ret;
1636 }
1637
1638 void composite_dev_cleanup(struct usb_composite_dev *cdev)
1639 {
1640 struct usb_gadget_string_container *uc, *tmp;
1641
1642 list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
1643 list_del(&uc->list);
1644 kfree(uc);
1645 }
1646 if (cdev->req) {
1647 kfree(cdev->req->buf);
1648 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
1649 }
1650 cdev->next_string_id = 0;
1651 device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
1652 }
1653
1654 static int composite_bind(struct usb_gadget *gadget,
1655 struct usb_gadget_driver *gdriver)
1656 {
1657 struct usb_composite_dev *cdev;
1658 struct usb_composite_driver *composite = to_cdriver(gdriver);
1659 int status = -ENOMEM;
1660
1661 cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
1662 if (!cdev)
1663 return status;
1664
1665 spin_lock_init(&cdev->lock);
1666 cdev->gadget = gadget;
1667 set_gadget_data(gadget, cdev);
1668 INIT_LIST_HEAD(&cdev->configs);
1669 INIT_LIST_HEAD(&cdev->gstrings);
1670
1671 status = composite_dev_prepare(composite, cdev);
1672 if (status)
1673 goto fail;
1674
1675 /* composite gadget needs to assign strings for whole device (like
1676 * serial number), register function drivers, potentially update
1677 * power state and consumption, etc
1678 */
1679 status = composite->bind(cdev);
1680 if (status < 0)
1681 goto fail;
1682
1683 update_unchanged_dev_desc(&cdev->desc, composite->dev);
1684
1685 /* has userspace failed to provide a serial number? */
1686 if (composite->needs_serial && !cdev->desc.iSerialNumber)
1687 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
1688
1689 INFO(cdev, "%s ready\n", composite->name);
1690 return 0;
1691
1692 fail:
1693 __composite_unbind(gadget, false);
1694 return status;
1695 }
1696
1697 /*-------------------------------------------------------------------------*/
1698
1699 static void
1700 composite_suspend(struct usb_gadget *gadget)
1701 {
1702 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1703 struct usb_function *f;
1704
1705 /* REVISIT: should we have config level
1706 * suspend/resume callbacks?
1707 */
1708 DBG(cdev, "suspend\n");
1709 if (cdev->config) {
1710 list_for_each_entry(f, &cdev->config->functions, list) {
1711 if (f->suspend)
1712 f->suspend(f);
1713 }
1714 }
1715 if (cdev->driver->suspend)
1716 cdev->driver->suspend(cdev);
1717
1718 cdev->suspended = 1;
1719
1720 usb_gadget_vbus_draw(gadget, 2);
1721 }
1722
1723 static void
1724 composite_resume(struct usb_gadget *gadget)
1725 {
1726 struct usb_composite_dev *cdev = get_gadget_data(gadget);
1727 struct usb_function *f;
1728 u8 maxpower;
1729
1730 /* REVISIT: should we have config level
1731 * suspend/resume callbacks?
1732 */
1733 DBG(cdev, "resume\n");
1734 if (cdev->driver->resume)
1735 cdev->driver->resume(cdev);
1736 if (cdev->config) {
1737 list_for_each_entry(f, &cdev->config->functions, list) {
1738 if (f->resume)
1739 f->resume(f);
1740 }
1741
1742 maxpower = cdev->config->MaxPower;
1743
1744 usb_gadget_vbus_draw(gadget, maxpower ?
1745 maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
1746 }
1747
1748 cdev->suspended = 0;
1749 }
1750
1751 /*-------------------------------------------------------------------------*/
1752
1753 static const struct usb_gadget_driver composite_driver_template = {
1754 .bind = composite_bind,
1755 .unbind = composite_unbind,
1756
1757 .setup = composite_setup,
1758 .disconnect = composite_disconnect,
1759
1760 .suspend = composite_suspend,
1761 .resume = composite_resume,
1762
1763 .driver = {
1764 .owner = THIS_MODULE,
1765 },
1766 };
1767
1768 /**
1769 * usb_composite_probe() - register a composite driver
1770 * @driver: the driver to register
1771 *
1772 * Context: single threaded during gadget setup
1773 *
1774 * This function is used to register drivers using the composite driver
1775 * framework. The return value is zero, or a negative errno value.
1776 * Those values normally come from the driver's @bind method, which does
1777 * all the work of setting up the driver to match the hardware.
1778 *
1779 * On successful return, the gadget is ready to respond to requests from
1780 * the host, unless one of its components invokes usb_gadget_disconnect()
1781 * while it was binding. That would usually be done in order to wait for
1782 * some userspace participation.
1783 */
1784 int usb_composite_probe(struct usb_composite_driver *driver)
1785 {
1786 struct usb_gadget_driver *gadget_driver;
1787
1788 if (!driver || !driver->dev || !driver->bind)
1789 return -EINVAL;
1790
1791 if (!driver->name)
1792 driver->name = "composite";
1793
1794 driver->gadget_driver = composite_driver_template;
1795 gadget_driver = &driver->gadget_driver;
1796
1797 gadget_driver->function = (char *) driver->name;
1798 gadget_driver->driver.name = driver->name;
1799 gadget_driver->max_speed = driver->max_speed;
1800
1801 return usb_gadget_probe_driver(gadget_driver);
1802 }
1803 EXPORT_SYMBOL_GPL(usb_composite_probe);
1804
1805 /**
1806 * usb_composite_unregister() - unregister a composite driver
1807 * @driver: the driver to unregister
1808 *
1809 * This function is used to unregister drivers using the composite
1810 * driver framework.
1811 */
1812 void usb_composite_unregister(struct usb_composite_driver *driver)
1813 {
1814 usb_gadget_unregister_driver(&driver->gadget_driver);
1815 }
1816 EXPORT_SYMBOL_GPL(usb_composite_unregister);
1817
1818 /**
1819 * usb_composite_setup_continue() - Continue with the control transfer
1820 * @cdev: the composite device who's control transfer was kept waiting
1821 *
1822 * This function must be called by the USB function driver to continue
1823 * with the control transfer's data/status stage in case it had requested to
1824 * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
1825 * can request the composite framework to delay the setup request's data/status
1826 * stages by returning USB_GADGET_DELAYED_STATUS.
1827 */
1828 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
1829 {
1830 int value;
1831 struct usb_request *req = cdev->req;
1832 unsigned long flags;
1833
1834 DBG(cdev, "%s\n", __func__);
1835 spin_lock_irqsave(&cdev->lock, flags);
1836
1837 if (cdev->delayed_status == 0) {
1838 WARN(cdev, "%s: Unexpected call\n", __func__);
1839
1840 } else if (--cdev->delayed_status == 0) {
1841 DBG(cdev, "%s: Completing delayed status\n", __func__);
1842 req->length = 0;
1843 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1844 if (value < 0) {
1845 DBG(cdev, "ep_queue --> %d\n", value);
1846 req->status = 0;
1847 composite_setup_complete(cdev->gadget->ep0, req);
1848 }
1849 }
1850
1851 spin_unlock_irqrestore(&cdev->lock, flags);
1852 }
1853 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
1854
1855 static char *composite_default_mfr(struct usb_gadget *gadget)
1856 {
1857 char *mfr;
1858 int len;
1859
1860 len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
1861 init_utsname()->release, gadget->name);
1862 len++;
1863 mfr = kmalloc(len, GFP_KERNEL);
1864 if (!mfr)
1865 return NULL;
1866 snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
1867 init_utsname()->release, gadget->name);
1868 return mfr;
1869 }
1870
1871 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
1872 struct usb_composite_overwrite *covr)
1873 {
1874 struct usb_device_descriptor *desc = &cdev->desc;
1875 struct usb_gadget_strings *gstr = cdev->driver->strings[0];
1876 struct usb_string *dev_str = gstr->strings;
1877
1878 if (covr->idVendor)
1879 desc->idVendor = cpu_to_le16(covr->idVendor);
1880
1881 if (covr->idProduct)
1882 desc->idProduct = cpu_to_le16(covr->idProduct);
1883
1884 if (covr->bcdDevice)
1885 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
1886
1887 if (covr->serial_number) {
1888 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
1889 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
1890 }
1891 if (covr->manufacturer) {
1892 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
1893 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
1894
1895 } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
1896 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
1897 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
1898 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
1899 }
1900
1901 if (covr->product) {
1902 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
1903 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
1904 }
1905 }
1906 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
1907
1908 MODULE_LICENSE("GPL");
1909 MODULE_AUTHOR("David Brownell");