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