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