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