]> rtime.felk.cvut.cz Git - sojka/nv-tegra/linux-3.10.git/blob - drivers/usb/gadget/composite.c
usb: gadget: composite: Fix cdev null after rmmod
[sojka/nv-tegra/linux-3.10.git] / drivers / usb / gadget / composite.c
1 /*
2  * composite.c - infrastructure for Composite USB Gadgets
3  *
4  * Copyright (C) 2006-2008 David Brownell
5  * Copyright (c) 2015 NVIDIA CORPORATION. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12
13 /* #define VERBOSE_DEBUG */
14
15 #include <linux/kallsyms.h>
16 #include <linux/kernel.h>
17 #include <linux/slab.h>
18 #include <linux/module.h>
19 #include <linux/device.h>
20 #include <linux/utsname.h>
21
22 #include <linux/usb/composite.h>
23 #include <asm/unaligned.h>
24
25 /*
26  * The code in this file is utility code, used to build a gadget driver
27  * from one or more "function" drivers, one or more "configuration"
28  * objects, and a "usb_composite_driver" by gluing them together along
29  * with the relevant device-wide data.
30  */
31
32 static struct usb_gadget_strings **get_containers_gs(
33                 struct usb_gadget_string_container *uc)
34 {
35         return (struct usb_gadget_strings **)uc->stash;
36 }
37
38 /**
39  * next_ep_desc() - advance to the next EP descriptor
40  * @t: currect pointer within descriptor array
41  *
42  * Return: next EP descriptor or NULL
43  *
44  * Iterate over @t until either EP descriptor found or
45  * NULL (that indicates end of list) encountered
46  */
47 static struct usb_descriptor_header**
48 next_ep_desc(struct usb_descriptor_header **t)
49 {
50         for (; *t; t++) {
51                 if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
52                         return t;
53         }
54         return NULL;
55 }
56
57 /*
58  * for_each_ep_desc()- iterate over endpoint descriptors in the
59  *              descriptors list
60  * @start:      pointer within descriptor array.
61  * @ep_desc:    endpoint descriptor to use as the loop cursor
62  */
63 #define for_each_ep_desc(start, ep_desc) \
64         for (ep_desc = next_ep_desc(start); \
65               ep_desc; ep_desc = next_ep_desc(ep_desc+1))
66
67 /**
68  * config_ep_by_speed() - configures the given endpoint
69  * according to gadget speed.
70  * @g: pointer to the gadget
71  * @f: usb function
72  * @_ep: the endpoint to configure
73  *
74  * Return: error code, 0 on success
75  *
76  * This function chooses the right descriptors for a given
77  * endpoint according to gadget speed and saves it in the
78  * endpoint desc field. If the endpoint already has a descriptor
79  * assigned to it - overwrites it with currently corresponding
80  * descriptor. The endpoint maxpacket field is updated according
81  * to the chosen descriptor.
82  * Note: the supplied function should hold all the descriptors
83  * for supported speeds
84  */
85 int config_ep_by_speed(struct usb_gadget *g,
86                         struct usb_function *f,
87                         struct usb_ep *_ep)
88 {
89         struct usb_composite_dev        *cdev = get_gadget_data(g);
90         struct usb_endpoint_descriptor *chosen_desc = NULL;
91         struct usb_descriptor_header **speed_desc = NULL;
92
93         struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
94         int want_comp_desc = 0;
95
96         struct usb_descriptor_header **d_spd; /* cursor for speed desc */
97
98         if (!g || !f || !_ep)
99                 return -EIO;
100
101         /* select desired speed */
102         switch (g->speed) {
103         case USB_SPEED_SUPER:
104                 if (gadget_is_superspeed(g)) {
105                         speed_desc = f->ss_descriptors;
106                         want_comp_desc = 1;
107                         break;
108                 }
109                 /* else: Fall trough */
110         case USB_SPEED_HIGH:
111                 if (gadget_is_dualspeed(g)) {
112                         speed_desc = f->hs_descriptors;
113                         break;
114                 }
115                 /* else: fall through */
116         default:
117                 speed_desc = f->fs_descriptors;
118         }
119         /* find descriptors */
120         for_each_ep_desc(speed_desc, d_spd) {
121                 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
122                 if (chosen_desc->bEndpointAddress == _ep->address)
123                         goto ep_found;
124         }
125         return -EIO;
126
127 ep_found:
128         /* commit results */
129         _ep->maxpacket = usb_endpoint_maxp(chosen_desc);
130         _ep->desc = chosen_desc;
131         _ep->comp_desc = NULL;
132         _ep->maxburst = 0;
133         _ep->mult = 0;
134         if (!want_comp_desc)
135                 return 0;
136
137         /*
138          * Companion descriptor should follow EP descriptor
139          * USB 3.0 spec, #9.6.7
140          */
141         comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
142         if (!comp_desc ||
143             (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
144                 return -EIO;
145         _ep->comp_desc = comp_desc;
146         if (g->speed == USB_SPEED_SUPER) {
147                 switch (usb_endpoint_type(_ep->desc)) {
148                 case USB_ENDPOINT_XFER_ISOC:
149                         /* mult: bits 1:0 of bmAttributes */
150                         _ep->mult = comp_desc->bmAttributes & 0x3;
151                 case USB_ENDPOINT_XFER_BULK:
152                 case USB_ENDPOINT_XFER_INT:
153                         _ep->maxburst = comp_desc->bMaxBurst + 1;
154                         break;
155                 default:
156                         if (comp_desc->bMaxBurst != 0)
157                                 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
158                         _ep->maxburst = 1;
159                         break;
160                 }
161         }
162         return 0;
163 }
164 EXPORT_SYMBOL_GPL(config_ep_by_speed);
165
166 /**
167  * usb_add_function() - add a function to a configuration
168  * @config: the configuration
169  * @function: the function being added
170  * Context: single threaded during gadget setup
171  *
172  * After initialization, each configuration must have one or more
173  * functions added to it.  Adding a function involves calling its @bind()
174  * method to allocate resources such as interface and string identifiers
175  * and endpoints.
176  *
177  * This function returns the value of the function's bind(), which is
178  * zero for success else a negative errno value.
179  */
180 int usb_add_function(struct usb_configuration *config,
181                 struct usb_function *function)
182 {
183         int     value = -EINVAL;
184
185         DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
186                         function->name, function,
187                         config->label, config);
188
189         if (!function->set_alt || !function->disable)
190                 goto done;
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->fs_descriptors)
211                 config->fullspeed = true;
212         if (!config->highspeed && function->hs_descriptors)
213                 config->highspeed = true;
214         if (!config->superspeed && function->ss_descriptors)
215                 config->superspeed = true;
216
217 done:
218         if (value)
219                 DBG(config->cdev, "adding '%s'/%p --> %d\n",
220                                 function->name, function, value);
221         return value;
222 }
223 EXPORT_SYMBOL_GPL(usb_add_function);
224
225 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
226 {
227         if (f->disable)
228                 f->disable(f);
229
230         bitmap_zero(f->endpoints, 32);
231         list_del(&f->list);
232         if (f->unbind)
233                 f->unbind(c, f);
234 }
235 EXPORT_SYMBOL_GPL(usb_remove_function);
236
237 /**
238  * usb_function_deactivate - prevent function and gadget enumeration
239  * @function: the function that isn't yet ready to respond
240  *
241  * Blocks response of the gadget driver to host enumeration by
242  * preventing the data line pullup from being activated.  This is
243  * normally called during @bind() processing to change from the
244  * initial "ready to respond" state, or when a required resource
245  * becomes available.
246  *
247  * For example, drivers that serve as a passthrough to a userspace
248  * daemon can block enumeration unless that daemon (such as an OBEX,
249  * MTP, or print server) is ready to handle host requests.
250  *
251  * Not all systems support software control of their USB peripheral
252  * data pullups.
253  *
254  * Returns zero on success, else negative errno.
255  */
256 int usb_function_deactivate(struct usb_function *function)
257 {
258         struct usb_composite_dev        *cdev = function->config->cdev;
259         unsigned long                   flags;
260         int                             status = 0;
261
262         spin_lock_irqsave(&cdev->lock, flags);
263
264         if (cdev->deactivations == 0)
265                 status = usb_gadget_disconnect(cdev->gadget);
266         if (status == 0)
267                 cdev->deactivations++;
268
269         spin_unlock_irqrestore(&cdev->lock, flags);
270         return status;
271 }
272 EXPORT_SYMBOL_GPL(usb_function_deactivate);
273
274 /**
275  * usb_function_activate - allow function and gadget enumeration
276  * @function: function on which usb_function_activate() was called
277  *
278  * Reverses effect of usb_function_deactivate().  If no more functions
279  * are delaying their activation, the gadget driver will respond to
280  * host enumeration procedures.
281  *
282  * Returns zero on success, else negative errno.
283  */
284 int usb_function_activate(struct usb_function *function)
285 {
286         struct usb_composite_dev        *cdev = function->config->cdev;
287         unsigned long                   flags;
288         int                             status = 0;
289
290         spin_lock_irqsave(&cdev->lock, flags);
291
292         if (WARN_ON(cdev->deactivations == 0))
293                 status = -EINVAL;
294         else {
295                 cdev->deactivations--;
296                 if (cdev->deactivations == 0)
297                         status = usb_gadget_connect(cdev->gadget);
298         }
299
300         spin_unlock_irqrestore(&cdev->lock, flags);
301         return status;
302 }
303 EXPORT_SYMBOL_GPL(usb_function_activate);
304
305 /**
306  * usb_interface_id() - allocate an unused interface ID
307  * @config: configuration associated with the interface
308  * @function: function handling the interface
309  * Context: single threaded during gadget setup
310  *
311  * usb_interface_id() is called from usb_function.bind() callbacks to
312  * allocate new interface IDs.  The function driver will then store that
313  * ID in interface, association, CDC union, and other descriptors.  It
314  * will also handle any control requests targeted at that interface,
315  * particularly changing its altsetting via set_alt().  There may
316  * also be class-specific or vendor-specific requests to handle.
317  *
318  * All interface identifier should be allocated using this routine, to
319  * ensure that for example different functions don't wrongly assign
320  * different meanings to the same identifier.  Note that since interface
321  * identifiers are configuration-specific, functions used in more than
322  * one configuration (or more than once in a given configuration) need
323  * multiple versions of the relevant descriptors.
324  *
325  * Returns the interface ID which was allocated; or -ENODEV if no
326  * more interface IDs can be allocated.
327  */
328 int usb_interface_id(struct usb_configuration *config,
329                 struct usb_function *function)
330 {
331         unsigned id = config->next_interface_id;
332
333         if (id < MAX_CONFIG_INTERFACES) {
334                 config->interface[id] = function;
335                 config->next_interface_id = id + 1;
336                 return id;
337         }
338         return -ENODEV;
339 }
340 EXPORT_SYMBOL_GPL(usb_interface_id);
341
342 static u8 encode_bMaxPower(enum usb_device_speed speed,
343                 struct usb_configuration *c)
344 {
345         unsigned val;
346
347         if (c->MaxPower)
348                 val = c->MaxPower;
349         else
350                 val = CONFIG_USB_GADGET_VBUS_DRAW;
351         if (!val)
352                 return 0;
353         switch (speed) {
354         case USB_SPEED_SUPER:
355                 return DIV_ROUND_UP(val, 8);
356         default:
357                 return DIV_ROUND_UP(val, 2);
358         };
359 }
360
361 static int config_buf(struct usb_configuration *config,
362                 enum usb_device_speed speed, void *buf, u8 type)
363 {
364         struct usb_config_descriptor    *c = buf;
365         void                            *next = buf + USB_DT_CONFIG_SIZE;
366         int                             len;
367         struct usb_function             *f;
368         int                             status;
369         int                             interfaceCount = 0;
370
371         len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
372         /* write the config descriptor */
373         c = buf;
374         c->bLength = USB_DT_CONFIG_SIZE;
375         c->bDescriptorType = type;
376         /* wTotalLength is written later */
377         c->bNumInterfaces = config->next_interface_id;
378         c->bConfigurationValue = config->bConfigurationValue;
379         c->iConfiguration = config->iConfiguration;
380         c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
381         if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
382                 c->bmAttributes |= USB_CONFIG_ATT_SELFPOWER;
383         c->bMaxPower = encode_bMaxPower(speed, config);
384
385         /* There may be e.g. OTG descriptors */
386         if (config->descriptors) {
387                 status = usb_descriptor_fillbuf(next, len,
388                                 config->descriptors);
389                 if (status < 0)
390                         return status;
391                 len -= status;
392                 next += status;
393         }
394
395         /* add each function's descriptors */
396         list_for_each_entry(f, &config->functions, list) {
397                 struct usb_descriptor_header **descriptors;
398
399                 switch (speed) {
400                 case USB_SPEED_SUPER:
401                         descriptors = f->ss_descriptors;
402                         break;
403                 case USB_SPEED_HIGH:
404                         descriptors = f->hs_descriptors;
405                         break;
406                 default:
407                         descriptors = f->fs_descriptors;
408                 }
409
410                 if (f->hidden || !descriptors || descriptors[0] == NULL) {
411                         for (; f != config->interface[interfaceCount];) {
412                                 interfaceCount++;
413                                 c->bNumInterfaces--;
414                         }
415                         continue;
416                 }
417                 for (; f != config->interface[interfaceCount];)
418                         interfaceCount++;
419
420                 status = usb_descriptor_fillbuf(next, len,
421                         (const struct usb_descriptor_header **) descriptors);
422                 if (status < 0)
423                         return status;
424                 len -= status;
425                 next += status;
426         }
427
428         len = next - buf;
429         c->wTotalLength = cpu_to_le16(len);
430         return len;
431 }
432
433 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
434 {
435         struct usb_gadget               *gadget = cdev->gadget;
436         struct usb_configuration        *c;
437         u8                              type = w_value >> 8;
438         enum usb_device_speed           speed = USB_SPEED_UNKNOWN;
439
440         if (gadget->speed == USB_SPEED_SUPER)
441                 speed = gadget->speed;
442         else if (gadget_is_dualspeed(gadget)) {
443                 int     hs = 0;
444                 if (gadget->speed == USB_SPEED_HIGH)
445                         hs = 1;
446                 if (type == USB_DT_OTHER_SPEED_CONFIG)
447                         hs = !hs;
448                 if (hs)
449                         speed = USB_SPEED_HIGH;
450
451         }
452
453         /* This is a lookup by config *INDEX* */
454         w_value &= 0xff;
455         list_for_each_entry(c, &cdev->configs, list) {
456                 /* ignore configs that won't work at this speed */
457                 switch (speed) {
458                 case USB_SPEED_SUPER:
459                         if (!c->superspeed)
460                                 continue;
461                         break;
462                 case USB_SPEED_HIGH:
463                         if (!c->highspeed)
464                                 continue;
465                         break;
466                 default:
467                         if (!c->fullspeed)
468                                 continue;
469                 }
470
471                 if (w_value == 0)
472                         return config_buf(c, speed, cdev->req->buf, type);
473                 w_value--;
474         }
475         return -EINVAL;
476 }
477
478 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
479 {
480         struct usb_gadget               *gadget = cdev->gadget;
481         struct usb_configuration        *c;
482         unsigned                        count = 0;
483         int                             hs = 0;
484         int                             ss = 0;
485
486         if (gadget_is_dualspeed(gadget)) {
487                 if (gadget->speed == USB_SPEED_HIGH)
488                         hs = 1;
489                 if (gadget->speed == USB_SPEED_SUPER)
490                         ss = 1;
491                 if (type == USB_DT_DEVICE_QUALIFIER)
492                         hs = !hs;
493         }
494         list_for_each_entry(c, &cdev->configs, list) {
495                 /* ignore configs that won't work at this speed */
496                 if (ss) {
497                         if (!c->superspeed)
498                                 continue;
499                 } else if (hs) {
500                         if (!c->highspeed)
501                                 continue;
502                 } else {
503                         if (!c->fullspeed)
504                                 continue;
505                 }
506                 count++;
507         }
508         return count;
509 }
510
511 /**
512  * bos_desc() - prepares the BOS descriptor.
513  * @cdev: pointer to usb_composite device to generate the bos
514  *      descriptor for
515  *
516  * This function generates the BOS (Binary Device Object)
517  * descriptor and its device capabilities descriptors. The BOS
518  * descriptor should be supported by a SuperSpeed device.
519  */
520 static int bos_desc(struct usb_composite_dev *cdev)
521 {
522         struct usb_ext_cap_descriptor   *usb_ext;
523         struct usb_ss_cap_descriptor    *ss_cap;
524         struct usb_dcd_config_params    dcd_config_params;
525         struct usb_bos_descriptor       *bos = cdev->req->buf;
526
527         bos->bLength = USB_DT_BOS_SIZE;
528         bos->bDescriptorType = USB_DT_BOS;
529
530         bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
531         bos->bNumDeviceCaps = 0;
532
533         /*
534          * A SuperSpeed device shall include the USB2.0 extension descriptor
535          * and shall support LPM when operating in USB2.0 HS mode.
536          */
537         usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
538         bos->bNumDeviceCaps++;
539         le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
540         usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
541         usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
542         usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
543         usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT);
544
545         /*
546          * The Superspeed USB Capability descriptor shall be implemented by all
547          * SuperSpeed devices.
548          */
549         ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
550         bos->bNumDeviceCaps++;
551         le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
552         ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
553         ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
554         ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
555         ss_cap->bmAttributes = 0; /* LTM is not supported yet */
556         ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
557                                 USB_FULL_SPEED_OPERATION |
558                                 USB_HIGH_SPEED_OPERATION |
559                                 USB_5GBPS_OPERATION);
560         ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
561
562         /* Get Controller configuration */
563         if (cdev->gadget->ops->get_config_params)
564                 cdev->gadget->ops->get_config_params(&dcd_config_params);
565         else {
566                 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
567                 dcd_config_params.bU2DevExitLat =
568                         cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
569         }
570         ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
571         ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
572
573         return le16_to_cpu(bos->wTotalLength);
574 }
575
576 static void device_qual(struct usb_composite_dev *cdev)
577 {
578         struct usb_qualifier_descriptor *qual = cdev->req->buf;
579
580         qual->bLength = sizeof(*qual);
581         qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
582         /* POLICY: same bcdUSB and device type info at both speeds */
583         qual->bcdUSB = cdev->desc.bcdUSB;
584         qual->bDeviceClass = cdev->desc.bDeviceClass;
585         qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
586         qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
587         /* ASSUME same EP0 fifo size at both speeds */
588         qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
589         qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
590         qual->bRESERVED = 0;
591 }
592
593 /*-------------------------------------------------------------------------*/
594
595 static void reset_config(struct usb_composite_dev *cdev)
596 {
597         struct usb_function             *f;
598
599         DBG(cdev, "reset config\n");
600
601         list_for_each_entry(f, &cdev->config->functions, list) {
602                 if (f->disable)
603                         f->disable(f);
604
605                 bitmap_zero(f->endpoints, 32);
606         }
607         cdev->config = NULL;
608         cdev->delayed_status = 0;
609 }
610
611 static int set_config(struct usb_composite_dev *cdev,
612                 const struct usb_ctrlrequest *ctrl, unsigned number)
613 {
614         struct usb_gadget       *gadget = cdev->gadget;
615         struct usb_configuration *c = NULL;
616         int                     result = -EINVAL;
617         unsigned                power = gadget_is_otg(gadget) ? 8 : 100;
618         int                     tmp;
619
620         if (number) {
621                 list_for_each_entry(c, &cdev->configs, list) {
622                         if (c->bConfigurationValue == number) {
623                                 /*
624                                  * We disable the FDs of the previous
625                                  * configuration only if the new configuration
626                                  * is a valid one
627                                  */
628                                 if (cdev->config)
629                                         reset_config(cdev);
630                                 result = 0;
631                                 break;
632                         }
633                 }
634                 if (result < 0)
635                         goto done;
636         } else { /* Zero configuration value - need to reset the config */
637                 if (cdev->config)
638                         reset_config(cdev);
639                 result = 0;
640         }
641
642         INFO(cdev, "%s config #%d: %s\n",
643              usb_speed_string(gadget->speed),
644              number, c ? c->label : "unconfigured");
645
646         if (!c)
647                 goto done;
648
649         cdev->config = c;
650
651         /* Initialize all interfaces by setting them to altsetting zero. */
652         for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
653                 struct usb_function     *f = c->interface[tmp];
654                 struct usb_descriptor_header **descriptors;
655
656                 if (!f)
657                         break;
658
659                 /*
660                  * Record which endpoints are used by the function. This is used
661                  * to dispatch control requests targeted at that endpoint to the
662                  * function's setup callback instead of the current
663                  * configuration's setup callback.
664                  */
665                 switch (gadget->speed) {
666                 case USB_SPEED_SUPER:
667                         descriptors = f->ss_descriptors;
668                         break;
669                 case USB_SPEED_HIGH:
670                         descriptors = f->hs_descriptors;
671                         break;
672                 default:
673                         descriptors = f->fs_descriptors;
674                 }
675
676                 for (; *descriptors; ++descriptors) {
677                         struct usb_endpoint_descriptor *ep;
678                         int addr;
679
680                         if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
681                                 continue;
682
683                         ep = (struct usb_endpoint_descriptor *)*descriptors;
684                         addr = ((ep->bEndpointAddress & 0x80) >> 3)
685                              |  (ep->bEndpointAddress & 0x0f);
686                         set_bit(addr, f->endpoints);
687                 }
688
689                 result = f->set_alt(f, tmp, 0);
690                 if (result < 0) {
691                         DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
692                                         tmp, f->name, f, result);
693
694                         reset_config(cdev);
695                         goto done;
696                 }
697
698                 if (result == USB_GADGET_DELAYED_STATUS) {
699                         DBG(cdev,
700                          "%s: interface %d (%s) requested delayed status\n",
701                                         __func__, tmp, f->name);
702                         cdev->delayed_status++;
703                         DBG(cdev, "delayed_status count %d\n",
704                                         cdev->delayed_status);
705                 }
706         }
707
708         /* when we return, be sure our power usage is valid */
709         power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
710 done:
711         usb_gadget_vbus_draw(gadget, power);
712         if (result >= 0 && cdev->delayed_status)
713                 result = USB_GADGET_DELAYED_STATUS;
714         return result;
715 }
716
717 int usb_add_config_only(struct usb_composite_dev *cdev,
718                 struct usb_configuration *config)
719 {
720         struct usb_configuration *c;
721
722         if (!config->bConfigurationValue)
723                 return -EINVAL;
724
725         /* Prevent duplicate configuration identifiers */
726         list_for_each_entry(c, &cdev->configs, list) {
727                 if (c->bConfigurationValue == config->bConfigurationValue)
728                         return -EBUSY;
729         }
730
731         config->cdev = cdev;
732         list_add_tail(&config->list, &cdev->configs);
733
734         INIT_LIST_HEAD(&config->functions);
735         config->next_interface_id = 0;
736         memset(config->interface, 0, sizeof(config->interface));
737
738         return 0;
739 }
740 EXPORT_SYMBOL_GPL(usb_add_config_only);
741
742 /**
743  * usb_add_config() - add a configuration to a device.
744  * @cdev: wraps the USB gadget
745  * @config: the configuration, with bConfigurationValue assigned
746  * @bind: the configuration's bind function
747  * Context: single threaded during gadget setup
748  *
749  * One of the main tasks of a composite @bind() routine is to
750  * add each of the configurations it supports, using this routine.
751  *
752  * This function returns the value of the configuration's @bind(), which
753  * is zero for success else a negative errno value.  Binding configurations
754  * assigns global resources including string IDs, and per-configuration
755  * resources such as interface IDs and endpoints.
756  */
757 int usb_add_config(struct usb_composite_dev *cdev,
758                 struct usb_configuration *config,
759                 int (*bind)(struct usb_configuration *))
760 {
761         int                             status = -EINVAL;
762
763         if (!bind)
764                 goto done;
765
766         DBG(cdev, "adding config #%u '%s'/%p\n",
767                         config->bConfigurationValue,
768                         config->label, config);
769
770         status = usb_add_config_only(cdev, config);
771         if (status)
772                 goto done;
773
774         status = bind(config);
775         if (status < 0) {
776                 while (!list_empty(&config->functions)) {
777                         struct usb_function             *f;
778
779                         f = list_first_entry(&config->functions,
780                                         struct usb_function, list);
781                         list_del(&f->list);
782                         if (f->unbind) {
783                                 DBG(cdev, "unbind function '%s'/%p\n",
784                                         f->name, f);
785                                 f->unbind(config, f);
786                                 /* may free memory for "f" */
787                         }
788                 }
789                 list_del(&config->list);
790                 config->cdev = NULL;
791         } else {
792                 unsigned        i;
793
794                 DBG(cdev, "cfg %d/%p speeds:%s%s%s\n",
795                         config->bConfigurationValue, config,
796                         config->superspeed ? " super" : "",
797                         config->highspeed ? " high" : "",
798                         config->fullspeed
799                                 ? (gadget_is_dualspeed(cdev->gadget)
800                                         ? " full"
801                                         : " full/low")
802                                 : "");
803
804                 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
805                         struct usb_function     *f = config->interface[i];
806
807                         if (!f)
808                                 continue;
809                         DBG(cdev, "  interface %d = %s/%p\n",
810                                 i, f->name, f);
811                 }
812         }
813
814         /* set_alt(), or next bind(), sets up
815          * ep->driver_data as needed.
816          */
817         usb_ep_autoconfig_reset(cdev->gadget);
818
819 done:
820         if (status)
821                 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
822                                 config->bConfigurationValue, status);
823         return status;
824 }
825 EXPORT_SYMBOL_GPL(usb_add_config);
826
827 static void unbind_config(struct usb_composite_dev *cdev,
828                               struct usb_configuration *config)
829 {
830         while (!list_empty(&config->functions)) {
831                 struct usb_function             *f;
832
833                 f = list_first_entry(&config->functions,
834                                 struct usb_function, list);
835                 list_del(&f->list);
836                 if (f->unbind) {
837                         DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
838                         f->unbind(config, f);
839                         /* may free memory for "f" */
840                 }
841         }
842         if (config->unbind) {
843                 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
844                 config->unbind(config);
845                         /* may free memory for "c" */
846         }
847 }
848
849 /**
850  * usb_remove_config() - remove a configuration from a device.
851  * @cdev: wraps the USB gadget
852  * @config: the configuration
853  *
854  * Drivers must call usb_gadget_disconnect before calling this function
855  * to disconnect the device from the host and make sure the host will not
856  * try to enumerate the device while we are changing the config list.
857  */
858 void usb_remove_config(struct usb_composite_dev *cdev,
859                       struct usb_configuration *config)
860 {
861         unsigned long flags;
862
863         spin_lock_irqsave(&cdev->lock, flags);
864
865         if (cdev->config == config)
866                 reset_config(cdev);
867
868         list_del(&config->list);
869
870         spin_unlock_irqrestore(&cdev->lock, flags);
871
872         unbind_config(cdev, config);
873 }
874
875 /*-------------------------------------------------------------------------*/
876
877 /* We support strings in multiple languages ... string descriptor zero
878  * says which languages are supported.  The typical case will be that
879  * only one language (probably English) is used, with I18N handled on
880  * the host side.
881  */
882
883 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
884 {
885         const struct usb_gadget_strings *s;
886         __le16                          language;
887         __le16                          *tmp;
888
889         while (*sp) {
890                 s = *sp;
891                 language = cpu_to_le16(s->language);
892                 for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
893                         if (*tmp == language)
894                                 goto repeat;
895                 }
896                 *tmp++ = language;
897 repeat:
898                 sp++;
899         }
900 }
901
902 static int lookup_string(
903         struct usb_gadget_strings       **sp,
904         void                            *buf,
905         u16                             language,
906         int                             id
907 )
908 {
909         struct usb_gadget_strings       *s;
910         int                             value;
911
912         while (*sp) {
913                 s = *sp++;
914                 if (s->language != language)
915                         continue;
916                 value = usb_gadget_get_string(s, id, buf);
917                 if (value > 0)
918                         return value;
919         }
920         return -EINVAL;
921 }
922
923 static int get_string(struct usb_composite_dev *cdev,
924                 void *buf, u16 language, int id)
925 {
926         struct usb_composite_driver     *composite = cdev->driver;
927         struct usb_gadget_string_container *uc;
928         struct usb_configuration        *c;
929         struct usb_function             *f;
930         int                             len;
931
932         /* Yes, not only is USB's I18N support probably more than most
933          * folk will ever care about ... also, it's all supported here.
934          * (Except for UTF8 support for Unicode's "Astral Planes".)
935          */
936
937         /* 0 == report all available language codes */
938         if (id == 0) {
939                 struct usb_string_descriptor    *s = buf;
940                 struct usb_gadget_strings       **sp;
941
942                 memset(s, 0, 256);
943                 s->bDescriptorType = USB_DT_STRING;
944
945                 sp = composite->strings;
946                 if (sp)
947                         collect_langs(sp, s->wData);
948
949                 list_for_each_entry(c, &cdev->configs, list) {
950                         sp = c->strings;
951                         if (sp)
952                                 collect_langs(sp, s->wData);
953
954                         list_for_each_entry(f, &c->functions, list) {
955                                 sp = f->strings;
956                                 if (sp)
957                                         collect_langs(sp, s->wData);
958                         }
959                 }
960                 list_for_each_entry(uc, &cdev->gstrings, list) {
961                         struct usb_gadget_strings **sp;
962
963                         sp = get_containers_gs(uc);
964                         collect_langs(sp, s->wData);
965                 }
966
967                 for (len = 0; len <= 126 && s->wData[len]; len++)
968                         continue;
969                 if (!len)
970                         return -EINVAL;
971
972                 s->bLength = 2 * (len + 1);
973                 return s->bLength;
974         }
975
976         list_for_each_entry(uc, &cdev->gstrings, list) {
977                 struct usb_gadget_strings **sp;
978
979                 sp = get_containers_gs(uc);
980                 len = lookup_string(sp, buf, language, id);
981                 if (len > 0)
982                         return len;
983         }
984
985         /* String IDs are device-scoped, so we look up each string
986          * table we're told about.  These lookups are infrequent;
987          * simpler-is-better here.
988          */
989         if (composite->strings) {
990                 len = lookup_string(composite->strings, buf, language, id);
991                 if (len > 0)
992                         return len;
993         }
994         list_for_each_entry(c, &cdev->configs, list) {
995                 if (c->strings) {
996                         len = lookup_string(c->strings, buf, language, id);
997                         if (len > 0)
998                                 return len;
999                 }
1000                 list_for_each_entry(f, &c->functions, list) {
1001                         if (!f->strings)
1002                                 continue;
1003                         len = lookup_string(f->strings, buf, language, id);
1004                         if (len > 0)
1005                                 return len;
1006                 }
1007         }
1008         return -EINVAL;
1009 }
1010
1011 /**
1012  * usb_string_id() - allocate an unused string ID
1013  * @cdev: the device whose string descriptor IDs are being allocated
1014  * Context: single threaded during gadget setup
1015  *
1016  * @usb_string_id() is called from bind() callbacks to allocate
1017  * string IDs.  Drivers for functions, configurations, or gadgets will
1018  * then store that ID in the appropriate descriptors and string table.
1019  *
1020  * All string identifier should be allocated using this,
1021  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1022  * that for example different functions don't wrongly assign different
1023  * meanings to the same identifier.
1024  */
1025 int usb_string_id(struct usb_composite_dev *cdev)
1026 {
1027         if (cdev->next_string_id < 254) {
1028                 /* string id 0 is reserved by USB spec for list of
1029                  * supported languages */
1030                 /* 255 reserved as well? -- mina86 */
1031                 cdev->next_string_id++;
1032                 return cdev->next_string_id;
1033         }
1034         return -ENODEV;
1035 }
1036 EXPORT_SYMBOL_GPL(usb_string_id);
1037
1038 /**
1039  * usb_string_ids() - allocate unused string IDs in batch
1040  * @cdev: the device whose string descriptor IDs are being allocated
1041  * @str: an array of usb_string objects to assign numbers to
1042  * Context: single threaded during gadget setup
1043  *
1044  * @usb_string_ids() is called from bind() callbacks to allocate
1045  * string IDs.  Drivers for functions, configurations, or gadgets will
1046  * then copy IDs from the string table to the appropriate descriptors
1047  * and string table for other languages.
1048  *
1049  * All string identifier should be allocated using this,
1050  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1051  * example different functions don't wrongly assign different meanings
1052  * to the same identifier.
1053  */
1054 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1055 {
1056         int next = cdev->next_string_id;
1057
1058         for (; str->s; ++str) {
1059                 if (unlikely(next >= 254))
1060                         return -ENODEV;
1061                 str->id = ++next;
1062         }
1063
1064         cdev->next_string_id = next;
1065
1066         return 0;
1067 }
1068 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1069
1070 static struct usb_gadget_string_container *copy_gadget_strings(
1071                 struct usb_gadget_strings **sp, unsigned n_gstrings,
1072                 unsigned n_strings)
1073 {
1074         struct usb_gadget_string_container *uc;
1075         struct usb_gadget_strings **gs_array;
1076         struct usb_gadget_strings *gs;
1077         struct usb_string *s;
1078         unsigned mem;
1079         unsigned n_gs;
1080         unsigned n_s;
1081         void *stash;
1082
1083         mem = sizeof(*uc);
1084         mem += sizeof(void *) * (n_gstrings + 1);
1085         mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1086         mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1087         uc = kmalloc(mem, GFP_KERNEL);
1088         if (!uc)
1089                 return ERR_PTR(-ENOMEM);
1090         gs_array = get_containers_gs(uc);
1091         stash = uc->stash;
1092         stash += sizeof(void *) * (n_gstrings + 1);
1093         for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1094                 struct usb_string *org_s;
1095
1096                 gs_array[n_gs] = stash;
1097                 gs = gs_array[n_gs];
1098                 stash += sizeof(struct usb_gadget_strings);
1099                 gs->language = sp[n_gs]->language;
1100                 gs->strings = stash;
1101                 org_s = sp[n_gs]->strings;
1102
1103                 for (n_s = 0; n_s < n_strings; n_s++) {
1104                         s = stash;
1105                         stash += sizeof(struct usb_string);
1106                         if (org_s->s)
1107                                 s->s = org_s->s;
1108                         else
1109                                 s->s = "";
1110                         org_s++;
1111                 }
1112                 s = stash;
1113                 s->s = NULL;
1114                 stash += sizeof(struct usb_string);
1115
1116         }
1117         gs_array[n_gs] = NULL;
1118         return uc;
1119 }
1120
1121 /**
1122  * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1123  * @cdev: the device whose string descriptor IDs are being allocated
1124  * and attached.
1125  * @sp: an array of usb_gadget_strings to attach.
1126  * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1127  *
1128  * This function will create a deep copy of usb_gadget_strings and usb_string
1129  * and attach it to the cdev. The actual string (usb_string.s) will not be
1130  * copied but only a referenced will be made. The struct usb_gadget_strings
1131  * array may contain multiple languges and should be NULL terminated.
1132  * The ->language pointer of each struct usb_gadget_strings has to contain the
1133  * same amount of entries.
1134  * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1135  * usb_string entry of es-ES containts the translation of the first usb_string
1136  * entry of en-US. Therefore both entries become the same id assign.
1137  */
1138 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1139                 struct usb_gadget_strings **sp, unsigned n_strings)
1140 {
1141         struct usb_gadget_string_container *uc;
1142         struct usb_gadget_strings **n_gs;
1143         unsigned n_gstrings = 0;
1144         unsigned i;
1145         int ret;
1146
1147         for (i = 0; sp[i]; i++)
1148                 n_gstrings++;
1149
1150         if (!n_gstrings)
1151                 return ERR_PTR(-EINVAL);
1152
1153         uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1154         if (IS_ERR(uc))
1155                 return ERR_PTR(PTR_ERR(uc));
1156
1157         n_gs = get_containers_gs(uc);
1158         ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1159         if (ret)
1160                 goto err;
1161
1162         for (i = 1; i < n_gstrings; i++) {
1163                 struct usb_string *m_s;
1164                 struct usb_string *s;
1165                 unsigned n;
1166
1167                 m_s = n_gs[0]->strings;
1168                 s = n_gs[i]->strings;
1169                 for (n = 0; n < n_strings; n++) {
1170                         s->id = m_s->id;
1171                         s++;
1172                         m_s++;
1173                 }
1174         }
1175         list_add_tail(&uc->list, &cdev->gstrings);
1176         return n_gs[0]->strings;
1177 err:
1178         kfree(uc);
1179         return ERR_PTR(ret);
1180 }
1181 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1182
1183 /**
1184  * usb_string_ids_n() - allocate unused string IDs in batch
1185  * @c: the device whose string descriptor IDs are being allocated
1186  * @n: number of string IDs to allocate
1187  * Context: single threaded during gadget setup
1188  *
1189  * Returns the first requested ID.  This ID and next @n-1 IDs are now
1190  * valid IDs.  At least provided that @n is non-zero because if it
1191  * is, returns last requested ID which is now very useful information.
1192  *
1193  * @usb_string_ids_n() is called from bind() callbacks to allocate
1194  * string IDs.  Drivers for functions, configurations, or gadgets will
1195  * then store that ID in the appropriate descriptors and string table.
1196  *
1197  * All string identifier should be allocated using this,
1198  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1199  * example different functions don't wrongly assign different meanings
1200  * to the same identifier.
1201  */
1202 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1203 {
1204         unsigned next = c->next_string_id;
1205         if (unlikely(n > 254 || (unsigned)next + n > 254))
1206                 return -ENODEV;
1207         c->next_string_id += n;
1208         return next + 1;
1209 }
1210 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1211
1212 /*-------------------------------------------------------------------------*/
1213
1214 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1215 {
1216         if (req->status || req->actual != req->length)
1217                 DBG((struct usb_composite_dev *) ep->driver_data,
1218                                 "setup complete --> %d, %d/%d\n",
1219                                 req->status, req->actual, req->length);
1220 }
1221
1222 /*
1223  * The setup() callback implements all the ep0 functionality that's
1224  * not handled lower down, in hardware or the hardware driver(like
1225  * device and endpoint feature flags, and their status).  It's all
1226  * housekeeping for the gadget function we're implementing.  Most of
1227  * the work is in config and function specific setup.
1228  */
1229 int
1230 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1231 {
1232         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1233         struct usb_request              *req = cdev->req;
1234         int                             value = -EOPNOTSUPP;
1235         int                             status = 0;
1236         u16                             w_index = le16_to_cpu(ctrl->wIndex);
1237         u8                              intf = w_index & 0xFF;
1238         u16                             w_value = le16_to_cpu(ctrl->wValue);
1239         u16                             w_length = le16_to_cpu(ctrl->wLength);
1240         struct usb_function             *f = NULL;
1241         u8                              endp;
1242
1243         /* partial re-init of the response message; the function or the
1244          * gadget might need to intercept e.g. a control-OUT completion
1245          * when we delegate to it.
1246          */
1247         req->zero = 0;
1248         req->complete = composite_setup_complete;
1249         req->length = 0;
1250         gadget->ep0->driver_data = cdev;
1251
1252         switch (ctrl->bRequest) {
1253
1254         /* we handle all standard USB descriptors */
1255         case USB_REQ_GET_DESCRIPTOR:
1256                 if (ctrl->bRequestType != USB_DIR_IN)
1257                         goto unknown;
1258                 switch (w_value >> 8) {
1259
1260                 case USB_DT_DEVICE:
1261                         cdev->desc.bNumConfigurations =
1262                                 count_configs(cdev, USB_DT_DEVICE);
1263                         cdev->desc.bMaxPacketSize0 =
1264                                 cdev->gadget->ep0->maxpacket;
1265                         if (gadget_is_superspeed(gadget)) {
1266                                 if (gadget->speed >= USB_SPEED_SUPER) {
1267                                         cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1268                                         cdev->desc.bMaxPacketSize0 = 9;
1269                                 } else {
1270                                         cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1271                                 }
1272                         }
1273
1274                         value = min(w_length, (u16) sizeof cdev->desc);
1275                         memcpy(req->buf, &cdev->desc, value);
1276                         break;
1277                 case USB_DT_DEVICE_QUALIFIER:
1278                         if (!gadget_is_dualspeed(gadget) ||
1279                             gadget->speed >= USB_SPEED_SUPER)
1280                                 break;
1281                         device_qual(cdev);
1282                         value = min_t(int, w_length,
1283                                 sizeof(struct usb_qualifier_descriptor));
1284                         break;
1285                 case USB_DT_OTHER_SPEED_CONFIG:
1286                         if (!gadget_is_dualspeed(gadget) ||
1287                             gadget->speed >= USB_SPEED_SUPER)
1288                                 break;
1289                         /* FALLTHROUGH */
1290                 case USB_DT_CONFIG:
1291                         value = config_desc(cdev, w_value);
1292                         if (value >= 0)
1293                                 value = min(w_length, (u16) value);
1294                         break;
1295                 case USB_DT_STRING:
1296                         value = get_string(cdev, req->buf,
1297                                         w_index, w_value & 0xff);
1298                         if (value >= 0)
1299                                 value = min(w_length, (u16) value);
1300                         break;
1301                 case USB_DT_BOS:
1302                         if (gadget_is_superspeed(gadget)) {
1303                                 value = bos_desc(cdev);
1304                                 value = min(w_length, (u16) value);
1305                         }
1306                         break;
1307                 }
1308                 break;
1309
1310         /* any number of configs can work */
1311         case USB_REQ_SET_CONFIGURATION:
1312                 if (ctrl->bRequestType != 0)
1313                         goto unknown;
1314                 if (gadget_is_otg(gadget)) {
1315                         if (gadget->a_hnp_support)
1316                                 DBG(cdev, "HNP available\n");
1317                         else if (gadget->a_alt_hnp_support)
1318                                 DBG(cdev, "HNP on another port\n");
1319                         else
1320                                 VDBG(cdev, "HNP inactive\n");
1321                 }
1322                 spin_lock(&cdev->lock);
1323                 value = set_config(cdev, ctrl, w_value);
1324                 spin_unlock(&cdev->lock);
1325                 break;
1326         case USB_REQ_GET_CONFIGURATION:
1327                 if (ctrl->bRequestType != USB_DIR_IN)
1328                         goto unknown;
1329                 if (cdev->config)
1330                         *(u8 *)req->buf = cdev->config->bConfigurationValue;
1331                 else
1332                         *(u8 *)req->buf = 0;
1333                 value = min(w_length, (u16) 1);
1334                 break;
1335
1336         /* function drivers must handle get/set altsetting; if there's
1337          * no get() method, we know only altsetting zero works.
1338          */
1339         case USB_REQ_SET_INTERFACE:
1340                 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1341                         goto unknown;
1342                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1343                         break;
1344                 f = cdev->config->interface[intf];
1345                 if (!f)
1346                         break;
1347                 if (w_value && !f->set_alt)
1348                         break;
1349                 value = f->set_alt(f, w_index, w_value);
1350                 if (value == USB_GADGET_DELAYED_STATUS) {
1351                         DBG(cdev,
1352                          "%s: interface %d (%s) requested delayed status\n",
1353                                         __func__, intf, f->name);
1354                         cdev->delayed_status++;
1355                         DBG(cdev, "delayed_status count %d\n",
1356                                         cdev->delayed_status);
1357                 }
1358                 break;
1359         case USB_REQ_GET_INTERFACE:
1360                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1361                         goto unknown;
1362                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1363                         break;
1364                 f = cdev->config->interface[intf];
1365                 if (!f)
1366                         break;
1367                 /* lots of interfaces only need altsetting zero... */
1368                 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1369                 if (value < 0)
1370                         break;
1371                 *((u8 *)req->buf) = value;
1372                 value = min(w_length, (u16) 1);
1373                 break;
1374
1375         /*
1376          * USB 3.0 additions:
1377          * Function driver should handle get_status request. If such cb
1378          * wasn't supplied we respond with default value = 0
1379          * Note: function driver should supply such cb only for the first
1380          * interface of the function
1381          */
1382         case USB_REQ_GET_STATUS:
1383                 if (!gadget_is_superspeed(gadget))
1384                         goto unknown;
1385                 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1386                         goto unknown;
1387                 value = 2;      /* This is the length of the get_status reply */
1388                 put_unaligned_le16(0, req->buf);
1389                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1390                         break;
1391                 f = cdev->config->interface[intf];
1392                 if (!f)
1393                         break;
1394                 status = f->get_status ? f->get_status(f) : 0;
1395                 if (status < 0)
1396                         break;
1397                 put_unaligned_le16(status & 0x0000ffff, req->buf);
1398                 break;
1399         /*
1400          * Function drivers should handle SetFeature/ClearFeature
1401          * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1402          * only for the first interface of the function
1403          */
1404         case USB_REQ_CLEAR_FEATURE:
1405         case USB_REQ_SET_FEATURE:
1406                 if (!gadget_is_superspeed(gadget))
1407                         goto unknown;
1408                 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1409                         goto unknown;
1410                 switch (w_value) {
1411                 case USB_INTRF_FUNC_SUSPEND:
1412                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1413                                 break;
1414                         f = cdev->config->interface[intf];
1415                         if (!f)
1416                                 break;
1417                         value = 0;
1418                         if (f->func_suspend)
1419                                 value = f->func_suspend(f, w_index >> 8);
1420                         if (value < 0) {
1421                                 ERROR(cdev,
1422                                       "func_suspend() returned error %d\n",
1423                                       value);
1424                                 value = 0;
1425                         }
1426                         break;
1427                 }
1428                 break;
1429         default:
1430 unknown:
1431                 VDBG(cdev,
1432                         "non-core control req%02x.%02x v%04x i%04x l%d\n",
1433                         ctrl->bRequestType, ctrl->bRequest,
1434                         w_value, w_index, w_length);
1435
1436                 /* functions always handle their interfaces and endpoints...
1437                  * punt other recipients (other, WUSB, ...) to the current
1438                  * configuration code.
1439                  *
1440                  * REVISIT it could make sense to let the composite device
1441                  * take such requests too, if that's ever needed:  to work
1442                  * in config 0, etc.
1443                  */
1444                 switch (ctrl->bRequestType & USB_RECIP_MASK) {
1445                 case USB_RECIP_INTERFACE:
1446                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1447                                 break;
1448                         f = cdev->config->interface[intf];
1449                         break;
1450
1451                 case USB_RECIP_ENDPOINT:
1452                         endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1453                         list_for_each_entry(f, &cdev->config->functions, list) {
1454                                 if (test_bit(endp, f->endpoints))
1455                                         break;
1456                         }
1457                         if (&f->list == &cdev->config->functions)
1458                                 f = NULL;
1459                         break;
1460                 }
1461
1462                 if (f && f->setup)
1463                         value = f->setup(f, ctrl);
1464                 else {
1465                         struct usb_configuration        *c;
1466
1467                         c = cdev->config;
1468                         if (c && c->setup)
1469                                 value = c->setup(c, ctrl);
1470                 }
1471
1472                 /* If the vendor request is not processed (value < 0),
1473                  * call all device registered configure setup callbacks
1474                  * to process it.
1475                  * This is used to handle the following cases:
1476                  * - vendor request is for the device and arrives before
1477                  * setconfiguration.
1478                  * - Some devices are required to handle vendor request before
1479                  * setconfiguration such as MTP, USBNET.
1480                  */
1481
1482                 if (value < 0) {
1483                         struct usb_configuration        *cfg;
1484
1485                         list_for_each_entry(cfg, &cdev->configs, list) {
1486                         if (cfg && cfg->setup)
1487                                 value = cfg->setup(cfg, ctrl);
1488                         }
1489                 }
1490
1491                 goto done;
1492         }
1493
1494         /* respond with data transfer before status phase? */
1495         if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1496                 req->length = value;
1497                 req->zero = value < w_length;
1498                 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1499                 if (value < 0) {
1500                         DBG(cdev, "ep_queue --> %d\n", value);
1501                         req->status = 0;
1502                         composite_setup_complete(gadget->ep0, req);
1503                 }
1504         } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1505                 WARN(cdev,
1506                         "%s: Delayed status not supported for w_length != 0",
1507                         __func__);
1508         }
1509
1510 done:
1511         /* device either stalls (value < 0) or reports success */
1512         return value;
1513 }
1514
1515 void composite_disconnect(struct usb_gadget *gadget)
1516 {
1517         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1518         unsigned long                   flags;
1519
1520         /* REVISIT:  should we have config and device level
1521          * disconnect callbacks?
1522          */
1523         if (!cdev)
1524                 return;
1525
1526         spin_lock_irqsave(&cdev->lock, flags);
1527         if (cdev->config)
1528                 reset_config(cdev);
1529         if (cdev->driver->disconnect)
1530                 cdev->driver->disconnect(cdev);
1531         spin_unlock_irqrestore(&cdev->lock, flags);
1532 }
1533
1534 /*-------------------------------------------------------------------------*/
1535
1536 static ssize_t composite_show_suspended(struct device *dev,
1537                                         struct device_attribute *attr,
1538                                         char *buf)
1539 {
1540         struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1541         struct usb_composite_dev *cdev = get_gadget_data(gadget);
1542
1543         return sprintf(buf, "%d\n", cdev->suspended);
1544 }
1545
1546 static DEVICE_ATTR(suspended, 0444, composite_show_suspended, NULL);
1547
1548 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
1549 {
1550         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1551
1552         /* composite_disconnect() must already have been called
1553          * by the underlying peripheral controller driver!
1554          * so there's no i/o concurrency that could affect the
1555          * state protected by cdev->lock.
1556          */
1557         WARN_ON(cdev->config);
1558
1559         while (!list_empty(&cdev->configs)) {
1560                 struct usb_configuration        *c;
1561                 c = list_first_entry(&cdev->configs,
1562                                 struct usb_configuration, list);
1563                 list_del(&c->list);
1564                 unbind_config(cdev, c);
1565         }
1566         if (cdev->driver->unbind && unbind_driver)
1567                 cdev->driver->unbind(cdev);
1568
1569         composite_dev_cleanup(cdev);
1570
1571         kfree(cdev->def_manufacturer);
1572         kfree(cdev);
1573         set_gadget_data(gadget, NULL);
1574 }
1575
1576 static void composite_unbind(struct usb_gadget *gadget)
1577 {
1578         __composite_unbind(gadget, true);
1579 }
1580
1581 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
1582                 const struct usb_device_descriptor *old)
1583 {
1584         __le16 idVendor;
1585         __le16 idProduct;
1586         __le16 bcdDevice;
1587         u8 iSerialNumber;
1588         u8 iManufacturer;
1589         u8 iProduct;
1590
1591         /*
1592          * these variables may have been set in
1593          * usb_composite_overwrite_options()
1594          */
1595         idVendor = new->idVendor;
1596         idProduct = new->idProduct;
1597         bcdDevice = new->bcdDevice;
1598         iSerialNumber = new->iSerialNumber;
1599         iManufacturer = new->iManufacturer;
1600         iProduct = new->iProduct;
1601
1602         *new = *old;
1603         if (idVendor)
1604                 new->idVendor = idVendor;
1605         if (idProduct)
1606                 new->idProduct = idProduct;
1607         if (bcdDevice)
1608                 new->bcdDevice = bcdDevice;
1609         else
1610                 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
1611         if (iSerialNumber)
1612                 new->iSerialNumber = iSerialNumber;
1613         if (iManufacturer)
1614                 new->iManufacturer = iManufacturer;
1615         if (iProduct)
1616                 new->iProduct = iProduct;
1617 }
1618
1619 int composite_dev_prepare(struct usb_composite_driver *composite,
1620                 struct usb_composite_dev *cdev)
1621 {
1622         struct usb_gadget *gadget = cdev->gadget;
1623         int ret = -ENOMEM;
1624
1625         /* preallocate control response and buffer */
1626         cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1627         if (!cdev->req)
1628                 return -ENOMEM;
1629
1630         cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
1631         if (!cdev->req->buf)
1632                 goto fail;
1633
1634         ret = device_create_file(&gadget->dev, &dev_attr_suspended);
1635         if (ret)
1636                 goto fail_dev;
1637
1638         cdev->req->complete = composite_setup_complete;
1639         gadget->ep0->driver_data = cdev;
1640
1641         cdev->driver = composite;
1642
1643         /*
1644          * As per USB compliance update, a device that is actively drawing
1645          * more than 100mA from USB must report itself as bus-powered in
1646          * the GetStatus(DEVICE) call.
1647          */
1648         if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
1649                 usb_gadget_set_selfpowered(gadget);
1650
1651         /* interface and string IDs start at zero via kzalloc.
1652          * we force endpoints to start unassigned; few controller
1653          * drivers will zero ep->driver_data.
1654          */
1655         usb_ep_autoconfig_reset(gadget);
1656         return 0;
1657 fail_dev:
1658         kfree(cdev->req->buf);
1659 fail:
1660         usb_ep_free_request(gadget->ep0, cdev->req);
1661         cdev->req = NULL;
1662         return ret;
1663 }
1664
1665 void composite_dev_cleanup(struct usb_composite_dev *cdev)
1666 {
1667         struct usb_gadget_string_container *uc, *tmp;
1668
1669         list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
1670                 list_del(&uc->list);
1671                 kfree(uc);
1672         }
1673         if (cdev->req) {
1674                 kfree(cdev->req->buf);
1675                 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
1676         }
1677         cdev->next_string_id = 0;
1678         device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
1679 }
1680
1681 static int composite_bind(struct usb_gadget *gadget,
1682                 struct usb_gadget_driver *gdriver)
1683 {
1684         struct usb_composite_dev        *cdev;
1685         struct usb_composite_driver     *composite = to_cdriver(gdriver);
1686         int                             status = -ENOMEM;
1687
1688         cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
1689         if (!cdev)
1690                 return status;
1691
1692         spin_lock_init(&cdev->lock);
1693         cdev->gadget = gadget;
1694         set_gadget_data(gadget, cdev);
1695         INIT_LIST_HEAD(&cdev->configs);
1696         INIT_LIST_HEAD(&cdev->gstrings);
1697
1698         status = composite_dev_prepare(composite, cdev);
1699         if (status)
1700                 goto fail;
1701
1702         /* composite gadget needs to assign strings for whole device (like
1703          * serial number), register function drivers, potentially update
1704          * power state and consumption, etc
1705          */
1706         status = composite->bind(cdev);
1707         if (status < 0)
1708                 goto fail;
1709
1710         update_unchanged_dev_desc(&cdev->desc, composite->dev);
1711
1712         /* has userspace failed to provide a serial number? */
1713         if (composite->needs_serial && !cdev->desc.iSerialNumber)
1714                 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
1715
1716         INFO(cdev, "%s ready\n", composite->name);
1717         return 0;
1718
1719 fail:
1720         __composite_unbind(gadget, false);
1721         return status;
1722 }
1723
1724 /*-------------------------------------------------------------------------*/
1725
1726 static void
1727 composite_suspend(struct usb_gadget *gadget)
1728 {
1729         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1730         struct usb_function             *f;
1731
1732         /* REVISIT:  should we have config level
1733          * suspend/resume callbacks?
1734          */
1735         DBG(cdev, "suspend\n");
1736         if (cdev->config) {
1737                 list_for_each_entry(f, &cdev->config->functions, list) {
1738                         if (f->suspend)
1739                                 f->suspend(f);
1740                 }
1741         }
1742         if (cdev->driver->suspend)
1743                 cdev->driver->suspend(cdev);
1744
1745         cdev->suspended = 1;
1746
1747         usb_gadget_vbus_draw(gadget, 2);
1748 }
1749
1750 static void
1751 composite_resume(struct usb_gadget *gadget)
1752 {
1753         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1754         struct usb_function             *f;
1755         u8                              maxpower;
1756
1757         /* REVISIT:  should we have config level
1758          * suspend/resume callbacks?
1759          */
1760         DBG(cdev, "resume\n");
1761         if (cdev->driver->resume)
1762                 cdev->driver->resume(cdev);
1763         if (cdev->config) {
1764                 list_for_each_entry(f, &cdev->config->functions, list) {
1765                         if (f->resume)
1766                                 f->resume(f);
1767                 }
1768
1769                 maxpower = cdev->config->MaxPower;
1770
1771                 usb_gadget_vbus_draw(gadget, maxpower ?
1772                         maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
1773         }
1774
1775         cdev->suspended = 0;
1776 }
1777
1778 /*-------------------------------------------------------------------------*/
1779
1780 static const struct usb_gadget_driver composite_driver_template = {
1781         .bind           = composite_bind,
1782         .unbind         = composite_unbind,
1783
1784         .setup          = composite_setup,
1785         .disconnect     = composite_disconnect,
1786
1787         .suspend        = composite_suspend,
1788         .resume         = composite_resume,
1789
1790         .driver = {
1791                 .owner          = THIS_MODULE,
1792         },
1793 };
1794
1795 /**
1796  * usb_composite_probe() - register a composite driver
1797  * @driver: the driver to register
1798  *
1799  * Context: single threaded during gadget setup
1800  *
1801  * This function is used to register drivers using the composite driver
1802  * framework.  The return value is zero, or a negative errno value.
1803  * Those values normally come from the driver's @bind method, which does
1804  * all the work of setting up the driver to match the hardware.
1805  *
1806  * On successful return, the gadget is ready to respond to requests from
1807  * the host, unless one of its components invokes usb_gadget_disconnect()
1808  * while it was binding.  That would usually be done in order to wait for
1809  * some userspace participation.
1810  */
1811 int usb_composite_probe(struct usb_composite_driver *driver)
1812 {
1813         struct usb_gadget_driver *gadget_driver;
1814
1815         if (!driver || !driver->dev || !driver->bind)
1816                 return -EINVAL;
1817
1818         if (!driver->name)
1819                 driver->name = "composite";
1820
1821         driver->gadget_driver = composite_driver_template;
1822         gadget_driver = &driver->gadget_driver;
1823
1824         gadget_driver->function =  (char *) driver->name;
1825         gadget_driver->driver.name = driver->name;
1826         gadget_driver->max_speed = driver->max_speed;
1827
1828         return usb_gadget_probe_driver(gadget_driver);
1829 }
1830 EXPORT_SYMBOL_GPL(usb_composite_probe);
1831
1832 /**
1833  * usb_composite_unregister() - unregister a composite driver
1834  * @driver: the driver to unregister
1835  *
1836  * This function is used to unregister drivers using the composite
1837  * driver framework.
1838  */
1839 void usb_composite_unregister(struct usb_composite_driver *driver)
1840 {
1841         usb_gadget_unregister_driver(&driver->gadget_driver);
1842 }
1843 EXPORT_SYMBOL_GPL(usb_composite_unregister);
1844
1845 /**
1846  * usb_composite_setup_continue() - Continue with the control transfer
1847  * @cdev: the composite device who's control transfer was kept waiting
1848  *
1849  * This function must be called by the USB function driver to continue
1850  * with the control transfer's data/status stage in case it had requested to
1851  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
1852  * can request the composite framework to delay the setup request's data/status
1853  * stages by returning USB_GADGET_DELAYED_STATUS.
1854  */
1855 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
1856 {
1857         int                     value;
1858         struct usb_request      *req = cdev->req;
1859         unsigned long           flags;
1860
1861         DBG(cdev, "%s\n", __func__);
1862         spin_lock_irqsave(&cdev->lock, flags);
1863
1864         if (cdev->delayed_status == 0) {
1865                 WARN(cdev, "%s: Unexpected call\n", __func__);
1866
1867         } else if (--cdev->delayed_status == 0) {
1868                 DBG(cdev, "%s: Completing delayed status\n", __func__);
1869                 req->length = 0;
1870                 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1871                 if (value < 0) {
1872                         DBG(cdev, "ep_queue --> %d\n", value);
1873                         req->status = 0;
1874                         composite_setup_complete(cdev->gadget->ep0, req);
1875                 }
1876         }
1877
1878         spin_unlock_irqrestore(&cdev->lock, flags);
1879 }
1880 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
1881
1882 static char *composite_default_mfr(struct usb_gadget *gadget)
1883 {
1884         char *mfr;
1885         int len;
1886
1887         len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
1888                         init_utsname()->release, gadget->name);
1889         len++;
1890         mfr = kmalloc(len, GFP_KERNEL);
1891         if (!mfr)
1892                 return NULL;
1893         snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
1894                         init_utsname()->release, gadget->name);
1895         return mfr;
1896 }
1897
1898 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
1899                 struct usb_composite_overwrite *covr)
1900 {
1901         struct usb_device_descriptor    *desc = &cdev->desc;
1902         struct usb_gadget_strings       *gstr = cdev->driver->strings[0];
1903         struct usb_string               *dev_str = gstr->strings;
1904
1905         if (covr->idVendor)
1906                 desc->idVendor = cpu_to_le16(covr->idVendor);
1907
1908         if (covr->idProduct)
1909                 desc->idProduct = cpu_to_le16(covr->idProduct);
1910
1911         if (covr->bcdDevice)
1912                 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
1913
1914         if (covr->serial_number) {
1915                 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
1916                 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
1917         }
1918         if (covr->manufacturer) {
1919                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
1920                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
1921
1922         } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
1923                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
1924                 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
1925                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
1926         }
1927
1928         if (covr->product) {
1929                 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
1930                 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
1931         }
1932 }
1933 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
1934
1935 MODULE_LICENSE("GPL");
1936 MODULE_AUTHOR("David Brownell");