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