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