0c6101d4423ca04ce592dd697f42a7bd8ef14efa
[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  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /* #define VERBOSE_DEBUG */
22
23 #include <linux/kallsyms.h>
24 #include <linux/kernel.h>
25 #include <linux/slab.h>
26 #include <linux/device.h>
27 #include <linux/utsname.h>
28
29 #include <linux/usb/composite.h>
30
31
32 /*
33  * The code in this file is utility code, used to build a gadget driver
34  * from one or more "function" drivers, one or more "configuration"
35  * objects, and a "usb_composite_driver" by gluing them together along
36  * with the relevant device-wide data.
37  */
38
39 /* big enough to hold our biggest descriptor */
40 #define USB_BUFSIZ      1024
41
42 static struct usb_composite_driver *composite;
43 static int (*composite_gadget_bind)(struct usb_composite_dev *cdev);
44
45 /* Some systems will need runtime overrides for the  product identifiers
46  * published in the device descriptor, either numbers or strings or both.
47  * String parameters are in UTF-8 (superset of ASCII's 7 bit characters).
48  */
49
50 static ushort idVendor;
51 module_param(idVendor, ushort, 0);
52 MODULE_PARM_DESC(idVendor, "USB Vendor ID");
53
54 static ushort idProduct;
55 module_param(idProduct, ushort, 0);
56 MODULE_PARM_DESC(idProduct, "USB Product ID");
57
58 static ushort bcdDevice;
59 module_param(bcdDevice, ushort, 0);
60 MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
61
62 static char *iManufacturer;
63 module_param(iManufacturer, charp, 0);
64 MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
65
66 static char *iProduct;
67 module_param(iProduct, charp, 0);
68 MODULE_PARM_DESC(iProduct, "USB Product string");
69
70 static char *iSerialNumber;
71 module_param(iSerialNumber, charp, 0);
72 MODULE_PARM_DESC(iSerialNumber, "SerialNumber string");
73
74 static char composite_manufacturer[50];
75 static int gadget_connected = 0;
76 /*-------------------------------------------------------------------------*/
77
78 /**
79  * usb_add_function() - add a function to a configuration
80  * @config: the configuration
81  * @function: the function being added
82  * Context: single threaded during gadget setup
83  *
84  * After initialization, each configuration must have one or more
85  * functions added to it.  Adding a function involves calling its @bind()
86  * method to allocate resources such as interface and string identifiers
87  * and endpoints.
88  *
89  * This function returns the value of the function's bind(), which is
90  * zero for success else a negative errno value.
91  */
92 int usb_add_function(struct usb_configuration *config,
93                 struct usb_function *function)
94 {
95         int     value = -EINVAL;
96
97         DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
98                         function->name, function,
99                         config->label, config);
100
101         if (!function->set_alt || !function->disable)
102                 goto done;
103
104         function->config = config;
105         list_add_tail(&function->list, &config->functions);
106
107         /* REVISIT *require* function->bind? */
108         if (function->bind) {
109                 value = function->bind(config, function);
110                 if (value < 0) {
111                         list_del(&function->list);
112                         function->config = NULL;
113                 }
114         } else
115                 value = 0;
116
117         /* We allow configurations that don't work at both speeds.
118          * If we run into a lowspeed Linux system, treat it the same
119          * as full speed ... it's the function drivers that will need
120          * to avoid bulk and ISO transfers.
121          */
122         if (!config->fullspeed && function->descriptors)
123                 config->fullspeed = true;
124         if (!config->highspeed && function->hs_descriptors)
125                 config->highspeed = true;
126
127 done:
128         if (value)
129                 DBG(config->cdev, "adding '%s'/%p --> %d\n",
130                                 function->name, function, value);
131         return value;
132 }
133
134 /**
135  * usb_function_deactivate - prevent function and gadget enumeration
136  * @function: the function that isn't yet ready to respond
137  *
138  * Blocks response of the gadget driver to host enumeration by
139  * preventing the data line pullup from being activated.  This is
140  * normally called during @bind() processing to change from the
141  * initial "ready to respond" state, or when a required resource
142  * becomes available.
143  *
144  * For example, drivers that serve as a passthrough to a userspace
145  * daemon can block enumeration unless that daemon (such as an OBEX,
146  * MTP, or print server) is ready to handle host requests.
147  *
148  * Not all systems support software control of their USB peripheral
149  * data pullups.
150  *
151  * Returns zero on success, else negative errno.
152  */
153 int usb_function_deactivate(struct usb_function *function)
154 {
155         struct usb_composite_dev        *cdev = function->config->cdev;
156         unsigned long                   flags;
157         int                             status = 0;
158
159         spin_lock_irqsave(&cdev->lock, flags);
160
161         if (cdev->deactivations == 0)
162                 status = usb_gadget_disconnect(cdev->gadget);
163         if (status == 0)
164                 cdev->deactivations++;
165
166         spin_unlock_irqrestore(&cdev->lock, flags);
167         return status;
168 }
169
170 /**
171  * usb_function_activate - allow function and gadget enumeration
172  * @function: function on which usb_function_activate() was called
173  *
174  * Reverses effect of usb_function_deactivate().  If no more functions
175  * are delaying their activation, the gadget driver will respond to
176  * host enumeration procedures.
177  *
178  * Returns zero on success, else negative errno.
179  */
180 int usb_function_activate(struct usb_function *function)
181 {
182         struct usb_composite_dev        *cdev = function->config->cdev;
183         int                             status = 0;
184
185         spin_lock(&cdev->lock);
186
187         if (WARN_ON(cdev->deactivations == 0))
188                 status = -EINVAL;
189         else {
190                 cdev->deactivations--;
191                 if (cdev->deactivations == 0)
192                         status = usb_gadget_connect(cdev->gadget);
193         }
194
195         spin_unlock(&cdev->lock);
196         return status;
197 }
198
199 /**
200  * usb_interface_id() - allocate an unused interface ID
201  * @config: configuration associated with the interface
202  * @function: function handling the interface
203  * Context: single threaded during gadget setup
204  *
205  * usb_interface_id() is called from usb_function.bind() callbacks to
206  * allocate new interface IDs.  The function driver will then store that
207  * ID in interface, association, CDC union, and other descriptors.  It
208  * will also handle any control requests targeted at that interface,
209  * particularly changing its altsetting via set_alt().  There may
210  * also be class-specific or vendor-specific requests to handle.
211  *
212  * All interface identifier should be allocated using this routine, to
213  * ensure that for example different functions don't wrongly assign
214  * different meanings to the same identifier.  Note that since interface
215  * identifiers are configuration-specific, functions used in more than
216  * one configuration (or more than once in a given configuration) need
217  * multiple versions of the relevant descriptors.
218  *
219  * Returns the interface ID which was allocated; or -ENODEV if no
220  * more interface IDs can be allocated.
221  */
222 int usb_interface_id(struct usb_configuration *config,
223                 struct usb_function *function)
224 {
225         unsigned id = config->next_interface_id;
226
227         if (id < MAX_CONFIG_INTERFACES) {
228                 config->interface[id] = function;
229                 config->next_interface_id = id + 1;
230                 return id;
231         }
232         return -ENODEV;
233 }
234
235 static int config_buf(struct usb_configuration *config,
236                 enum usb_device_speed speed, void *buf, u8 type)
237 {
238         struct usb_config_descriptor    *c = buf;
239         void                            *next = buf + USB_DT_CONFIG_SIZE;
240         int                             len = USB_BUFSIZ - USB_DT_CONFIG_SIZE;
241         struct usb_function             *f;
242         int                             status;
243
244         /* write the config descriptor */
245         c = buf;
246         c->bLength = USB_DT_CONFIG_SIZE;
247         c->bDescriptorType = type;
248         /* wTotalLength is written later */
249         c->bNumInterfaces = config->next_interface_id;
250         c->bConfigurationValue = config->bConfigurationValue;
251         c->iConfiguration = config->iConfiguration;
252         c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
253         c->bMaxPower = config->bMaxPower ? : (CONFIG_USB_GADGET_VBUS_DRAW / 2);
254
255         /* There may be e.g. OTG descriptors */
256         if (config->descriptors) {
257                 status = usb_descriptor_fillbuf(next, len,
258                                 config->descriptors);
259                 if (status < 0)
260                         return status;
261                 len -= status;
262                 next += status;
263         }
264
265         /* add each function's descriptors */
266         list_for_each_entry(f, &config->functions, list) {
267                 struct usb_descriptor_header **descriptors;
268
269                 if (speed == USB_SPEED_HIGH)
270                         descriptors = f->hs_descriptors;
271                 else
272                         descriptors = f->descriptors;
273                 if (!descriptors)
274                         continue;
275                 status = usb_descriptor_fillbuf(next, len,
276                         (const struct usb_descriptor_header **) descriptors);
277                 if (status < 0)
278                         return status;
279                 len -= status;
280                 next += status;
281         }
282
283         len = next - buf;
284         c->wTotalLength = cpu_to_le16(len);
285         return len;
286 }
287
288 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
289 {
290         struct usb_gadget               *gadget = cdev->gadget;
291         struct usb_configuration        *c;
292         u8                              type = w_value >> 8;
293         enum usb_device_speed           speed = USB_SPEED_UNKNOWN;
294
295         if (gadget_is_dualspeed(gadget)) {
296                 int                     hs = 0;
297
298                 if (gadget->speed == USB_SPEED_HIGH)
299                         hs = 1;
300                 if (type == USB_DT_OTHER_SPEED_CONFIG)
301                         hs = !hs;
302                 if (hs)
303                         speed = USB_SPEED_HIGH;
304
305         }
306
307         /* This is a lookup by config *INDEX* */
308         w_value &= 0xff;
309         list_for_each_entry(c, &cdev->configs, list) {
310                 /* ignore configs that won't work at this speed */
311                 if (speed == USB_SPEED_HIGH) {
312                         if (!c->highspeed)
313                                 continue;
314                 } else {
315                         if (!c->fullspeed)
316                                 continue;
317                 }
318                 if (w_value == 0)
319                         return config_buf(c, speed, cdev->req->buf, type);
320                 w_value--;
321         }
322         return -EINVAL;
323 }
324
325 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
326 {
327         struct usb_gadget               *gadget = cdev->gadget;
328         struct usb_configuration        *c;
329         unsigned                        count = 0;
330         int                             hs = 0;
331
332         if (gadget_is_dualspeed(gadget)) {
333                 if (gadget->speed == USB_SPEED_HIGH)
334                         hs = 1;
335                 if (type == USB_DT_DEVICE_QUALIFIER)
336                         hs = !hs;
337         }
338         list_for_each_entry(c, &cdev->configs, list) {
339                 /* ignore configs that won't work at this speed */
340                 if (hs) {
341                         if (!c->highspeed)
342                                 continue;
343                 } else {
344                         if (!c->fullspeed)
345                                 continue;
346                 }
347                 count++;
348         }
349         return count;
350 }
351
352 static void device_qual(struct usb_composite_dev *cdev)
353 {
354         struct usb_qualifier_descriptor *qual = cdev->req->buf;
355
356         qual->bLength = sizeof(*qual);
357         qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
358         /* POLICY: same bcdUSB and device type info at both speeds */
359         qual->bcdUSB = cdev->desc.bcdUSB;
360         qual->bDeviceClass = cdev->desc.bDeviceClass;
361         qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
362         qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
363         /* ASSUME same EP0 fifo size at both speeds */
364         qual->bMaxPacketSize0 = cdev->desc.bMaxPacketSize0;
365         qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
366         qual->bRESERVED = 0;
367 }
368
369 /*-------------------------------------------------------------------------*/
370
371 static void reset_config(struct usb_composite_dev *cdev)
372 {
373         struct usb_function             *f;
374
375         DBG(cdev, "reset config\n");
376
377         list_for_each_entry(f, &cdev->config->functions, list) {
378                 if (f->disable)
379                         f->disable(f);
380
381                 bitmap_zero(f->endpoints, 32);
382         }
383         cdev->config = NULL;
384 }
385
386 static int set_config(struct usb_composite_dev *cdev,
387                 const struct usb_ctrlrequest *ctrl, unsigned number)
388 {
389         struct usb_gadget       *gadget = cdev->gadget;
390         struct usb_configuration *c = NULL;
391         int                     result = -EINVAL;
392         unsigned                power = gadget_is_otg(gadget) ? 8 : 100;
393         int                     tmp;
394
395         if (cdev->config)
396                 reset_config(cdev);
397
398         if (number) {
399                 list_for_each_entry(c, &cdev->configs, list) {
400                         if (c->bConfigurationValue == number) {
401                                 result = 0;
402                                 break;
403                         }
404                 }
405                 if (result < 0)
406                         goto done;
407         } else
408                 result = 0;
409
410         INFO(cdev, "%s speed config #%d: %s\n",
411                 ({ char *speed;
412                 switch (gadget->speed) {
413                 case USB_SPEED_LOW:     speed = "low"; break;
414                 case USB_SPEED_FULL:    speed = "full"; break;
415                 case USB_SPEED_HIGH:    speed = "high"; break;
416                 default:                speed = "?"; break;
417                 } ; speed; }), number, c ? c->label : "unconfigured");
418
419         if (!c)
420                 goto done;
421
422         cdev->config = c;
423         
424         /* reset delay status to zero every time usb reconnect */
425         cdev->delayed_status = 0;
426
427         /* Initialize all interfaces by setting them to altsetting zero. */
428         for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
429                 struct usb_function     *f = c->interface[tmp];
430                 struct usb_descriptor_header **descriptors;
431
432                 if (!f)
433                         break;
434
435                 /*
436                  * Record which endpoints are used by the function. This is used
437                  * to dispatch control requests targeted at that endpoint to the
438                  * function's setup callback instead of the current
439                  * configuration's setup callback.
440                  */
441                 if (gadget->speed == USB_SPEED_HIGH)
442                         descriptors = f->hs_descriptors;
443                 else
444                         descriptors = f->descriptors;
445
446                 for (; *descriptors; ++descriptors) {
447                         struct usb_endpoint_descriptor *ep;
448                         int addr;
449
450                         if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
451                                 continue;
452
453                         ep = (struct usb_endpoint_descriptor *)*descriptors;
454                         addr = ((ep->bEndpointAddress & 0x80) >> 3)
455                              |  (ep->bEndpointAddress & 0x0f);
456                         set_bit(addr, f->endpoints);
457                 }
458
459                 result = f->set_alt(f, tmp, 0);
460                 if (result < 0) {
461                         DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
462                                         tmp, f->name, f, result);
463
464                         reset_config(cdev);
465                         goto done;
466                 }
467
468                 if (result == USB_GADGET_DELAYED_STATUS) {
469                         DBG(cdev,
470                          "%s: interface %d (%s) requested delayed status\n",
471                                         __func__, tmp, f->name);
472                         cdev->delayed_status++;
473                         DBG(cdev, "delayed_status count %d\n",
474                                         cdev->delayed_status);
475                 }
476         }
477
478         /* when we return, be sure our power usage is valid */
479         power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
480
481         /* usb gadget connect flag */
482         gadget_connected = 1;
483 done:
484         usb_gadget_vbus_draw(gadget, power);
485
486         if (result >= 0 && cdev->delayed_status)
487                 result = USB_GADGET_DELAYED_STATUS;
488         return result;
489 }
490
491 /**
492  * usb_add_config() - add a configuration to a device.
493  * @cdev: wraps the USB gadget
494  * @config: the configuration, with bConfigurationValue assigned
495  * @bind: the configuration's bind function
496  * Context: single threaded during gadget setup
497  *
498  * One of the main tasks of a composite @bind() routine is to
499  * add each of the configurations it supports, using this routine.
500  *
501  * This function returns the value of the configuration's @bind(), which
502  * is zero for success else a negative errno value.  Binding configurations
503  * assigns global resources including string IDs, and per-configuration
504  * resources such as interface IDs and endpoints.
505  */
506 int usb_add_config(struct usb_composite_dev *cdev,
507                 struct usb_configuration *config,
508                 int (*bind)(struct usb_configuration *))
509 {
510         int                             status = -EINVAL;
511         struct usb_configuration        *c;
512
513         DBG(cdev, "adding config #%u '%s'/%p\n",
514                         config->bConfigurationValue,
515                         config->label, config);
516
517         if (!config->bConfigurationValue || !bind)
518                 goto done;
519
520         /* Prevent duplicate configuration identifiers */
521         list_for_each_entry(c, &cdev->configs, list) {
522                 if (c->bConfigurationValue == config->bConfigurationValue) {
523                         printk("usb_add_config, already configed,everest\n");
524                         status = -EBUSY;
525                         goto done;
526                 }
527         }
528
529         config->cdev = cdev;
530         list_add_tail(&config->list, &cdev->configs);
531
532         INIT_LIST_HEAD(&config->functions);
533         config->next_interface_id = 0;
534         memset(config->interface, '\0', sizeof(config->interface));
535
536         status = bind(config);
537         if (status < 0) {
538                 list_del(&config->list);
539                 config->cdev = NULL;
540         } else {
541                 unsigned        i;
542
543                 DBG(cdev, "cfg %d/%p speeds:%s%s\n",
544                         config->bConfigurationValue, config,
545                         config->highspeed ? " high" : "",
546                         config->fullspeed
547                                 ? (gadget_is_dualspeed(cdev->gadget)
548                                         ? " full"
549                                         : " full/low")
550                                 : "");
551
552                 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
553                         struct usb_function     *f = config->interface[i];
554
555                         if (!f)
556                                 continue;
557                         DBG(cdev, "  interface %d = %s/%p\n",
558                                 i, f->name, f);
559                 }
560         }
561
562         /* set_alt(), or next bind(), sets up
563          * ep->driver_data as needed.
564          */
565         usb_ep_autoconfig_reset(cdev->gadget);
566
567 done:
568         if (status)
569                 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
570                                 config->bConfigurationValue, status);
571         return status;
572 }
573
574 static int unbind_config(struct usb_composite_dev *cdev,
575                               struct usb_configuration *config)
576 {
577         while (!list_empty(&config->functions)) {
578                 struct usb_function             *f;
579
580                 f = list_first_entry(&config->functions,
581                                 struct usb_function, list);
582                 list_del(&f->list);
583                 if (f->unbind) {
584                         DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
585                         f->unbind(config, f);
586                         /* may free memory for "f" */
587                 }
588         }
589         if (config->unbind) {
590                 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
591                 config->unbind(config);
592                         /* may free memory for "c" */
593         }
594         return 0;
595 }
596
597 int usb_remove_config(struct usb_composite_dev *cdev,
598                       struct usb_configuration *config)
599 {
600         unsigned long flags;
601
602         spin_lock_irqsave(&cdev->lock, flags);
603
604         if (cdev->config == config)
605                 reset_config(cdev);
606
607         list_del(&config->list);
608
609         spin_unlock_irqrestore(&cdev->lock, flags);
610
611         return unbind_config(cdev, config);
612 }
613
614 /*-------------------------------------------------------------------------*/
615
616 /* We support strings in multiple languages ... string descriptor zero
617  * says which languages are supported.  The typical case will be that
618  * only one language (probably English) is used, with I18N handled on
619  * the host side.
620  */
621
622 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
623 {
624         const struct usb_gadget_strings *s;
625         u16                             language;
626         __le16                          *tmp;
627
628         while (*sp) {
629                 s = *sp;
630                 language = cpu_to_le16(s->language);
631                 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
632                         if (*tmp == language)
633                                 goto repeat;
634                 }
635                 *tmp++ = language;
636 repeat:
637                 sp++;
638         }
639 }
640
641 static int lookup_string(
642         struct usb_gadget_strings       **sp,
643         void                            *buf,
644         u16                             language,
645         int                             id
646 )
647 {
648         struct usb_gadget_strings       *s;
649         int                             value;
650
651         while (*sp) {
652                 s = *sp++;
653                 if (s->language != language)
654                         continue;
655                 value = usb_gadget_get_string(s, id, buf);
656                 if (value > 0)
657                         return value;
658         }
659         return -EINVAL;
660 }
661
662 static int get_string(struct usb_composite_dev *cdev,
663                 void *buf, u16 language, int id)
664 {
665         struct usb_configuration        *c;
666         struct usb_function             *f;
667         int                             len;
668         const char                      *str;
669
670         /* Yes, not only is USB's I18N support probably more than most
671          * folk will ever care about ... also, it's all supported here.
672          * (Except for UTF8 support for Unicode's "Astral Planes".)
673          */
674
675         /* 0 == report all available language codes */
676         if (id == 0) {
677                 struct usb_string_descriptor    *s = buf;
678                 struct usb_gadget_strings       **sp;
679
680                 memset(s, 0, 256);
681                 s->bDescriptorType = USB_DT_STRING;
682
683                 sp = composite->strings;
684                 if (sp)
685                         collect_langs(sp, s->wData);
686
687                 list_for_each_entry(c, &cdev->configs, list) {
688                         sp = c->strings;
689                         if (sp)
690                                 collect_langs(sp, s->wData);
691
692                         list_for_each_entry(f, &c->functions, list) {
693                                 sp = f->strings;
694                                 if (sp)
695                                         collect_langs(sp, s->wData);
696                         }
697                 }
698
699                 for (len = 0; len <= 126 && s->wData[len]; len++)
700                         continue;
701                 if (!len)
702                         return -EINVAL;
703
704                 s->bLength = 2 * (len + 1);
705                 return s->bLength;
706         }
707
708         /* Otherwise, look up and return a specified string.  First
709          * check if the string has not been overridden.
710          */
711         if (cdev->manufacturer_override == id)
712                 str = iManufacturer ?: composite->iManufacturer ?:
713                         composite_manufacturer;
714         else if (cdev->product_override == id)
715                 str = iProduct ?: composite->iProduct;
716         else if (cdev->serial_override == id)
717                 str = iSerialNumber;
718         else
719                 str = NULL;
720         if (str) {
721                 struct usb_gadget_strings strings = {
722                         .language = language,
723                         .strings  = &(struct usb_string) { 0xff, str }
724                 };
725                 return usb_gadget_get_string(&strings, 0xff, buf);
726         }
727
728         /* String IDs are device-scoped, so we look up each string
729          * table we're told about.  These lookups are infrequent;
730          * simpler-is-better here.
731          */
732         if (composite->strings) {
733                 len = lookup_string(composite->strings, buf, language, id);
734                 if (len > 0)
735                         return len;
736         }
737         list_for_each_entry(c, &cdev->configs, list) {
738                 if (c->strings) {
739                         len = lookup_string(c->strings, buf, language, id);
740                         if (len > 0)
741                                 return len;
742                 }
743                 list_for_each_entry(f, &c->functions, list) {
744                         if (!f->strings)
745                                 continue;
746                         len = lookup_string(f->strings, buf, language, id);
747                         if (len > 0)
748                                 return len;
749                 }
750         }
751         return -EINVAL;
752 }
753
754 /**
755  * usb_string_id() - allocate an unused string ID
756  * @cdev: the device whose string descriptor IDs are being allocated
757  * Context: single threaded during gadget setup
758  *
759  * @usb_string_id() is called from bind() callbacks to allocate
760  * string IDs.  Drivers for functions, configurations, or gadgets will
761  * then store that ID in the appropriate descriptors and string table.
762  *
763  * All string identifier should be allocated using this,
764  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
765  * that for example different functions don't wrongly assign different
766  * meanings to the same identifier.
767  */
768 int usb_string_id(struct usb_composite_dev *cdev)
769 {
770         if (cdev->next_string_id < 254) {
771                 /* string id 0 is reserved by USB spec for list of
772                  * supported languages */
773                 /* 255 reserved as well? -- mina86 */
774                 cdev->next_string_id++;
775                 return cdev->next_string_id;
776         }
777         return -ENODEV;
778 }
779
780 /**
781  * usb_string_ids() - allocate unused string IDs in batch
782  * @cdev: the device whose string descriptor IDs are being allocated
783  * @str: an array of usb_string objects to assign numbers to
784  * Context: single threaded during gadget setup
785  *
786  * @usb_string_ids() is called from bind() callbacks to allocate
787  * string IDs.  Drivers for functions, configurations, or gadgets will
788  * then copy IDs from the string table to the appropriate descriptors
789  * and string table for other languages.
790  *
791  * All string identifier should be allocated using this,
792  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
793  * example different functions don't wrongly assign different meanings
794  * to the same identifier.
795  */
796 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
797 {
798         int next = cdev->next_string_id;
799
800         for (; str->s; ++str) {
801                 if (unlikely(next >= 254))
802                         return -ENODEV;
803                 str->id = ++next;
804         }
805
806         cdev->next_string_id = next;
807
808         return 0;
809 }
810
811 /**
812  * usb_string_ids_n() - allocate unused string IDs in batch
813  * @c: the device whose string descriptor IDs are being allocated
814  * @n: number of string IDs to allocate
815  * Context: single threaded during gadget setup
816  *
817  * Returns the first requested ID.  This ID and next @n-1 IDs are now
818  * valid IDs.  At least provided that @n is non-zero because if it
819  * is, returns last requested ID which is now very useful information.
820  *
821  * @usb_string_ids_n() is called from bind() callbacks to allocate
822  * string IDs.  Drivers for functions, configurations, or gadgets will
823  * then store that ID in the appropriate descriptors and string table.
824  *
825  * All string identifier should be allocated using this,
826  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
827  * example different functions don't wrongly assign different meanings
828  * to the same identifier.
829  */
830 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
831 {
832         unsigned next = c->next_string_id;
833         if (unlikely(n > 254 || (unsigned)next + n > 254))
834                 return -ENODEV;
835         c->next_string_id += n;
836         return next + 1;
837 }
838
839
840 /*-------------------------------------------------------------------------*/
841
842 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
843 {
844         if (req->status || req->actual != req->length)
845                 DBG((struct usb_composite_dev *) ep->driver_data,
846                                 "setup complete --> %d, %d/%d\n",
847                                 req->status, req->actual, req->length);
848 }
849
850 /*
851  * The setup() callback implements all the ep0 functionality that's
852  * not handled lower down, in hardware or the hardware driver(like
853  * device and endpoint feature flags, and their status).  It's all
854  * housekeeping for the gadget function we're implementing.  Most of
855  * the work is in config and function specific setup.
856  */
857 static int
858 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
859 {
860         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
861         struct usb_request              *req = cdev->req;
862         int                             value = -EOPNOTSUPP;
863         u16                             w_index = le16_to_cpu(ctrl->wIndex);
864         u8                              intf = w_index & 0xFF;
865         u16                             w_value = le16_to_cpu(ctrl->wValue);
866         u16                             w_length = le16_to_cpu(ctrl->wLength);
867         struct usb_function             *f = NULL;
868         u8                              endp;
869
870         /* partial re-init of the response message; the function or the
871          * gadget might need to intercept e.g. a control-OUT completion
872          * when we delegate to it.
873          */
874         req->zero = 0;
875         req->complete = composite_setup_complete;
876         req->length = 0;
877         gadget->ep0->driver_data = cdev;
878
879         switch (ctrl->bRequest) {
880
881         /* we handle all standard USB descriptors */
882         case USB_REQ_GET_DESCRIPTOR:
883                 if (ctrl->bRequestType != USB_DIR_IN)
884                         goto unknown;
885                 switch (w_value >> 8) {
886
887                 case USB_DT_DEVICE:
888                         cdev->desc.bNumConfigurations =
889                                 count_configs(cdev, USB_DT_DEVICE);
890                         value = min(w_length, (u16) sizeof cdev->desc);
891                         memcpy(req->buf, &cdev->desc, value);
892                         break;
893                 case USB_DT_DEVICE_QUALIFIER:
894                         if (!gadget_is_dualspeed(gadget))
895                                 break;
896                         device_qual(cdev);
897                         value = min_t(int, w_length,
898                                 sizeof(struct usb_qualifier_descriptor));
899                         break;
900                 case USB_DT_OTHER_SPEED_CONFIG:
901                         if (!gadget_is_dualspeed(gadget))
902                                 break;
903                         /* FALLTHROUGH */
904                 case USB_DT_CONFIG:
905                         value = config_desc(cdev, w_value);
906                         if (value >= 0)
907                                 value = min(w_length, (u16) value);
908                         break;
909                 case USB_DT_STRING:
910                         value = get_string(cdev, req->buf,
911                                         w_index, w_value & 0xff);
912                         if (value >= 0)
913                                 value = min(w_length, (u16) value);
914                         break;
915                 }
916                 break;
917
918         /* any number of configs can work */
919         case USB_REQ_SET_CONFIGURATION:
920                 if (ctrl->bRequestType != 0)
921                         goto unknown;
922                 if (gadget_is_otg(gadget)) {
923                         if (gadget->a_hnp_support)
924                                 DBG(cdev, "HNP available\n");
925                         else if (gadget->a_alt_hnp_support)
926                                 DBG(cdev, "HNP on another port\n");
927                         else
928                                 VDBG(cdev, "HNP inactive\n");
929                 }
930                 spin_lock(&cdev->lock);
931                 value = set_config(cdev, ctrl, w_value);
932                 spin_unlock(&cdev->lock);
933                 break;
934         case USB_REQ_GET_CONFIGURATION:
935                 if (ctrl->bRequestType != USB_DIR_IN)
936                         goto unknown;
937                 if (cdev->config)
938                         *(u8 *)req->buf = cdev->config->bConfigurationValue;
939                 else
940                         *(u8 *)req->buf = 0;
941                 value = min(w_length, (u16) 1);
942                 break;
943
944         /* function drivers must handle get/set altsetting; if there's
945          * no get() method, we know only altsetting zero works.
946          */
947         case USB_REQ_SET_INTERFACE:
948                 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
949                         goto unknown;
950                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
951                         break;
952                 f = cdev->config->interface[intf];
953                 if (!f)
954                         break;
955                 if (w_value && !f->set_alt)
956                         break;
957                 value = f->set_alt(f, w_index, w_value);
958                 if (value == USB_GADGET_DELAYED_STATUS) {
959                         DBG(cdev,
960                          "%s: interface %d (%s) requested delayed status\n",
961                                         __func__, intf, f->name);
962                         cdev->delayed_status++;
963                         DBG(cdev, "delayed_status count %d\n",
964                                         cdev->delayed_status);
965                 }
966                 break;
967         case USB_REQ_GET_INTERFACE:
968                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
969                         goto unknown;
970                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
971                         break;
972                 f = cdev->config->interface[intf];
973                 if (!f)
974                         break;
975                 /* lots of interfaces only need altsetting zero... */
976                 value = f->get_alt ? f->get_alt(f, w_index) : 0;
977                 if (value < 0)
978                         break;
979                 *((u8 *)req->buf) = value;
980                 value = min(w_length, (u16) 1);
981                 break;
982         default:
983 unknown:
984                 VDBG(cdev,
985                         "non-core control req%02x.%02x v%04x i%04x l%d\n",
986                         ctrl->bRequestType, ctrl->bRequest,
987                         w_value, w_index, w_length);
988
989                 /* functions always handle their interfaces and endpoints...
990                  * punt other recipients (other, WUSB, ...) to the current
991                  * configuration code.
992                  *
993                  * REVISIT it could make sense to let the composite device
994                  * take such requests too, if that's ever needed:  to work
995                  * in config 0, etc.
996                  */
997                 switch (ctrl->bRequestType & USB_RECIP_MASK) {
998                 case USB_RECIP_INTERFACE:
999                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1000                                 break;
1001                         f = cdev->config->interface[intf];
1002                         break;
1003
1004                 case USB_RECIP_ENDPOINT:
1005                         endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1006                         list_for_each_entry(f, &cdev->config->functions, list) {
1007                                 if (test_bit(endp, f->endpoints))
1008                                         break;
1009                         }
1010                         if (&f->list == &cdev->config->functions)
1011                                 f = NULL;
1012                         break;
1013                 }
1014
1015                 if (f && f->setup)
1016                         value = f->setup(f, ctrl);
1017                 else {
1018                         struct usb_configuration        *c;
1019
1020                         c = cdev->config;
1021                         if (c && c->setup)
1022                                 value = c->setup(c, ctrl);
1023                 }
1024
1025                 goto done;
1026         }
1027
1028         /* respond with data transfer before status phase? */
1029         if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1030                 req->length = value;
1031                 req->zero = value < w_length;
1032                 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1033                 if (value < 0) {
1034                         DBG(cdev, "ep_queue --> %d\n", value);
1035                         req->status = 0;
1036                         composite_setup_complete(gadget->ep0, req);
1037                 }
1038         } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1039                 WARN(cdev,
1040                         "%s: Delayed status not supported for w_length != 0",
1041                         __func__);
1042         }
1043
1044 done:
1045         /* device either stalls (value < 0) or reports success */
1046         return value;
1047 }
1048
1049 static void composite_disconnect(struct usb_gadget *gadget)
1050 {
1051         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1052         unsigned long                   flags;
1053
1054         /* REVISIT:  should we have config and device level
1055          * disconnect callbacks?
1056          */
1057         spin_lock_irqsave(&cdev->lock, flags);
1058         if (cdev->config)
1059                 reset_config(cdev);
1060         if (composite->disconnect)
1061                 composite->disconnect(cdev);
1062         /* usb gadget connect flag */
1063         gadget_connected = 0;
1064         spin_unlock_irqrestore(&cdev->lock, flags);
1065 }
1066
1067 /*-------------------------------------------------------------------------*/
1068 int get_gadget_connect_flag( void )
1069 {
1070     return gadget_connected;
1071 }
1072 EXPORT_SYMBOL(get_gadget_connect_flag);
1073
1074 static ssize_t composite_show_suspended(struct device *dev,
1075                                         struct device_attribute *attr,
1076                                         char *buf)
1077 {
1078         struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1079         struct usb_composite_dev *cdev = get_gadget_data(gadget);
1080
1081         return sprintf(buf, "%d\n", cdev->suspended);
1082 }
1083
1084 static DEVICE_ATTR(suspended, 0444, composite_show_suspended, NULL);
1085
1086 static void
1087 composite_unbind(struct usb_gadget *gadget)
1088 {
1089         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1090
1091         /* composite_disconnect() must already have been called
1092          * by the underlying peripheral controller driver!
1093          * so there's no i/o concurrency that could affect the
1094          * state protected by cdev->lock.
1095          */
1096         WARN_ON(cdev->config);
1097
1098         while (!list_empty(&cdev->configs)) {
1099                 struct usb_configuration        *c;
1100                 c = list_first_entry(&cdev->configs,
1101                                 struct usb_configuration, list);
1102                 list_del(&c->list);
1103                 unbind_config(cdev, c);
1104         }
1105         if (composite->unbind)
1106                 composite->unbind(cdev);
1107
1108         if (cdev->req) {
1109                 kfree(cdev->req->buf);
1110                 usb_ep_free_request(gadget->ep0, cdev->req);
1111         }
1112         device_remove_file(&gadget->dev, &dev_attr_suspended);
1113         kfree(cdev);
1114         set_gadget_data(gadget, NULL);
1115         composite = NULL;
1116 }
1117
1118 static u8 override_id(struct usb_composite_dev *cdev, u8 *desc)
1119 {
1120         if (!*desc) {
1121                 int ret = usb_string_id(cdev);
1122                 if (unlikely(ret < 0))
1123                         WARNING(cdev, "failed to override string ID\n");
1124                 else
1125                         *desc = ret;
1126         }
1127
1128         return *desc;
1129 }
1130
1131 static int composite_bind(struct usb_gadget *gadget)
1132 {
1133         struct usb_composite_dev        *cdev;
1134         int                             status = -ENOMEM;
1135
1136         cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
1137         if (!cdev)
1138                 return status;
1139
1140         spin_lock_init(&cdev->lock);
1141         cdev->gadget = gadget;
1142         set_gadget_data(gadget, cdev);
1143         INIT_LIST_HEAD(&cdev->configs);
1144
1145         /* preallocate control response and buffer */
1146         cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1147         if (!cdev->req)
1148                 goto fail;
1149         cdev->req->buf = kmalloc(USB_BUFSIZ, GFP_KERNEL);
1150         if (!cdev->req->buf)
1151                 goto fail;
1152         cdev->req->complete = composite_setup_complete;
1153         gadget->ep0->driver_data = cdev;
1154
1155         cdev->bufsiz = USB_BUFSIZ;
1156         cdev->driver = composite;
1157
1158         /*
1159          * As per USB compliance update, a device that is actively drawing
1160          * more than 100mA from USB must report itself as bus-powered in
1161          * the GetStatus(DEVICE) call.
1162          */
1163         if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
1164                 usb_gadget_set_selfpowered(gadget);
1165
1166         /* interface and string IDs start at zero via kzalloc.
1167          * we force endpoints to start unassigned; few controller
1168          * drivers will zero ep->driver_data.
1169          */
1170         usb_ep_autoconfig_reset(cdev->gadget);
1171
1172         /* composite gadget needs to assign strings for whole device (like
1173          * serial number), register function drivers, potentially update
1174          * power state and consumption, etc
1175          */
1176         status = composite_gadget_bind(cdev);
1177         if (status < 0)
1178                 goto fail;
1179
1180         cdev->desc = *composite->dev;
1181         cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1182
1183         /* standardized runtime overrides for device ID data */
1184         if (idVendor)
1185                 cdev->desc.idVendor = cpu_to_le16(idVendor);
1186         if (idProduct)
1187                 cdev->desc.idProduct = cpu_to_le16(idProduct);
1188         if (bcdDevice)
1189                 cdev->desc.bcdDevice = cpu_to_le16(bcdDevice);
1190
1191         /* string overrides */
1192         if (iManufacturer || !cdev->desc.iManufacturer) {
1193                 if (!iManufacturer && !composite->iManufacturer &&
1194                     !*composite_manufacturer)
1195                         snprintf(composite_manufacturer,
1196                                  sizeof composite_manufacturer,
1197                                  "%s %s with %s",
1198                                  init_utsname()->sysname,
1199                                  init_utsname()->release,
1200                                  gadget->name);
1201
1202                 cdev->manufacturer_override =
1203                         override_id(cdev, &cdev->desc.iManufacturer);
1204         }
1205
1206         if (iProduct || (!cdev->desc.iProduct && composite->iProduct))
1207                 cdev->product_override =
1208                         override_id(cdev, &cdev->desc.iProduct);
1209
1210         if (iSerialNumber)
1211                 cdev->serial_override =
1212                         override_id(cdev, &cdev->desc.iSerialNumber);
1213
1214         /* has userspace failed to provide a serial number? */
1215         if (composite->needs_serial && !cdev->desc.iSerialNumber)
1216                 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
1217
1218         /* finish up */
1219         status = device_create_file(&gadget->dev, &dev_attr_suspended);
1220         if (status)
1221                 goto fail;
1222
1223         INFO(cdev, "%s ready\n", composite->name);
1224         return 0;
1225
1226 fail:
1227         composite_unbind(gadget);
1228         return status;
1229 }
1230
1231 /*-------------------------------------------------------------------------*/
1232
1233 static void
1234 composite_suspend(struct usb_gadget *gadget)
1235 {
1236         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1237         struct usb_function             *f;
1238
1239         /* REVISIT:  should we have config level
1240          * suspend/resume callbacks?
1241          */
1242         DBG(cdev, "suspend\n");
1243         if (cdev->config) {
1244                 list_for_each_entry(f, &cdev->config->functions, list) {
1245                         if (f->suspend)
1246                                 f->suspend(f);
1247                 }
1248         }
1249         if (composite->suspend)
1250                 composite->suspend(cdev);
1251
1252         cdev->suspended = 1;
1253
1254         usb_gadget_vbus_draw(gadget, 2);
1255 }
1256
1257 static void
1258 composite_resume(struct usb_gadget *gadget)
1259 {
1260         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1261         struct usb_function             *f;
1262         u8                              maxpower;
1263
1264         /* REVISIT:  should we have config level
1265          * suspend/resume callbacks?
1266          */
1267         DBG(cdev, "resume\n");
1268         if (composite->resume)
1269                 composite->resume(cdev);
1270         if (cdev->config) {
1271                 list_for_each_entry(f, &cdev->config->functions, list) {
1272                         if (f->resume)
1273                                 f->resume(f);
1274                 }
1275
1276                 maxpower = cdev->config->bMaxPower;
1277
1278                 usb_gadget_vbus_draw(gadget, maxpower ?
1279                         (2 * maxpower) : CONFIG_USB_GADGET_VBUS_DRAW);
1280         }
1281
1282         cdev->suspended = 0;
1283 }
1284
1285 /*-------------------------------------------------------------------------*/
1286
1287 static struct usb_gadget_driver composite_driver = {
1288         .speed          = USB_SPEED_HIGH,
1289
1290         .unbind         = composite_unbind,
1291
1292         .setup          = composite_setup,
1293         .disconnect     = composite_disconnect,
1294
1295         .suspend        = composite_suspend,
1296         .resume         = composite_resume,
1297
1298         .driver = {
1299                 .owner          = THIS_MODULE,
1300         },
1301 };
1302
1303 /**
1304  * usb_composite_probe() - register a composite driver
1305  * @driver: the driver to register
1306  * @bind: the callback used to allocate resources that are shared across the
1307  *      whole device, such as string IDs, and add its configurations using
1308  *      @usb_add_config().  This may fail by returning a negative errno
1309  *      value; it should return zero on successful initialization.
1310  * Context: single threaded during gadget setup
1311  *
1312  * This function is used to register drivers using the composite driver
1313  * framework.  The return value is zero, or a negative errno value.
1314  * Those values normally come from the driver's @bind method, which does
1315  * all the work of setting up the driver to match the hardware.
1316  *
1317  * On successful return, the gadget is ready to respond to requests from
1318  * the host, unless one of its components invokes usb_gadget_disconnect()
1319  * while it was binding.  That would usually be done in order to wait for
1320  * some userspace participation.
1321  */
1322 int usb_composite_probe(struct usb_composite_driver *driver,
1323                                int (*bind)(struct usb_composite_dev *cdev))
1324 {
1325         if (!driver || !driver->dev || !bind || composite)
1326                 return -EINVAL;
1327
1328         if (!driver->name)
1329                 driver->name = "composite";
1330         if (!driver->iProduct)
1331                 driver->iProduct = driver->name;
1332         composite_driver.function =  (char *) driver->name;
1333         composite_driver.driver.name = driver->name;
1334         composite = driver;
1335         composite_gadget_bind = bind;
1336
1337         return usb_gadget_probe_driver(&composite_driver, composite_bind);
1338 }
1339
1340 /**
1341  * usb_composite_unregister() - unregister a composite driver
1342  * @driver: the driver to unregister
1343  *
1344  * This function is used to unregister drivers using the composite
1345  * driver framework.
1346  */
1347 void usb_composite_unregister(struct usb_composite_driver *driver)
1348 {
1349         if (composite != driver)
1350                 return;
1351         usb_gadget_unregister_driver(&composite_driver);
1352 }
1353
1354 /**
1355  * usb_composite_setup_continue() - Continue with the control transfer
1356  * @cdev: the composite device who's control transfer was kept waiting
1357  *
1358  * This function must be called by the USB function driver to continue
1359  * with the control transfer's data/status stage in case it had requested to
1360  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
1361  * can request the composite framework to delay the setup request's data/status
1362  * stages by returning USB_GADGET_DELAYED_STATUS.
1363  */
1364 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
1365 {
1366         int                     value;
1367         struct usb_request      *req = cdev->req;
1368         unsigned long           flags;
1369
1370         DBG(cdev, "%s\n", __func__);
1371         spin_lock_irqsave(&cdev->lock, flags);
1372
1373         if (cdev->delayed_status == 0) {
1374                 WARN(cdev, "%s: Unexpected call\n", __func__);
1375
1376         } else if (--cdev->delayed_status == 0) {
1377                 DBG(cdev, "%s: Completing delayed status\n", __func__);
1378                 req->length = 0;
1379                 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1380                 if (value < 0) {
1381                         DBG(cdev, "ep_queue --> %d\n", value);
1382                         req->status = 0;
1383                         composite_setup_complete(cdev->gadget->ep0, req);
1384                 }
1385         }
1386         else{
1387             WARN(cdev, "%s: Unexpected delayed status 0x%x\n", __func__, cdev->delayed_status);
1388         }
1389
1390         spin_unlock_irqrestore(&cdev->lock, flags);
1391 }
1392