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