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