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