Merge branch 'linux-linaro-lsk-v4.4-android' of git://git.linaro.org/kernel/linux...
[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
1775                         if (value >= 0) {
1776                                 req->length = value;
1777                                 req->context = cdev;
1778                                 req->zero = value < w_length;
1779                                 value = composite_ep0_queue(cdev, req,
1780                                                             GFP_ATOMIC);
1781                                 if (value < 0) {
1782                                         DBG(cdev, "ep_queue --> %d\n", value);
1783                                         req->status = 0;
1784                                         composite_setup_complete(gadget->ep0,
1785                                                                  req);
1786                                 }
1787                         }
1788                         return value;
1789                 }
1790
1791                 VDBG(cdev,
1792                         "non-core control req%02x.%02x v%04x i%04x l%d\n",
1793                         ctrl->bRequestType, ctrl->bRequest,
1794                         w_value, w_index, w_length);
1795
1796                 /* functions always handle their interfaces and endpoints...
1797                  * punt other recipients (other, WUSB, ...) to the current
1798                  * configuration code.
1799                  *
1800                  * REVISIT it could make sense to let the composite device
1801                  * take such requests too, if that's ever needed:  to work
1802                  * in config 0, etc.
1803                  */
1804                 if (cdev->config) {
1805                         list_for_each_entry(f, &cdev->config->functions, list)
1806                                 if (f->req_match && f->req_match(f, ctrl))
1807                                         goto try_fun_setup;
1808                         f = NULL;
1809                 }
1810
1811                 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1812                 case USB_RECIP_INTERFACE:
1813                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1814                                 break;
1815                         f = cdev->config->interface[intf];
1816                         break;
1817
1818                 case USB_RECIP_ENDPOINT:
1819                         endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1820                         list_for_each_entry(f, &cdev->config->functions, list) {
1821                                 if (test_bit(endp, f->endpoints))
1822                                         break;
1823                         }
1824                         if (&f->list == &cdev->config->functions)
1825                                 f = NULL;
1826                         break;
1827                 }
1828 try_fun_setup:
1829                 if (f && f->setup)
1830                         value = f->setup(f, ctrl);
1831                 else {
1832                         struct usb_configuration        *c;
1833
1834                         c = cdev->config;
1835                         if (!c)
1836                                 goto done;
1837
1838                         /* try current config's setup */
1839                         if (c->setup) {
1840                                 value = c->setup(c, ctrl);
1841                                 goto done;
1842                         }
1843
1844                         /* try the only function in the current config */
1845                         if (!list_is_singular(&c->functions))
1846                                 goto done;
1847                         f = list_first_entry(&c->functions, struct usb_function,
1848                                              list);
1849                         if (f->setup)
1850                                 value = f->setup(f, ctrl);
1851                 }
1852
1853                 goto done;
1854         }
1855
1856         /* respond with data transfer before status phase? */
1857         if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1858                 req->length = value;
1859                 req->context = cdev;
1860                 req->zero = value < w_length;
1861                 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1862                 if (value < 0) {
1863                         DBG(cdev, "ep_queue --> %d\n", value);
1864                         req->status = 0;
1865                         composite_setup_complete(gadget->ep0, req);
1866                 }
1867         } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1868                 WARN(cdev,
1869                         "%s: Delayed status not supported for w_length != 0",
1870                         __func__);
1871         }
1872
1873 done:
1874         /* device either stalls (value < 0) or reports success */
1875         return value;
1876 }
1877
1878 void composite_disconnect(struct usb_gadget *gadget)
1879 {
1880         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1881         unsigned long                   flags;
1882
1883         if (cdev == NULL) {
1884                 WARN(1, "%s: Calling disconnect on a Gadget that is \
1885                          not connected\n", __func__);
1886                 return;
1887         }
1888
1889         /* REVISIT:  should we have config and device level
1890          * disconnect callbacks?
1891          */
1892         spin_lock_irqsave(&cdev->lock, flags);
1893         if (cdev->config)
1894                 reset_config(cdev);
1895         if (cdev->driver->disconnect)
1896                 cdev->driver->disconnect(cdev);
1897         spin_unlock_irqrestore(&cdev->lock, flags);
1898 }
1899
1900 /*-------------------------------------------------------------------------*/
1901
1902 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
1903                               char *buf)
1904 {
1905         struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1906         struct usb_composite_dev *cdev = get_gadget_data(gadget);
1907
1908         return sprintf(buf, "%d\n", cdev->suspended);
1909 }
1910 static DEVICE_ATTR_RO(suspended);
1911
1912 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1913 {
1914         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1915
1916         /* composite_disconnect() must already have been called
1917          * by the underlying peripheral controller driver!
1918          * so there's no i/o concurrency that could affect the
1919          * state protected by cdev->lock.
1920          */
1921         WARN_ON(cdev->config);
1922
1923         while (!list_empty(&cdev->configs)) {
1924                 struct usb_configuration        *c;
1925                 c = list_first_entry(&cdev->configs,
1926                                 struct usb_configuration, list);
1927                 remove_config(cdev, c);
1928         }
1929         if (cdev->driver->unbind && unbind_driver)
1930                 cdev->driver->unbind(cdev);
1931
1932         composite_dev_cleanup(cdev);
1933
1934         kfree(cdev->def_manufacturer);
1935         kfree(cdev);
1936         set_gadget_data(gadget, NULL);
1937 }
1938
1939 static void composite_unbind(struct usb_gadget *gadget)
1940 {
1941         __composite_unbind(gadget, true);
1942 }
1943
1944 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1945                 const struct usb_device_descriptor *old)
1946 {
1947         __le16 idVendor;
1948         __le16 idProduct;
1949         __le16 bcdDevice;
1950         u8 iSerialNumber;
1951         u8 iManufacturer;
1952         u8 iProduct;
1953
1954         /*
1955          * these variables may have been set in
1956          * usb_composite_overwrite_options()
1957          */
1958         idVendor = new->idVendor;
1959         idProduct = new->idProduct;
1960         bcdDevice = new->bcdDevice;
1961         iSerialNumber = new->iSerialNumber;
1962         iManufacturer = new->iManufacturer;
1963         iProduct = new->iProduct;
1964
1965         *new = *old;
1966         if (idVendor)
1967                 new->idVendor = idVendor;
1968         if (idProduct)
1969                 new->idProduct = idProduct;
1970         if (bcdDevice)
1971                 new->bcdDevice = bcdDevice;
1972         else
1973                 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1974         if (iSerialNumber)
1975                 new->iSerialNumber = iSerialNumber;
1976         if (iManufacturer)
1977                 new->iManufacturer = iManufacturer;
1978         if (iProduct)
1979                 new->iProduct = iProduct;
1980 }
1981
1982 int composite_dev_prepare(struct usb_composite_driver *composite,
1983                 struct usb_composite_dev *cdev)
1984 {
1985         struct usb_gadget *gadget = cdev->gadget;
1986         int ret = -ENOMEM;
1987
1988         /* preallocate control response and buffer */
1989         cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1990         if (!cdev->req)
1991                 return -ENOMEM;
1992
1993         cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
1994         if (!cdev->req->buf)
1995                 goto fail;
1996
1997         ret = device_create_file(&gadget->dev, &dev_attr_suspended);
1998         if (ret)
1999                 goto fail_dev;
2000
2001         cdev->req->complete = composite_setup_complete;
2002         cdev->req->context = cdev;
2003         gadget->ep0->driver_data = cdev;
2004
2005         cdev->driver = composite;
2006
2007         /*
2008          * As per USB compliance update, a device that is actively drawing
2009          * more than 100mA from USB must report itself as bus-powered in
2010          * the GetStatus(DEVICE) call.
2011          */
2012         if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2013                 usb_gadget_set_selfpowered(gadget);
2014
2015         /* interface and string IDs start at zero via kzalloc.
2016          * we force endpoints to start unassigned; few controller
2017          * drivers will zero ep->driver_data.
2018          */
2019         usb_ep_autoconfig_reset(gadget);
2020         return 0;
2021 fail_dev:
2022         kfree(cdev->req->buf);
2023 fail:
2024         usb_ep_free_request(gadget->ep0, cdev->req);
2025         cdev->req = NULL;
2026         return ret;
2027 }
2028
2029 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2030                                   struct usb_ep *ep0)
2031 {
2032         int ret = 0;
2033
2034         cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2035         if (!cdev->os_desc_req) {
2036                 ret = PTR_ERR(cdev->os_desc_req);
2037                 goto end;
2038         }
2039
2040         /* OS feature descriptor length <= 4kB */
2041         cdev->os_desc_req->buf = kmalloc(4096, GFP_KERNEL);
2042         if (!cdev->os_desc_req->buf) {
2043                 ret = PTR_ERR(cdev->os_desc_req->buf);
2044                 kfree(cdev->os_desc_req);
2045                 goto end;
2046         }
2047         cdev->os_desc_req->context = cdev;
2048         cdev->os_desc_req->complete = composite_setup_complete;
2049 end:
2050         return ret;
2051 }
2052
2053 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2054 {
2055         struct usb_gadget_string_container *uc, *tmp;
2056
2057         list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2058                 list_del(&uc->list);
2059                 kfree(uc);
2060         }
2061         if (cdev->os_desc_req) {
2062                 if (cdev->os_desc_pending)
2063                         usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2064
2065                 kfree(cdev->os_desc_req->buf);
2066                 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2067                 cdev->os_desc_req = NULL;
2068         }
2069         if (cdev->req) {
2070                 if (cdev->setup_pending)
2071                         usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2072
2073                 kfree(cdev->req->buf);
2074                 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2075                 cdev->req = NULL;
2076         }
2077         cdev->next_string_id = 0;
2078         device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2079 }
2080
2081 static int composite_bind(struct usb_gadget *gadget,
2082                 struct usb_gadget_driver *gdriver)
2083 {
2084         struct usb_composite_dev        *cdev;
2085         struct usb_composite_driver     *composite = to_cdriver(gdriver);
2086         int                             status = -ENOMEM;
2087
2088         cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2089         if (!cdev)
2090                 return status;
2091
2092         spin_lock_init(&cdev->lock);
2093         cdev->gadget = gadget;
2094         set_gadget_data(gadget, cdev);
2095         INIT_LIST_HEAD(&cdev->configs);
2096         INIT_LIST_HEAD(&cdev->gstrings);
2097
2098         status = composite_dev_prepare(composite, cdev);
2099         if (status)
2100                 goto fail;
2101
2102         /* composite gadget needs to assign strings for whole device (like
2103          * serial number), register function drivers, potentially update
2104          * power state and consumption, etc
2105          */
2106         status = composite->bind(cdev);
2107         if (status < 0)
2108                 goto fail;
2109
2110         if (cdev->use_os_string) {
2111                 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2112                 if (status)
2113                         goto fail;
2114         }
2115
2116         update_unchanged_dev_desc(&cdev->desc, composite->dev);
2117
2118         /* has userspace failed to provide a serial number? */
2119         if (composite->needs_serial && !cdev->desc.iSerialNumber)
2120                 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2121
2122         INFO(cdev, "%s ready\n", composite->name);
2123         return 0;
2124
2125 fail:
2126         __composite_unbind(gadget, false);
2127         return status;
2128 }
2129
2130 /*-------------------------------------------------------------------------*/
2131
2132 void composite_suspend(struct usb_gadget *gadget)
2133 {
2134         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2135         struct usb_function             *f;
2136
2137         /* REVISIT:  should we have config level
2138          * suspend/resume callbacks?
2139          */
2140         DBG(cdev, "suspend\n");
2141         if (cdev->config) {
2142                 list_for_each_entry(f, &cdev->config->functions, list) {
2143                         if (f->suspend)
2144                                 f->suspend(f);
2145                 }
2146         }
2147         if (cdev->driver->suspend)
2148                 cdev->driver->suspend(cdev);
2149
2150         cdev->suspended = 1;
2151
2152         usb_gadget_vbus_draw(gadget, 2);
2153 }
2154
2155 void composite_resume(struct usb_gadget *gadget)
2156 {
2157         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2158         struct usb_function             *f;
2159         u16                             maxpower;
2160
2161         /* REVISIT:  should we have config level
2162          * suspend/resume callbacks?
2163          */
2164         DBG(cdev, "resume\n");
2165         if (cdev->driver->resume)
2166                 cdev->driver->resume(cdev);
2167         if (cdev->config) {
2168                 list_for_each_entry(f, &cdev->config->functions, list) {
2169                         if (f->resume)
2170                                 f->resume(f);
2171                 }
2172
2173                 maxpower = cdev->config->MaxPower;
2174
2175                 usb_gadget_vbus_draw(gadget, maxpower ?
2176                         maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2177         }
2178
2179         cdev->suspended = 0;
2180 }
2181
2182 /*-------------------------------------------------------------------------*/
2183
2184 static const struct usb_gadget_driver composite_driver_template = {
2185         .bind           = composite_bind,
2186         .unbind         = composite_unbind,
2187
2188         .setup          = composite_setup,
2189         .reset          = composite_disconnect,
2190         .disconnect     = composite_disconnect,
2191
2192         .suspend        = composite_suspend,
2193         .resume         = composite_resume,
2194
2195         .driver = {
2196                 .owner          = THIS_MODULE,
2197         },
2198 };
2199
2200 /**
2201  * usb_composite_probe() - register a composite driver
2202  * @driver: the driver to register
2203  *
2204  * Context: single threaded during gadget setup
2205  *
2206  * This function is used to register drivers using the composite driver
2207  * framework.  The return value is zero, or a negative errno value.
2208  * Those values normally come from the driver's @bind method, which does
2209  * all the work of setting up the driver to match the hardware.
2210  *
2211  * On successful return, the gadget is ready to respond to requests from
2212  * the host, unless one of its components invokes usb_gadget_disconnect()
2213  * while it was binding.  That would usually be done in order to wait for
2214  * some userspace participation.
2215  */
2216 int usb_composite_probe(struct usb_composite_driver *driver)
2217 {
2218         struct usb_gadget_driver *gadget_driver;
2219
2220         if (!driver || !driver->dev || !driver->bind)
2221                 return -EINVAL;
2222
2223         if (!driver->name)
2224                 driver->name = "composite";
2225
2226         driver->gadget_driver = composite_driver_template;
2227         gadget_driver = &driver->gadget_driver;
2228
2229         gadget_driver->function =  (char *) driver->name;
2230         gadget_driver->driver.name = driver->name;
2231         gadget_driver->max_speed = driver->max_speed;
2232
2233         return usb_gadget_probe_driver(gadget_driver);
2234 }
2235 EXPORT_SYMBOL_GPL(usb_composite_probe);
2236
2237 /**
2238  * usb_composite_unregister() - unregister a composite driver
2239  * @driver: the driver to unregister
2240  *
2241  * This function is used to unregister drivers using the composite
2242  * driver framework.
2243  */
2244 void usb_composite_unregister(struct usb_composite_driver *driver)
2245 {
2246         usb_gadget_unregister_driver(&driver->gadget_driver);
2247 }
2248 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2249
2250 /**
2251  * usb_composite_setup_continue() - Continue with the control transfer
2252  * @cdev: the composite device who's control transfer was kept waiting
2253  *
2254  * This function must be called by the USB function driver to continue
2255  * with the control transfer's data/status stage in case it had requested to
2256  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2257  * can request the composite framework to delay the setup request's data/status
2258  * stages by returning USB_GADGET_DELAYED_STATUS.
2259  */
2260 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2261 {
2262         int                     value;
2263         struct usb_request      *req = cdev->req;
2264         unsigned long           flags;
2265
2266         DBG(cdev, "%s\n", __func__);
2267         spin_lock_irqsave(&cdev->lock, flags);
2268
2269         if (cdev->delayed_status == 0) {
2270                 WARN(cdev, "%s: Unexpected call\n", __func__);
2271
2272         } else if (--cdev->delayed_status == 0) {
2273                 DBG(cdev, "%s: Completing delayed status\n", __func__);
2274                 req->length = 0;
2275                 req->context = cdev;
2276                 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2277                 if (value < 0) {
2278                         DBG(cdev, "ep_queue --> %d\n", value);
2279                         req->status = 0;
2280                         composite_setup_complete(cdev->gadget->ep0, req);
2281                 }
2282         }
2283
2284         spin_unlock_irqrestore(&cdev->lock, flags);
2285 }
2286 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2287
2288 static char *composite_default_mfr(struct usb_gadget *gadget)
2289 {
2290         char *mfr;
2291         int len;
2292
2293         len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2294                         init_utsname()->release, gadget->name);
2295         len++;
2296         mfr = kmalloc(len, GFP_KERNEL);
2297         if (!mfr)
2298                 return NULL;
2299         snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2300                         init_utsname()->release, gadget->name);
2301         return mfr;
2302 }
2303
2304 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2305                 struct usb_composite_overwrite *covr)
2306 {
2307         struct usb_device_descriptor    *desc = &cdev->desc;
2308         struct usb_gadget_strings       *gstr = cdev->driver->strings[0];
2309         struct usb_string               *dev_str = gstr->strings;
2310
2311         if (covr->idVendor)
2312                 desc->idVendor = cpu_to_le16(covr->idVendor);
2313
2314         if (covr->idProduct)
2315                 desc->idProduct = cpu_to_le16(covr->idProduct);
2316
2317         if (covr->bcdDevice)
2318                 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2319
2320         if (covr->serial_number) {
2321                 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2322                 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2323         }
2324         if (covr->manufacturer) {
2325                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2326                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2327
2328         } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2329                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2330                 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2331                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2332         }
2333
2334         if (covr->product) {
2335                 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2336                 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2337         }
2338 }
2339 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2340
2341 MODULE_LICENSE("GPL");
2342 MODULE_AUTHOR("David Brownell");