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