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