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