GNU Linux-libre 4.9.308-gnu1
[releases.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
12 /* #define VERBOSE_DEBUG */
13
14 #include <linux/kallsyms.h>
15 #include <linux/kernel.h>
16 #include <linux/slab.h>
17 #include <linux/module.h>
18 #include <linux/device.h>
19 #include <linux/utsname.h>
20
21 #include <linux/usb/composite.h>
22 #include <linux/usb/otg.h>
23 #include <asm/unaligned.h>
24
25 #include "u_os_desc.h"
26
27 /**
28  * struct usb_os_string - represents OS String to be reported by a gadget
29  * @bLength: total length of the entire descritor, always 0x12
30  * @bDescriptorType: USB_DT_STRING
31  * @qwSignature: the OS String proper
32  * @bMS_VendorCode: code used by the host for subsequent requests
33  * @bPad: not used, must be zero
34  */
35 struct usb_os_string {
36         __u8    bLength;
37         __u8    bDescriptorType;
38         __u8    qwSignature[OS_STRING_QW_SIGN_LEN];
39         __u8    bMS_VendorCode;
40         __u8    bPad;
41 } __packed;
42
43 /*
44  * The code in this file is utility code, used to build a gadget driver
45  * from one or more "function" drivers, one or more "configuration"
46  * objects, and a "usb_composite_driver" by gluing them together along
47  * with the relevant device-wide data.
48  */
49
50 static struct usb_gadget_strings **get_containers_gs(
51                 struct usb_gadget_string_container *uc)
52 {
53         return (struct usb_gadget_strings **)uc->stash;
54 }
55
56 /**
57  * function_descriptors() - get function descriptors for speed
58  * @f: the function
59  * @speed: the speed
60  *
61  * Returns the descriptors or NULL if not set.
62  */
63 static struct usb_descriptor_header **
64 function_descriptors(struct usb_function *f,
65                      enum usb_device_speed speed)
66 {
67         struct usb_descriptor_header **descriptors;
68
69         /*
70          * NOTE: we try to help gadget drivers which might not be setting
71          * max_speed appropriately.
72          */
73
74         switch (speed) {
75         case USB_SPEED_SUPER_PLUS:
76                 descriptors = f->ssp_descriptors;
77                 if (descriptors)
78                         break;
79                 /* FALLTHROUGH */
80         case USB_SPEED_SUPER:
81                 descriptors = f->ss_descriptors;
82                 if (descriptors)
83                         break;
84                 /* FALLTHROUGH */
85         case USB_SPEED_HIGH:
86                 descriptors = f->hs_descriptors;
87                 if (descriptors)
88                         break;
89                 /* FALLTHROUGH */
90         default:
91                 descriptors = f->fs_descriptors;
92         }
93
94         /*
95          * if we can't find any descriptors at all, then this gadget deserves to
96          * Oops with a NULL pointer dereference
97          */
98
99         return descriptors;
100 }
101
102 /**
103  * next_desc() - advance to the next desc_type descriptor
104  * @t: currect pointer within descriptor array
105  * @desc_type: descriptor type
106  *
107  * Return: next desc_type descriptor or NULL
108  *
109  * Iterate over @t until either desc_type descriptor found or
110  * NULL (that indicates end of list) encountered
111  */
112 static struct usb_descriptor_header**
113 next_desc(struct usb_descriptor_header **t, u8 desc_type)
114 {
115         for (; *t; t++) {
116                 if ((*t)->bDescriptorType == desc_type)
117                         return t;
118         }
119         return NULL;
120 }
121
122 /*
123  * for_each_desc() - iterate over desc_type descriptors in the
124  * descriptors list
125  * @start: pointer within descriptor array.
126  * @iter_desc: desc_type descriptor to use as the loop cursor
127  * @desc_type: wanted descriptr type
128  */
129 #define for_each_desc(start, iter_desc, desc_type) \
130         for (iter_desc = next_desc(start, desc_type); \
131              iter_desc; iter_desc = next_desc(iter_desc + 1, desc_type))
132
133 /**
134  * config_ep_by_speed_and_alt() - configures the given endpoint
135  * according to gadget speed.
136  * @g: pointer to the gadget
137  * @f: usb function
138  * @_ep: the endpoint to configure
139  * @alt: alternate setting number
140  *
141  * Return: error code, 0 on success
142  *
143  * This function chooses the right descriptors for a given
144  * endpoint according to gadget speed and saves it in the
145  * endpoint desc field. If the endpoint already has a descriptor
146  * assigned to it - overwrites it with currently corresponding
147  * descriptor. The endpoint maxpacket field is updated according
148  * to the chosen descriptor.
149  * Note: the supplied function should hold all the descriptors
150  * for supported speeds
151  */
152 int config_ep_by_speed_and_alt(struct usb_gadget *g,
153                                 struct usb_function *f,
154                                 struct usb_ep *_ep,
155                                 u8 alt)
156 {
157         struct usb_endpoint_descriptor *chosen_desc = NULL;
158         struct usb_interface_descriptor *int_desc = NULL;
159         struct usb_descriptor_header **speed_desc = NULL;
160
161         struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
162         int want_comp_desc = 0;
163
164         struct usb_descriptor_header **d_spd; /* cursor for speed desc */
165
166         if (!g || !f || !_ep)
167                 return -EIO;
168
169         /* select desired speed */
170         switch (g->speed) {
171         case USB_SPEED_SUPER_PLUS:
172                 if (gadget_is_superspeed_plus(g)) {
173                         speed_desc = f->ssp_descriptors;
174                         want_comp_desc = 1;
175                         break;
176                 }
177                 /* else: Fall trough */
178         case USB_SPEED_SUPER:
179                 if (gadget_is_superspeed(g)) {
180                         speed_desc = f->ss_descriptors;
181                         want_comp_desc = 1;
182                         break;
183                 }
184                 /* else: Fall trough */
185         case USB_SPEED_HIGH:
186                 if (gadget_is_dualspeed(g)) {
187                         speed_desc = f->hs_descriptors;
188                         break;
189                 }
190                 /* else: fall through */
191         default:
192                 speed_desc = f->fs_descriptors;
193         }
194
195         /* find correct alternate setting descriptor */
196         for_each_desc(speed_desc, d_spd, USB_DT_INTERFACE) {
197                 int_desc = (struct usb_interface_descriptor *)*d_spd;
198
199                 if (int_desc->bAlternateSetting == alt) {
200                         speed_desc = d_spd;
201                         goto intf_found;
202                 }
203         }
204         return -EIO;
205
206 intf_found:
207         /* find descriptors */
208         for_each_desc(speed_desc, d_spd, USB_DT_ENDPOINT) {
209                 chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
210                 if (chosen_desc->bEndpointAddress == _ep->address)
211                         goto ep_found;
212         }
213         return -EIO;
214
215 ep_found:
216         /* commit results */
217         _ep->maxpacket = usb_endpoint_maxp(chosen_desc) & 0x7ff;
218         _ep->desc = chosen_desc;
219         _ep->comp_desc = NULL;
220         _ep->maxburst = 0;
221         _ep->mult = 1;
222
223         if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
224                                 usb_endpoint_xfer_int(_ep->desc)))
225                 _ep->mult = ((usb_endpoint_maxp(_ep->desc) & 0x1800) >> 11) + 1;
226
227         if (!want_comp_desc)
228                 return 0;
229
230         /*
231          * Companion descriptor should follow EP descriptor
232          * USB 3.0 spec, #9.6.7
233          */
234         comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
235         if (!comp_desc ||
236             (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
237                 return -EIO;
238         _ep->comp_desc = comp_desc;
239         if (g->speed >= USB_SPEED_SUPER) {
240                 switch (usb_endpoint_type(_ep->desc)) {
241                 case USB_ENDPOINT_XFER_ISOC:
242                         /* mult: bits 1:0 of bmAttributes */
243                         _ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
244                 case USB_ENDPOINT_XFER_BULK:
245                 case USB_ENDPOINT_XFER_INT:
246                         _ep->maxburst = comp_desc->bMaxBurst + 1;
247                         break;
248                 default:
249                         if (comp_desc->bMaxBurst != 0) {
250                                 struct usb_composite_dev *cdev;
251
252                                 cdev = get_gadget_data(g);
253                                 ERROR(cdev, "ep0 bMaxBurst must be 0\n");
254                         }
255                         _ep->maxburst = 1;
256                         break;
257                 }
258         }
259         return 0;
260 }
261 EXPORT_SYMBOL_GPL(config_ep_by_speed_and_alt);
262
263 /**
264  * config_ep_by_speed() - configures the given endpoint
265  * according to gadget speed.
266  * @g: pointer to the gadget
267  * @f: usb function
268  * @_ep: the endpoint to configure
269  *
270  * Return: error code, 0 on success
271  *
272  * This function chooses the right descriptors for a given
273  * endpoint according to gadget speed and saves it in the
274  * endpoint desc field. If the endpoint already has a descriptor
275  * assigned to it - overwrites it with currently corresponding
276  * descriptor. The endpoint maxpacket field is updated according
277  * to the chosen descriptor.
278  * Note: the supplied function should hold all the descriptors
279  * for supported speeds
280  */
281 int config_ep_by_speed(struct usb_gadget *g,
282                         struct usb_function *f,
283                         struct usb_ep *_ep)
284 {
285         return config_ep_by_speed_and_alt(g, f, _ep, 0);
286 }
287 EXPORT_SYMBOL_GPL(config_ep_by_speed);
288
289 /**
290  * usb_add_function() - add a function to a configuration
291  * @config: the configuration
292  * @function: the function being added
293  * Context: single threaded during gadget setup
294  *
295  * After initialization, each configuration must have one or more
296  * functions added to it.  Adding a function involves calling its @bind()
297  * method to allocate resources such as interface and string identifiers
298  * and endpoints.
299  *
300  * This function returns the value of the function's bind(), which is
301  * zero for success else a negative errno value.
302  */
303 int usb_add_function(struct usb_configuration *config,
304                 struct usb_function *function)
305 {
306         int     value = -EINVAL;
307
308         DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
309                         function->name, function,
310                         config->label, config);
311
312         if (!function->set_alt || !function->disable)
313                 goto done;
314
315         function->config = config;
316         list_add_tail(&function->list, &config->functions);
317
318         if (function->bind_deactivated) {
319                 value = usb_function_deactivate(function);
320                 if (value)
321                         goto done;
322         }
323
324         /* REVISIT *require* function->bind? */
325         if (function->bind) {
326                 value = function->bind(config, function);
327                 if (value < 0) {
328                         list_del(&function->list);
329                         function->config = NULL;
330                 }
331         } else
332                 value = 0;
333
334         /* We allow configurations that don't work at both speeds.
335          * If we run into a lowspeed Linux system, treat it the same
336          * as full speed ... it's the function drivers that will need
337          * to avoid bulk and ISO transfers.
338          */
339         if (!config->fullspeed && function->fs_descriptors)
340                 config->fullspeed = true;
341         if (!config->highspeed && function->hs_descriptors)
342                 config->highspeed = true;
343         if (!config->superspeed && function->ss_descriptors)
344                 config->superspeed = true;
345         if (!config->superspeed_plus && function->ssp_descriptors)
346                 config->superspeed_plus = true;
347
348 done:
349         if (value)
350                 DBG(config->cdev, "adding '%s'/%p --> %d\n",
351                                 function->name, function, value);
352         return value;
353 }
354 EXPORT_SYMBOL_GPL(usb_add_function);
355
356 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
357 {
358         if (f->disable)
359                 f->disable(f);
360
361         bitmap_zero(f->endpoints, 32);
362         list_del(&f->list);
363         if (f->unbind)
364                 f->unbind(c, f);
365 }
366 EXPORT_SYMBOL_GPL(usb_remove_function);
367
368 /**
369  * usb_function_deactivate - prevent function and gadget enumeration
370  * @function: the function that isn't yet ready to respond
371  *
372  * Blocks response of the gadget driver to host enumeration by
373  * preventing the data line pullup from being activated.  This is
374  * normally called during @bind() processing to change from the
375  * initial "ready to respond" state, or when a required resource
376  * becomes available.
377  *
378  * For example, drivers that serve as a passthrough to a userspace
379  * daemon can block enumeration unless that daemon (such as an OBEX,
380  * MTP, or print server) is ready to handle host requests.
381  *
382  * Not all systems support software control of their USB peripheral
383  * data pullups.
384  *
385  * Returns zero on success, else negative errno.
386  */
387 int usb_function_deactivate(struct usb_function *function)
388 {
389         struct usb_composite_dev        *cdev = function->config->cdev;
390         unsigned long                   flags;
391         int                             status = 0;
392
393         spin_lock_irqsave(&cdev->lock, flags);
394
395         if (cdev->deactivations == 0) {
396                 spin_unlock_irqrestore(&cdev->lock, flags);
397                 status = usb_gadget_deactivate(cdev->gadget);
398                 spin_lock_irqsave(&cdev->lock, flags);
399         }
400         if (status == 0)
401                 cdev->deactivations++;
402
403         spin_unlock_irqrestore(&cdev->lock, flags);
404         return status;
405 }
406 EXPORT_SYMBOL_GPL(usb_function_deactivate);
407
408 /**
409  * usb_function_activate - allow function and gadget enumeration
410  * @function: function on which usb_function_activate() was called
411  *
412  * Reverses effect of usb_function_deactivate().  If no more functions
413  * are delaying their activation, the gadget driver will respond to
414  * host enumeration procedures.
415  *
416  * Returns zero on success, else negative errno.
417  */
418 int usb_function_activate(struct usb_function *function)
419 {
420         struct usb_composite_dev        *cdev = function->config->cdev;
421         unsigned long                   flags;
422         int                             status = 0;
423
424         spin_lock_irqsave(&cdev->lock, flags);
425
426         if (WARN_ON(cdev->deactivations == 0))
427                 status = -EINVAL;
428         else {
429                 cdev->deactivations--;
430                 if (cdev->deactivations == 0) {
431                         spin_unlock_irqrestore(&cdev->lock, flags);
432                         status = usb_gadget_activate(cdev->gadget);
433                         spin_lock_irqsave(&cdev->lock, flags);
434                 }
435         }
436
437         spin_unlock_irqrestore(&cdev->lock, flags);
438         return status;
439 }
440 EXPORT_SYMBOL_GPL(usb_function_activate);
441
442 /**
443  * usb_interface_id() - allocate an unused interface ID
444  * @config: configuration associated with the interface
445  * @function: function handling the interface
446  * Context: single threaded during gadget setup
447  *
448  * usb_interface_id() is called from usb_function.bind() callbacks to
449  * allocate new interface IDs.  The function driver will then store that
450  * ID in interface, association, CDC union, and other descriptors.  It
451  * will also handle any control requests targeted at that interface,
452  * particularly changing its altsetting via set_alt().  There may
453  * also be class-specific or vendor-specific requests to handle.
454  *
455  * All interface identifier should be allocated using this routine, to
456  * ensure that for example different functions don't wrongly assign
457  * different meanings to the same identifier.  Note that since interface
458  * identifiers are configuration-specific, functions used in more than
459  * one configuration (or more than once in a given configuration) need
460  * multiple versions of the relevant descriptors.
461  *
462  * Returns the interface ID which was allocated; or -ENODEV if no
463  * more interface IDs can be allocated.
464  */
465 int usb_interface_id(struct usb_configuration *config,
466                 struct usb_function *function)
467 {
468         unsigned id = config->next_interface_id;
469
470         if (id < MAX_CONFIG_INTERFACES) {
471                 config->interface[id] = function;
472                 config->next_interface_id = id + 1;
473                 return id;
474         }
475         return -ENODEV;
476 }
477 EXPORT_SYMBOL_GPL(usb_interface_id);
478
479 static u8 encode_bMaxPower(enum usb_device_speed speed,
480                 struct usb_configuration *c)
481 {
482         unsigned val;
483
484         if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
485                 val = c->MaxPower;
486         else
487                 val = CONFIG_USB_GADGET_VBUS_DRAW;
488         if (!val)
489                 return 0;
490         if (speed < USB_SPEED_SUPER)
491                 return min(val, 500U) / 2;
492         else
493                 /*
494                  * USB 3.x supports up to 900mA, but since 900 isn't divisible
495                  * by 8 the integral division will effectively cap to 896mA.
496                  */
497                 return min(val, 900U) / 8;
498 }
499
500 static int config_buf(struct usb_configuration *config,
501                 enum usb_device_speed speed, void *buf, u8 type)
502 {
503         struct usb_config_descriptor    *c = buf;
504         void                            *next = buf + USB_DT_CONFIG_SIZE;
505         int                             len;
506         struct usb_function             *f;
507         int                             status;
508
509         len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
510         /* write the config descriptor */
511         c = buf;
512         c->bLength = USB_DT_CONFIG_SIZE;
513         c->bDescriptorType = type;
514         /* wTotalLength is written later */
515         c->bNumInterfaces = config->next_interface_id;
516         c->bConfigurationValue = config->bConfigurationValue;
517         c->iConfiguration = config->iConfiguration;
518         c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
519         c->bMaxPower = encode_bMaxPower(speed, config);
520
521         /* There may be e.g. OTG descriptors */
522         if (config->descriptors) {
523                 status = usb_descriptor_fillbuf(next, len,
524                                 config->descriptors);
525                 if (status < 0)
526                         return status;
527                 len -= status;
528                 next += status;
529         }
530
531         /* add each function's descriptors */
532         list_for_each_entry(f, &config->functions, list) {
533                 struct usb_descriptor_header **descriptors;
534
535                 descriptors = function_descriptors(f, speed);
536                 if (!descriptors)
537                         continue;
538                 status = usb_descriptor_fillbuf(next, len,
539                         (const struct usb_descriptor_header **) descriptors);
540                 if (status < 0)
541                         return status;
542                 len -= status;
543                 next += status;
544         }
545
546         len = next - buf;
547         c->wTotalLength = cpu_to_le16(len);
548         return len;
549 }
550
551 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
552 {
553         struct usb_gadget               *gadget = cdev->gadget;
554         struct usb_configuration        *c;
555         struct list_head                *pos;
556         u8                              type = w_value >> 8;
557         enum usb_device_speed           speed = USB_SPEED_UNKNOWN;
558
559         if (gadget->speed >= USB_SPEED_SUPER)
560                 speed = gadget->speed;
561         else if (gadget_is_dualspeed(gadget)) {
562                 int     hs = 0;
563                 if (gadget->speed == USB_SPEED_HIGH)
564                         hs = 1;
565                 if (type == USB_DT_OTHER_SPEED_CONFIG)
566                         hs = !hs;
567                 if (hs)
568                         speed = USB_SPEED_HIGH;
569
570         }
571
572         /* This is a lookup by config *INDEX* */
573         w_value &= 0xff;
574
575         pos = &cdev->configs;
576         c = cdev->os_desc_config;
577         if (c)
578                 goto check_config;
579
580         while ((pos = pos->next) !=  &cdev->configs) {
581                 c = list_entry(pos, typeof(*c), list);
582
583                 /* skip OS Descriptors config which is handled separately */
584                 if (c == cdev->os_desc_config)
585                         continue;
586
587 check_config:
588                 /* ignore configs that won't work at this speed */
589                 switch (speed) {
590                 case USB_SPEED_SUPER_PLUS:
591                         if (!c->superspeed_plus)
592                                 continue;
593                         break;
594                 case USB_SPEED_SUPER:
595                         if (!c->superspeed)
596                                 continue;
597                         break;
598                 case USB_SPEED_HIGH:
599                         if (!c->highspeed)
600                                 continue;
601                         break;
602                 default:
603                         if (!c->fullspeed)
604                                 continue;
605                 }
606
607                 if (w_value == 0)
608                         return config_buf(c, speed, cdev->req->buf, type);
609                 w_value--;
610         }
611         return -EINVAL;
612 }
613
614 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
615 {
616         struct usb_gadget               *gadget = cdev->gadget;
617         struct usb_configuration        *c;
618         unsigned                        count = 0;
619         int                             hs = 0;
620         int                             ss = 0;
621         int                             ssp = 0;
622
623         if (gadget_is_dualspeed(gadget)) {
624                 if (gadget->speed == USB_SPEED_HIGH)
625                         hs = 1;
626                 if (gadget->speed == USB_SPEED_SUPER)
627                         ss = 1;
628                 if (gadget->speed == USB_SPEED_SUPER_PLUS)
629                         ssp = 1;
630                 if (type == USB_DT_DEVICE_QUALIFIER)
631                         hs = !hs;
632         }
633         list_for_each_entry(c, &cdev->configs, list) {
634                 /* ignore configs that won't work at this speed */
635                 if (ssp) {
636                         if (!c->superspeed_plus)
637                                 continue;
638                 } else if (ss) {
639                         if (!c->superspeed)
640                                 continue;
641                 } else if (hs) {
642                         if (!c->highspeed)
643                                 continue;
644                 } else {
645                         if (!c->fullspeed)
646                                 continue;
647                 }
648                 count++;
649         }
650         return count;
651 }
652
653 /**
654  * bos_desc() - prepares the BOS descriptor.
655  * @cdev: pointer to usb_composite device to generate the bos
656  *      descriptor for
657  *
658  * This function generates the BOS (Binary Device Object)
659  * descriptor and its device capabilities descriptors. The BOS
660  * descriptor should be supported by a SuperSpeed device.
661  */
662 static int bos_desc(struct usb_composite_dev *cdev)
663 {
664         struct usb_ext_cap_descriptor   *usb_ext;
665         struct usb_ss_cap_descriptor    *ss_cap;
666         struct usb_dcd_config_params    dcd_config_params;
667         struct usb_bos_descriptor       *bos = cdev->req->buf;
668
669         bos->bLength = USB_DT_BOS_SIZE;
670         bos->bDescriptorType = USB_DT_BOS;
671
672         bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
673         bos->bNumDeviceCaps = 0;
674
675         /*
676          * A SuperSpeed device shall include the USB2.0 extension descriptor
677          * and shall support LPM when operating in USB2.0 HS mode.
678          */
679         usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
680         bos->bNumDeviceCaps++;
681         le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
682         usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
683         usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
684         usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
685         usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
686
687         /*
688          * The Superspeed USB Capability descriptor shall be implemented by all
689          * SuperSpeed devices.
690          */
691         ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
692         bos->bNumDeviceCaps++;
693         le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
694         ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
695         ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
696         ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
697         ss_cap->bmAttributes = 0; /* LTM is not supported yet */
698         ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
699                                 USB_FULL_SPEED_OPERATION |
700                                 USB_HIGH_SPEED_OPERATION |
701                                 USB_5GBPS_OPERATION);
702         ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
703
704         /* Get Controller configuration */
705         if (cdev->gadget->ops->get_config_params)
706                 cdev->gadget->ops->get_config_params(&dcd_config_params);
707         else {
708                 dcd_config_params.bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
709                 dcd_config_params.bU2DevExitLat =
710                         cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
711         }
712         ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
713         ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
714
715         /* The SuperSpeedPlus USB Device Capability descriptor */
716         if (gadget_is_superspeed_plus(cdev->gadget)) {
717                 struct usb_ssp_cap_descriptor *ssp_cap;
718
719                 ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
720                 bos->bNumDeviceCaps++;
721
722                 /*
723                  * Report typical values.
724                  */
725
726                 le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
727                 ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
728                 ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
729                 ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
730                 ssp_cap->bReserved = 0;
731                 ssp_cap->wReserved = 0;
732
733                 /* SSAC = 1 (2 attributes) */
734                 ssp_cap->bmAttributes = cpu_to_le32(1);
735
736                 /* Min RX/TX Lane Count = 1 */
737                 ssp_cap->wFunctionalitySupport =
738                         cpu_to_le16((1 << 8) | (1 << 12));
739
740                 /*
741                  * bmSublinkSpeedAttr[0]:
742                  *   ST  = Symmetric, RX
743                  *   LSE =  3 (Gbps)
744                  *   LP  =  1 (SuperSpeedPlus)
745                  *   LSM = 10 (10 Gbps)
746                  */
747                 ssp_cap->bmSublinkSpeedAttr[0] =
748                         cpu_to_le32((3 << 4) | (1 << 14) | (0xa << 16));
749                 /*
750                  * bmSublinkSpeedAttr[1] =
751                  *   ST  = Symmetric, TX
752                  *   LSE =  3 (Gbps)
753                  *   LP  =  1 (SuperSpeedPlus)
754                  *   LSM = 10 (10 Gbps)
755                  */
756                 ssp_cap->bmSublinkSpeedAttr[1] =
757                         cpu_to_le32((3 << 4) | (1 << 14) |
758                                     (0xa << 16) | (1 << 7));
759         }
760
761         return le16_to_cpu(bos->wTotalLength);
762 }
763
764 static void device_qual(struct usb_composite_dev *cdev)
765 {
766         struct usb_qualifier_descriptor *qual = cdev->req->buf;
767
768         qual->bLength = sizeof(*qual);
769         qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
770         /* POLICY: same bcdUSB and device type info at both speeds */
771         qual->bcdUSB = cdev->desc.bcdUSB;
772         qual->bDeviceClass = cdev->desc.bDeviceClass;
773         qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
774         qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
775         /* ASSUME same EP0 fifo size at both speeds */
776         qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
777         qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
778         qual->bRESERVED = 0;
779 }
780
781 /*-------------------------------------------------------------------------*/
782
783 static void reset_config(struct usb_composite_dev *cdev)
784 {
785         struct usb_function             *f;
786
787         DBG(cdev, "reset config\n");
788
789         list_for_each_entry(f, &cdev->config->functions, list) {
790                 if (f->disable)
791                         f->disable(f);
792
793                 bitmap_zero(f->endpoints, 32);
794         }
795         cdev->config = NULL;
796         cdev->delayed_status = 0;
797 }
798
799 static int set_config(struct usb_composite_dev *cdev,
800                 const struct usb_ctrlrequest *ctrl, unsigned number)
801 {
802         struct usb_gadget       *gadget = cdev->gadget;
803         struct usb_configuration *c = NULL;
804         int                     result = -EINVAL;
805         unsigned                power = gadget_is_otg(gadget) ? 8 : 100;
806         int                     tmp;
807
808         if (number) {
809                 list_for_each_entry(c, &cdev->configs, list) {
810                         if (c->bConfigurationValue == number) {
811                                 /*
812                                  * We disable the FDs of the previous
813                                  * configuration only if the new configuration
814                                  * is a valid one
815                                  */
816                                 if (cdev->config)
817                                         reset_config(cdev);
818                                 result = 0;
819                                 break;
820                         }
821                 }
822                 if (result < 0)
823                         goto done;
824         } else { /* Zero configuration value - need to reset the config */
825                 if (cdev->config)
826                         reset_config(cdev);
827                 result = 0;
828         }
829
830         INFO(cdev, "%s config #%d: %s\n",
831              usb_speed_string(gadget->speed),
832              number, c ? c->label : "unconfigured");
833
834         if (!c)
835                 goto done;
836
837         usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
838         cdev->config = c;
839
840         /* Initialize all interfaces by setting them to altsetting zero. */
841         for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
842                 struct usb_function     *f = c->interface[tmp];
843                 struct usb_descriptor_header **descriptors;
844
845                 if (!f)
846                         break;
847
848                 /*
849                  * Record which endpoints are used by the function. This is used
850                  * to dispatch control requests targeted at that endpoint to the
851                  * function's setup callback instead of the current
852                  * configuration's setup callback.
853                  */
854                 descriptors = function_descriptors(f, gadget->speed);
855
856                 for (; *descriptors; ++descriptors) {
857                         struct usb_endpoint_descriptor *ep;
858                         int addr;
859
860                         if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
861                                 continue;
862
863                         ep = (struct usb_endpoint_descriptor *)*descriptors;
864                         addr = ((ep->bEndpointAddress & 0x80) >> 3)
865                              |  (ep->bEndpointAddress & 0x0f);
866                         set_bit(addr, f->endpoints);
867                 }
868
869                 result = f->set_alt(f, tmp, 0);
870                 if (result < 0) {
871                         DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
872                                         tmp, f->name, f, result);
873
874                         reset_config(cdev);
875                         goto done;
876                 }
877
878                 if (result == USB_GADGET_DELAYED_STATUS) {
879                         DBG(cdev,
880                          "%s: interface %d (%s) requested delayed status\n",
881                                         __func__, tmp, f->name);
882                         cdev->delayed_status++;
883                         DBG(cdev, "delayed_status count %d\n",
884                                         cdev->delayed_status);
885                 }
886         }
887
888         /* when we return, be sure our power usage is valid */
889         if (c->MaxPower || (c->bmAttributes & USB_CONFIG_ATT_SELFPOWER))
890                 power = c->MaxPower;
891         else
892                 power = CONFIG_USB_GADGET_VBUS_DRAW;
893
894         if (gadget->speed < USB_SPEED_SUPER)
895                 power = min(power, 500U);
896         else
897                 power = min(power, 900U);
898 done:
899         if (power <= USB_SELF_POWER_VBUS_MAX_DRAW)
900                 usb_gadget_set_selfpowered(gadget);
901         else
902                 usb_gadget_clear_selfpowered(gadget);
903
904         usb_gadget_vbus_draw(gadget, power);
905         if (result >= 0 && cdev->delayed_status)
906                 result = USB_GADGET_DELAYED_STATUS;
907         return result;
908 }
909
910 int usb_add_config_only(struct usb_composite_dev *cdev,
911                 struct usb_configuration *config)
912 {
913         struct usb_configuration *c;
914
915         if (!config->bConfigurationValue)
916                 return -EINVAL;
917
918         /* Prevent duplicate configuration identifiers */
919         list_for_each_entry(c, &cdev->configs, list) {
920                 if (c->bConfigurationValue == config->bConfigurationValue)
921                         return -EBUSY;
922         }
923
924         config->cdev = cdev;
925         list_add_tail(&config->list, &cdev->configs);
926
927         INIT_LIST_HEAD(&config->functions);
928         config->next_interface_id = 0;
929         memset(config->interface, 0, sizeof(config->interface));
930
931         return 0;
932 }
933 EXPORT_SYMBOL_GPL(usb_add_config_only);
934
935 /**
936  * usb_add_config() - add a configuration to a device.
937  * @cdev: wraps the USB gadget
938  * @config: the configuration, with bConfigurationValue assigned
939  * @bind: the configuration's bind function
940  * Context: single threaded during gadget setup
941  *
942  * One of the main tasks of a composite @bind() routine is to
943  * add each of the configurations it supports, using this routine.
944  *
945  * This function returns the value of the configuration's @bind(), which
946  * is zero for success else a negative errno value.  Binding configurations
947  * assigns global resources including string IDs, and per-configuration
948  * resources such as interface IDs and endpoints.
949  */
950 int usb_add_config(struct usb_composite_dev *cdev,
951                 struct usb_configuration *config,
952                 int (*bind)(struct usb_configuration *))
953 {
954         int                             status = -EINVAL;
955
956         if (!bind)
957                 goto done;
958
959         DBG(cdev, "adding config #%u '%s'/%p\n",
960                         config->bConfigurationValue,
961                         config->label, config);
962
963         status = usb_add_config_only(cdev, config);
964         if (status)
965                 goto done;
966
967         status = bind(config);
968         if (status < 0) {
969                 while (!list_empty(&config->functions)) {
970                         struct usb_function             *f;
971
972                         f = list_first_entry(&config->functions,
973                                         struct usb_function, list);
974                         list_del(&f->list);
975                         if (f->unbind) {
976                                 DBG(cdev, "unbind function '%s'/%p\n",
977                                         f->name, f);
978                                 f->unbind(config, f);
979                                 /* may free memory for "f" */
980                         }
981                 }
982                 list_del(&config->list);
983                 config->cdev = NULL;
984         } else {
985                 unsigned        i;
986
987                 DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
988                         config->bConfigurationValue, config,
989                         config->superspeed_plus ? " superplus" : "",
990                         config->superspeed ? " super" : "",
991                         config->highspeed ? " high" : "",
992                         config->fullspeed
993                                 ? (gadget_is_dualspeed(cdev->gadget)
994                                         ? " full"
995                                         : " full/low")
996                                 : "");
997
998                 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
999                         struct usb_function     *f = config->interface[i];
1000
1001                         if (!f)
1002                                 continue;
1003                         DBG(cdev, "  interface %d = %s/%p\n",
1004                                 i, f->name, f);
1005                 }
1006         }
1007
1008         /* set_alt(), or next bind(), sets up ep->claimed as needed */
1009         usb_ep_autoconfig_reset(cdev->gadget);
1010
1011 done:
1012         if (status)
1013                 DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1014                                 config->bConfigurationValue, status);
1015         return status;
1016 }
1017 EXPORT_SYMBOL_GPL(usb_add_config);
1018
1019 static void remove_config(struct usb_composite_dev *cdev,
1020                               struct usb_configuration *config)
1021 {
1022         while (!list_empty(&config->functions)) {
1023                 struct usb_function             *f;
1024
1025                 f = list_first_entry(&config->functions,
1026                                 struct usb_function, list);
1027                 list_del(&f->list);
1028                 if (f->unbind) {
1029                         DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
1030                         f->unbind(config, f);
1031                         /* may free memory for "f" */
1032                 }
1033         }
1034         list_del(&config->list);
1035         if (config->unbind) {
1036                 DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
1037                 config->unbind(config);
1038                         /* may free memory for "c" */
1039         }
1040 }
1041
1042 /**
1043  * usb_remove_config() - remove a configuration from a device.
1044  * @cdev: wraps the USB gadget
1045  * @config: the configuration
1046  *
1047  * Drivers must call usb_gadget_disconnect before calling this function
1048  * to disconnect the device from the host and make sure the host will not
1049  * try to enumerate the device while we are changing the config list.
1050  */
1051 void usb_remove_config(struct usb_composite_dev *cdev,
1052                       struct usb_configuration *config)
1053 {
1054         unsigned long flags;
1055
1056         spin_lock_irqsave(&cdev->lock, flags);
1057
1058         if (cdev->config == config)
1059                 reset_config(cdev);
1060
1061         spin_unlock_irqrestore(&cdev->lock, flags);
1062
1063         remove_config(cdev, config);
1064 }
1065
1066 /*-------------------------------------------------------------------------*/
1067
1068 /* We support strings in multiple languages ... string descriptor zero
1069  * says which languages are supported.  The typical case will be that
1070  * only one language (probably English) is used, with i18n handled on
1071  * the host side.
1072  */
1073
1074 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1075 {
1076         const struct usb_gadget_strings *s;
1077         __le16                          language;
1078         __le16                          *tmp;
1079
1080         while (*sp) {
1081                 s = *sp;
1082                 language = cpu_to_le16(s->language);
1083                 for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
1084                         if (*tmp == language)
1085                                 goto repeat;
1086                 }
1087                 *tmp++ = language;
1088 repeat:
1089                 sp++;
1090         }
1091 }
1092
1093 static int lookup_string(
1094         struct usb_gadget_strings       **sp,
1095         void                            *buf,
1096         u16                             language,
1097         int                             id
1098 )
1099 {
1100         struct usb_gadget_strings       *s;
1101         int                             value;
1102
1103         while (*sp) {
1104                 s = *sp++;
1105                 if (s->language != language)
1106                         continue;
1107                 value = usb_gadget_get_string(s, id, buf);
1108                 if (value > 0)
1109                         return value;
1110         }
1111         return -EINVAL;
1112 }
1113
1114 static int get_string(struct usb_composite_dev *cdev,
1115                 void *buf, u16 language, int id)
1116 {
1117         struct usb_composite_driver     *composite = cdev->driver;
1118         struct usb_gadget_string_container *uc;
1119         struct usb_configuration        *c;
1120         struct usb_function             *f;
1121         int                             len;
1122
1123         /* Yes, not only is USB's i18n support probably more than most
1124          * folk will ever care about ... also, it's all supported here.
1125          * (Except for UTF8 support for Unicode's "Astral Planes".)
1126          */
1127
1128         /* 0 == report all available language codes */
1129         if (id == 0) {
1130                 struct usb_string_descriptor    *s = buf;
1131                 struct usb_gadget_strings       **sp;
1132
1133                 memset(s, 0, 256);
1134                 s->bDescriptorType = USB_DT_STRING;
1135
1136                 sp = composite->strings;
1137                 if (sp)
1138                         collect_langs(sp, s->wData);
1139
1140                 list_for_each_entry(c, &cdev->configs, list) {
1141                         sp = c->strings;
1142                         if (sp)
1143                                 collect_langs(sp, s->wData);
1144
1145                         list_for_each_entry(f, &c->functions, list) {
1146                                 sp = f->strings;
1147                                 if (sp)
1148                                         collect_langs(sp, s->wData);
1149                         }
1150                 }
1151                 list_for_each_entry(uc, &cdev->gstrings, list) {
1152                         struct usb_gadget_strings **sp;
1153
1154                         sp = get_containers_gs(uc);
1155                         collect_langs(sp, s->wData);
1156                 }
1157
1158                 for (len = 0; len <= USB_MAX_STRING_LEN && s->wData[len]; len++)
1159                         continue;
1160                 if (!len)
1161                         return -EINVAL;
1162
1163                 s->bLength = 2 * (len + 1);
1164                 return s->bLength;
1165         }
1166
1167         if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1168                 struct usb_os_string *b = buf;
1169                 b->bLength = sizeof(*b);
1170                 b->bDescriptorType = USB_DT_STRING;
1171                 compiletime_assert(
1172                         sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1173                         "qwSignature size must be equal to qw_sign");
1174                 memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1175                 b->bMS_VendorCode = cdev->b_vendor_code;
1176                 b->bPad = 0;
1177                 return sizeof(*b);
1178         }
1179
1180         list_for_each_entry(uc, &cdev->gstrings, list) {
1181                 struct usb_gadget_strings **sp;
1182
1183                 sp = get_containers_gs(uc);
1184                 len = lookup_string(sp, buf, language, id);
1185                 if (len > 0)
1186                         return len;
1187         }
1188
1189         /* String IDs are device-scoped, so we look up each string
1190          * table we're told about.  These lookups are infrequent;
1191          * simpler-is-better here.
1192          */
1193         if (composite->strings) {
1194                 len = lookup_string(composite->strings, buf, language, id);
1195                 if (len > 0)
1196                         return len;
1197         }
1198         list_for_each_entry(c, &cdev->configs, list) {
1199                 if (c->strings) {
1200                         len = lookup_string(c->strings, buf, language, id);
1201                         if (len > 0)
1202                                 return len;
1203                 }
1204                 list_for_each_entry(f, &c->functions, list) {
1205                         if (!f->strings)
1206                                 continue;
1207                         len = lookup_string(f->strings, buf, language, id);
1208                         if (len > 0)
1209                                 return len;
1210                 }
1211         }
1212         return -EINVAL;
1213 }
1214
1215 /**
1216  * usb_string_id() - allocate an unused string ID
1217  * @cdev: the device whose string descriptor IDs are being allocated
1218  * Context: single threaded during gadget setup
1219  *
1220  * @usb_string_id() is called from bind() callbacks to allocate
1221  * string IDs.  Drivers for functions, configurations, or gadgets will
1222  * then store that ID in the appropriate descriptors and string table.
1223  *
1224  * All string identifier should be allocated using this,
1225  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1226  * that for example different functions don't wrongly assign different
1227  * meanings to the same identifier.
1228  */
1229 int usb_string_id(struct usb_composite_dev *cdev)
1230 {
1231         if (cdev->next_string_id < 254) {
1232                 /* string id 0 is reserved by USB spec for list of
1233                  * supported languages */
1234                 /* 255 reserved as well? -- mina86 */
1235                 cdev->next_string_id++;
1236                 return cdev->next_string_id;
1237         }
1238         return -ENODEV;
1239 }
1240 EXPORT_SYMBOL_GPL(usb_string_id);
1241
1242 /**
1243  * usb_string_ids() - allocate unused string IDs in batch
1244  * @cdev: the device whose string descriptor IDs are being allocated
1245  * @str: an array of usb_string objects to assign numbers to
1246  * Context: single threaded during gadget setup
1247  *
1248  * @usb_string_ids() is called from bind() callbacks to allocate
1249  * string IDs.  Drivers for functions, configurations, or gadgets will
1250  * then copy IDs from the string table to the appropriate descriptors
1251  * and string table for other languages.
1252  *
1253  * All string identifier should be allocated using this,
1254  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1255  * example different functions don't wrongly assign different meanings
1256  * to the same identifier.
1257  */
1258 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1259 {
1260         int next = cdev->next_string_id;
1261
1262         for (; str->s; ++str) {
1263                 if (unlikely(next >= 254))
1264                         return -ENODEV;
1265                 str->id = ++next;
1266         }
1267
1268         cdev->next_string_id = next;
1269
1270         return 0;
1271 }
1272 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1273
1274 static struct usb_gadget_string_container *copy_gadget_strings(
1275                 struct usb_gadget_strings **sp, unsigned n_gstrings,
1276                 unsigned n_strings)
1277 {
1278         struct usb_gadget_string_container *uc;
1279         struct usb_gadget_strings **gs_array;
1280         struct usb_gadget_strings *gs;
1281         struct usb_string *s;
1282         unsigned mem;
1283         unsigned n_gs;
1284         unsigned n_s;
1285         void *stash;
1286
1287         mem = sizeof(*uc);
1288         mem += sizeof(void *) * (n_gstrings + 1);
1289         mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1290         mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1291         uc = kmalloc(mem, GFP_KERNEL);
1292         if (!uc)
1293                 return ERR_PTR(-ENOMEM);
1294         gs_array = get_containers_gs(uc);
1295         stash = uc->stash;
1296         stash += sizeof(void *) * (n_gstrings + 1);
1297         for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1298                 struct usb_string *org_s;
1299
1300                 gs_array[n_gs] = stash;
1301                 gs = gs_array[n_gs];
1302                 stash += sizeof(struct usb_gadget_strings);
1303                 gs->language = sp[n_gs]->language;
1304                 gs->strings = stash;
1305                 org_s = sp[n_gs]->strings;
1306
1307                 for (n_s = 0; n_s < n_strings; n_s++) {
1308                         s = stash;
1309                         stash += sizeof(struct usb_string);
1310                         if (org_s->s)
1311                                 s->s = org_s->s;
1312                         else
1313                                 s->s = "";
1314                         org_s++;
1315                 }
1316                 s = stash;
1317                 s->s = NULL;
1318                 stash += sizeof(struct usb_string);
1319
1320         }
1321         gs_array[n_gs] = NULL;
1322         return uc;
1323 }
1324
1325 /**
1326  * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1327  * @cdev: the device whose string descriptor IDs are being allocated
1328  * and attached.
1329  * @sp: an array of usb_gadget_strings to attach.
1330  * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1331  *
1332  * This function will create a deep copy of usb_gadget_strings and usb_string
1333  * and attach it to the cdev. The actual string (usb_string.s) will not be
1334  * copied but only a referenced will be made. The struct usb_gadget_strings
1335  * array may contain multiple languages and should be NULL terminated.
1336  * The ->language pointer of each struct usb_gadget_strings has to contain the
1337  * same amount of entries.
1338  * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1339  * usb_string entry of es-ES contains the translation of the first usb_string
1340  * entry of en-US. Therefore both entries become the same id assign.
1341  */
1342 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1343                 struct usb_gadget_strings **sp, unsigned n_strings)
1344 {
1345         struct usb_gadget_string_container *uc;
1346         struct usb_gadget_strings **n_gs;
1347         unsigned n_gstrings = 0;
1348         unsigned i;
1349         int ret;
1350
1351         for (i = 0; sp[i]; i++)
1352                 n_gstrings++;
1353
1354         if (!n_gstrings)
1355                 return ERR_PTR(-EINVAL);
1356
1357         uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1358         if (IS_ERR(uc))
1359                 return ERR_CAST(uc);
1360
1361         n_gs = get_containers_gs(uc);
1362         ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1363         if (ret)
1364                 goto err;
1365
1366         for (i = 1; i < n_gstrings; i++) {
1367                 struct usb_string *m_s;
1368                 struct usb_string *s;
1369                 unsigned n;
1370
1371                 m_s = n_gs[0]->strings;
1372                 s = n_gs[i]->strings;
1373                 for (n = 0; n < n_strings; n++) {
1374                         s->id = m_s->id;
1375                         s++;
1376                         m_s++;
1377                 }
1378         }
1379         list_add_tail(&uc->list, &cdev->gstrings);
1380         return n_gs[0]->strings;
1381 err:
1382         kfree(uc);
1383         return ERR_PTR(ret);
1384 }
1385 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1386
1387 /**
1388  * usb_string_ids_n() - allocate unused string IDs in batch
1389  * @c: the device whose string descriptor IDs are being allocated
1390  * @n: number of string IDs to allocate
1391  * Context: single threaded during gadget setup
1392  *
1393  * Returns the first requested ID.  This ID and next @n-1 IDs are now
1394  * valid IDs.  At least provided that @n is non-zero because if it
1395  * is, returns last requested ID which is now very useful information.
1396  *
1397  * @usb_string_ids_n() is called from bind() callbacks to allocate
1398  * string IDs.  Drivers for functions, configurations, or gadgets will
1399  * then store that ID in the appropriate descriptors and string table.
1400  *
1401  * All string identifier should be allocated using this,
1402  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1403  * example different functions don't wrongly assign different meanings
1404  * to the same identifier.
1405  */
1406 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1407 {
1408         unsigned next = c->next_string_id;
1409         if (unlikely(n > 254 || (unsigned)next + n > 254))
1410                 return -ENODEV;
1411         c->next_string_id += n;
1412         return next + 1;
1413 }
1414 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1415
1416 /*-------------------------------------------------------------------------*/
1417
1418 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1419 {
1420         struct usb_composite_dev *cdev;
1421
1422         if (req->status || req->actual != req->length)
1423                 DBG((struct usb_composite_dev *) ep->driver_data,
1424                                 "setup complete --> %d, %d/%d\n",
1425                                 req->status, req->actual, req->length);
1426
1427         /*
1428          * REVIST The same ep0 requests are shared with function drivers
1429          * so they don't have to maintain the same ->complete() stubs.
1430          *
1431          * Because of that, we need to check for the validity of ->context
1432          * here, even though we know we've set it to something useful.
1433          */
1434         if (!req->context)
1435                 return;
1436
1437         cdev = req->context;
1438
1439         if (cdev->req == req)
1440                 cdev->setup_pending = false;
1441         else if (cdev->os_desc_req == req)
1442                 cdev->os_desc_pending = false;
1443         else
1444                 WARN(1, "unknown request %p\n", req);
1445 }
1446
1447 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1448                 struct usb_request *req, gfp_t gfp_flags)
1449 {
1450         int ret;
1451
1452         ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1453         if (ret == 0) {
1454                 if (cdev->req == req)
1455                         cdev->setup_pending = true;
1456                 else if (cdev->os_desc_req == req)
1457                         cdev->os_desc_pending = true;
1458                 else
1459                         WARN(1, "unknown request %p\n", req);
1460         }
1461
1462         return ret;
1463 }
1464
1465 static int count_ext_compat(struct usb_configuration *c)
1466 {
1467         int i, res;
1468
1469         res = 0;
1470         for (i = 0; i < c->next_interface_id; ++i) {
1471                 struct usb_function *f;
1472                 int j;
1473
1474                 f = c->interface[i];
1475                 for (j = 0; j < f->os_desc_n; ++j) {
1476                         struct usb_os_desc *d;
1477
1478                         if (i != f->os_desc_table[j].if_id)
1479                                 continue;
1480                         d = f->os_desc_table[j].os_desc;
1481                         if (d && d->ext_compat_id)
1482                                 ++res;
1483                 }
1484         }
1485         BUG_ON(res > 255);
1486         return res;
1487 }
1488
1489 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1490 {
1491         int i, count;
1492
1493         count = 16;
1494         for (i = 0; i < c->next_interface_id; ++i) {
1495                 struct usb_function *f;
1496                 int j;
1497
1498                 f = c->interface[i];
1499                 for (j = 0; j < f->os_desc_n; ++j) {
1500                         struct usb_os_desc *d;
1501
1502                         if (i != f->os_desc_table[j].if_id)
1503                                 continue;
1504                         d = f->os_desc_table[j].os_desc;
1505                         if (d && d->ext_compat_id) {
1506                                 *buf++ = i;
1507                                 *buf++ = 0x01;
1508                                 memcpy(buf, d->ext_compat_id, 16);
1509                                 buf += 22;
1510                         } else {
1511                                 ++buf;
1512                                 *buf = 0x01;
1513                                 buf += 23;
1514                         }
1515                         count += 24;
1516                         if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1517                                 return count;
1518                 }
1519         }
1520
1521         return count;
1522 }
1523
1524 static int count_ext_prop(struct usb_configuration *c, int interface)
1525 {
1526         struct usb_function *f;
1527         int j;
1528
1529         f = c->interface[interface];
1530         for (j = 0; j < f->os_desc_n; ++j) {
1531                 struct usb_os_desc *d;
1532
1533                 if (interface != f->os_desc_table[j].if_id)
1534                         continue;
1535                 d = f->os_desc_table[j].os_desc;
1536                 if (d && d->ext_compat_id)
1537                         return d->ext_prop_count;
1538         }
1539         return 0;
1540 }
1541
1542 static int len_ext_prop(struct usb_configuration *c, int interface)
1543 {
1544         struct usb_function *f;
1545         struct usb_os_desc *d;
1546         int j, res;
1547
1548         res = 10; /* header length */
1549         f = c->interface[interface];
1550         for (j = 0; j < f->os_desc_n; ++j) {
1551                 if (interface != f->os_desc_table[j].if_id)
1552                         continue;
1553                 d = f->os_desc_table[j].os_desc;
1554                 if (d)
1555                         return min(res + d->ext_prop_len, 4096);
1556         }
1557         return res;
1558 }
1559
1560 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1561 {
1562         struct usb_function *f;
1563         struct usb_os_desc *d;
1564         struct usb_os_desc_ext_prop *ext_prop;
1565         int j, count, n, ret;
1566
1567         f = c->interface[interface];
1568         count = 10; /* header length */
1569         for (j = 0; j < f->os_desc_n; ++j) {
1570                 if (interface != f->os_desc_table[j].if_id)
1571                         continue;
1572                 d = f->os_desc_table[j].os_desc;
1573                 if (d)
1574                         list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1575                                 n = ext_prop->data_len +
1576                                         ext_prop->name_len + 14;
1577                                 if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1578                                         return count;
1579                                 usb_ext_prop_put_size(buf, n);
1580                                 usb_ext_prop_put_type(buf, ext_prop->type);
1581                                 ret = usb_ext_prop_put_name(buf, ext_prop->name,
1582                                                             ext_prop->name_len);
1583                                 if (ret < 0)
1584                                         return ret;
1585                                 switch (ext_prop->type) {
1586                                 case USB_EXT_PROP_UNICODE:
1587                                 case USB_EXT_PROP_UNICODE_ENV:
1588                                 case USB_EXT_PROP_UNICODE_LINK:
1589                                         usb_ext_prop_put_unicode(buf, ret,
1590                                                          ext_prop->data,
1591                                                          ext_prop->data_len);
1592                                         break;
1593                                 case USB_EXT_PROP_BINARY:
1594                                         usb_ext_prop_put_binary(buf, ret,
1595                                                         ext_prop->data,
1596                                                         ext_prop->data_len);
1597                                         break;
1598                                 case USB_EXT_PROP_LE32:
1599                                         /* not implemented */
1600                                 case USB_EXT_PROP_BE32:
1601                                         /* not implemented */
1602                                 default:
1603                                         return -EINVAL;
1604                                 }
1605                                 buf += n;
1606                                 count += n;
1607                         }
1608         }
1609
1610         return count;
1611 }
1612
1613 /*
1614  * The setup() callback implements all the ep0 functionality that's
1615  * not handled lower down, in hardware or the hardware driver(like
1616  * device and endpoint feature flags, and their status).  It's all
1617  * housekeeping for the gadget function we're implementing.  Most of
1618  * the work is in config and function specific setup.
1619  */
1620 int
1621 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1622 {
1623         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1624         struct usb_request              *req = cdev->req;
1625         int                             value = -EOPNOTSUPP;
1626         int                             status = 0;
1627         u16                             w_index = le16_to_cpu(ctrl->wIndex);
1628         u8                              intf = w_index & 0xFF;
1629         u16                             w_value = le16_to_cpu(ctrl->wValue);
1630         u16                             w_length = le16_to_cpu(ctrl->wLength);
1631         struct usb_function             *f = NULL;
1632         u8                              endp;
1633
1634         if (w_length > USB_COMP_EP0_BUFSIZ) {
1635                 if (ctrl->bRequestType & USB_DIR_IN) {
1636                         /* Cast away the const, we are going to overwrite on purpose. */
1637                         __le16 *temp = (__le16 *)&ctrl->wLength;
1638
1639                         *temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
1640                         w_length = USB_COMP_EP0_BUFSIZ;
1641                 } else {
1642                         goto done;
1643                 }
1644         }
1645
1646         /* partial re-init of the response message; the function or the
1647          * gadget might need to intercept e.g. a control-OUT completion
1648          * when we delegate to it.
1649          */
1650         req->zero = 0;
1651         req->context = cdev;
1652         req->complete = composite_setup_complete;
1653         req->length = 0;
1654         gadget->ep0->driver_data = cdev;
1655
1656         /*
1657          * Don't let non-standard requests match any of the cases below
1658          * by accident.
1659          */
1660         if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1661                 goto unknown;
1662
1663         switch (ctrl->bRequest) {
1664
1665         /* we handle all standard USB descriptors */
1666         case USB_REQ_GET_DESCRIPTOR:
1667                 if (ctrl->bRequestType != USB_DIR_IN)
1668                         goto unknown;
1669                 switch (w_value >> 8) {
1670
1671                 case USB_DT_DEVICE:
1672                         cdev->desc.bNumConfigurations =
1673                                 count_configs(cdev, USB_DT_DEVICE);
1674                         cdev->desc.bMaxPacketSize0 =
1675                                 cdev->gadget->ep0->maxpacket;
1676                         if (gadget_is_superspeed(gadget)) {
1677                                 if (gadget->speed >= USB_SPEED_SUPER) {
1678                                         cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1679                                         cdev->desc.bMaxPacketSize0 = 9;
1680                                 } else {
1681                                         cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1682                                 }
1683                         } else {
1684                                 cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1685                         }
1686
1687                         value = min(w_length, (u16) sizeof cdev->desc);
1688                         memcpy(req->buf, &cdev->desc, value);
1689                         break;
1690                 case USB_DT_DEVICE_QUALIFIER:
1691                         if (!gadget_is_dualspeed(gadget) ||
1692                             gadget->speed >= USB_SPEED_SUPER)
1693                                 break;
1694                         device_qual(cdev);
1695                         value = min_t(int, w_length,
1696                                 sizeof(struct usb_qualifier_descriptor));
1697                         break;
1698                 case USB_DT_OTHER_SPEED_CONFIG:
1699                         if (!gadget_is_dualspeed(gadget) ||
1700                             gadget->speed >= USB_SPEED_SUPER)
1701                                 break;
1702                         /* FALLTHROUGH */
1703                 case USB_DT_CONFIG:
1704                         value = config_desc(cdev, w_value);
1705                         if (value >= 0)
1706                                 value = min(w_length, (u16) value);
1707                         break;
1708                 case USB_DT_STRING:
1709                         value = get_string(cdev, req->buf,
1710                                         w_index, w_value & 0xff);
1711                         if (value >= 0)
1712                                 value = min(w_length, (u16) value);
1713                         break;
1714                 case USB_DT_BOS:
1715                         if (gadget_is_superspeed(gadget)) {
1716                                 value = bos_desc(cdev);
1717                                 value = min(w_length, (u16) value);
1718                         }
1719                         break;
1720                 case USB_DT_OTG:
1721                         if (gadget_is_otg(gadget)) {
1722                                 struct usb_configuration *config;
1723                                 int otg_desc_len = 0;
1724
1725                                 if (cdev->config)
1726                                         config = cdev->config;
1727                                 else
1728                                         config = list_first_entry(
1729                                                         &cdev->configs,
1730                                                 struct usb_configuration, list);
1731                                 if (!config)
1732                                         goto done;
1733
1734                                 if (gadget->otg_caps &&
1735                                         (gadget->otg_caps->otg_rev >= 0x0200))
1736                                         otg_desc_len += sizeof(
1737                                                 struct usb_otg20_descriptor);
1738                                 else
1739                                         otg_desc_len += sizeof(
1740                                                 struct usb_otg_descriptor);
1741
1742                                 value = min_t(int, w_length, otg_desc_len);
1743                                 memcpy(req->buf, config->descriptors[0], value);
1744                         }
1745                         break;
1746                 }
1747                 break;
1748
1749         /* any number of configs can work */
1750         case USB_REQ_SET_CONFIGURATION:
1751                 if (ctrl->bRequestType != 0)
1752                         goto unknown;
1753                 if (gadget_is_otg(gadget)) {
1754                         if (gadget->a_hnp_support)
1755                                 DBG(cdev, "HNP available\n");
1756                         else if (gadget->a_alt_hnp_support)
1757                                 DBG(cdev, "HNP on another port\n");
1758                         else
1759                                 VDBG(cdev, "HNP inactive\n");
1760                 }
1761                 spin_lock(&cdev->lock);
1762                 value = set_config(cdev, ctrl, w_value);
1763                 spin_unlock(&cdev->lock);
1764                 break;
1765         case USB_REQ_GET_CONFIGURATION:
1766                 if (ctrl->bRequestType != USB_DIR_IN)
1767                         goto unknown;
1768                 if (cdev->config)
1769                         *(u8 *)req->buf = cdev->config->bConfigurationValue;
1770                 else
1771                         *(u8 *)req->buf = 0;
1772                 value = min(w_length, (u16) 1);
1773                 break;
1774
1775         /* function drivers must handle get/set altsetting */
1776         case USB_REQ_SET_INTERFACE:
1777                 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1778                         goto unknown;
1779                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1780                         break;
1781                 f = cdev->config->interface[intf];
1782                 if (!f)
1783                         break;
1784
1785                 /*
1786                  * If there's no get_alt() method, we know only altsetting zero
1787                  * works. There is no need to check if set_alt() is not NULL
1788                  * as we check this in usb_add_function().
1789                  */
1790                 if (w_value && !f->get_alt)
1791                         break;
1792
1793                 spin_lock(&cdev->lock);
1794                 value = f->set_alt(f, w_index, w_value);
1795                 if (value == USB_GADGET_DELAYED_STATUS) {
1796                         DBG(cdev,
1797                          "%s: interface %d (%s) requested delayed status\n",
1798                                         __func__, intf, f->name);
1799                         cdev->delayed_status++;
1800                         DBG(cdev, "delayed_status count %d\n",
1801                                         cdev->delayed_status);
1802                 }
1803                 spin_unlock(&cdev->lock);
1804                 break;
1805         case USB_REQ_GET_INTERFACE:
1806                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1807                         goto unknown;
1808                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1809                         break;
1810                 f = cdev->config->interface[intf];
1811                 if (!f)
1812                         break;
1813                 /* lots of interfaces only need altsetting zero... */
1814                 value = f->get_alt ? f->get_alt(f, w_index) : 0;
1815                 if (value < 0)
1816                         break;
1817                 *((u8 *)req->buf) = value;
1818                 value = min(w_length, (u16) 1);
1819                 break;
1820         case USB_REQ_GET_STATUS:
1821                 if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1822                                                 (w_index == OTG_STS_SELECTOR)) {
1823                         if (ctrl->bRequestType != (USB_DIR_IN |
1824                                                         USB_RECIP_DEVICE))
1825                                 goto unknown;
1826                         *((u8 *)req->buf) = gadget->host_request_flag;
1827                         value = 1;
1828                         break;
1829                 }
1830
1831                 /*
1832                  * USB 3.0 additions:
1833                  * Function driver should handle get_status request. If such cb
1834                  * wasn't supplied we respond with default value = 0
1835                  * Note: function driver should supply such cb only for the
1836                  * first interface of the function
1837                  */
1838                 if (!gadget_is_superspeed(gadget))
1839                         goto unknown;
1840                 if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1841                         goto unknown;
1842                 value = 2;      /* This is the length of the get_status reply */
1843                 put_unaligned_le16(0, req->buf);
1844                 if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1845                         break;
1846                 f = cdev->config->interface[intf];
1847                 if (!f)
1848                         break;
1849                 status = f->get_status ? f->get_status(f) : 0;
1850                 if (status < 0)
1851                         break;
1852                 put_unaligned_le16(status & 0x0000ffff, req->buf);
1853                 break;
1854         /*
1855          * Function drivers should handle SetFeature/ClearFeature
1856          * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1857          * only for the first interface of the function
1858          */
1859         case USB_REQ_CLEAR_FEATURE:
1860         case USB_REQ_SET_FEATURE:
1861                 if (!gadget_is_superspeed(gadget))
1862                         goto unknown;
1863                 if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1864                         goto unknown;
1865                 switch (w_value) {
1866                 case USB_INTRF_FUNC_SUSPEND:
1867                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1868                                 break;
1869                         f = cdev->config->interface[intf];
1870                         if (!f)
1871                                 break;
1872                         value = 0;
1873                         if (f->func_suspend)
1874                                 value = f->func_suspend(f, w_index >> 8);
1875                         if (value < 0) {
1876                                 ERROR(cdev,
1877                                       "func_suspend() returned error %d\n",
1878                                       value);
1879                                 value = 0;
1880                         }
1881                         break;
1882                 }
1883                 break;
1884         default:
1885 unknown:
1886                 /*
1887                  * OS descriptors handling
1888                  */
1889                 if (cdev->use_os_string && cdev->os_desc_config &&
1890                     (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1891                     ctrl->bRequest == cdev->b_vendor_code) {
1892                         struct usb_request              *req;
1893                         struct usb_configuration        *os_desc_cfg;
1894                         u8                              *buf;
1895                         int                             interface;
1896                         int                             count = 0;
1897
1898                         req = cdev->os_desc_req;
1899                         req->context = cdev;
1900                         req->complete = composite_setup_complete;
1901                         buf = req->buf;
1902                         os_desc_cfg = cdev->os_desc_config;
1903                         w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
1904                         memset(buf, 0, w_length);
1905                         buf[5] = 0x01;
1906                         switch (ctrl->bRequestType & USB_RECIP_MASK) {
1907                         case USB_RECIP_DEVICE:
1908                                 if (w_index != 0x4 || (w_value >> 8))
1909                                         break;
1910                                 buf[6] = w_index;
1911                                 if (w_length == 0x10) {
1912                                         /* Number of ext compat interfaces */
1913                                         count = count_ext_compat(os_desc_cfg);
1914                                         buf[8] = count;
1915                                         count *= 24; /* 24 B/ext compat desc */
1916                                         count += 16; /* header */
1917                                         put_unaligned_le32(count, buf);
1918                                         value = w_length;
1919                                 } else {
1920                                         /* "extended compatibility ID"s */
1921                                         count = count_ext_compat(os_desc_cfg);
1922                                         buf[8] = count;
1923                                         count *= 24; /* 24 B/ext compat desc */
1924                                         count += 16; /* header */
1925                                         put_unaligned_le32(count, buf);
1926                                         buf += 16;
1927                                         value = fill_ext_compat(os_desc_cfg, buf);
1928                                         value = min_t(u16, w_length, value);
1929                                 }
1930                                 break;
1931                         case USB_RECIP_INTERFACE:
1932                                 if (w_index != 0x5 || (w_value >> 8))
1933                                         break;
1934                                 interface = w_value & 0xFF;
1935                                 if (interface >= MAX_CONFIG_INTERFACES ||
1936                                     !os_desc_cfg->interface[interface])
1937                                         break;
1938                                 buf[6] = w_index;
1939                                 if (w_length == 0x0A) {
1940                                         count = count_ext_prop(os_desc_cfg,
1941                                                 interface);
1942                                         put_unaligned_le16(count, buf + 8);
1943                                         count = len_ext_prop(os_desc_cfg,
1944                                                 interface);
1945                                         put_unaligned_le32(count, buf);
1946
1947                                         value = w_length;
1948                                 } else {
1949                                         count = count_ext_prop(os_desc_cfg,
1950                                                 interface);
1951                                         put_unaligned_le16(count, buf + 8);
1952                                         count = len_ext_prop(os_desc_cfg,
1953                                                 interface);
1954                                         put_unaligned_le32(count, buf);
1955                                         buf += 10;
1956                                         value = fill_ext_prop(os_desc_cfg,
1957                                                               interface, buf);
1958                                         if (value < 0)
1959                                                 return value;
1960                                         value = min_t(u16, w_length, value);
1961                                 }
1962                                 break;
1963                         }
1964
1965                         if (value >= 0) {
1966                                 req->length = value;
1967                                 req->context = cdev;
1968                                 req->zero = value < w_length;
1969                                 value = composite_ep0_queue(cdev, req,
1970                                                             GFP_ATOMIC);
1971                                 if (value < 0) {
1972                                         DBG(cdev, "ep_queue --> %d\n", value);
1973                                         req->status = 0;
1974                                         composite_setup_complete(gadget->ep0,
1975                                                                  req);
1976                                 }
1977                         }
1978                         return value;
1979                 }
1980
1981                 VDBG(cdev,
1982                         "non-core control req%02x.%02x v%04x i%04x l%d\n",
1983                         ctrl->bRequestType, ctrl->bRequest,
1984                         w_value, w_index, w_length);
1985
1986                 /* functions always handle their interfaces and endpoints...
1987                  * punt other recipients (other, WUSB, ...) to the current
1988                  * configuration code.
1989                  */
1990                 if (cdev->config) {
1991                         list_for_each_entry(f, &cdev->config->functions, list)
1992                                 if (f->req_match &&
1993                                     f->req_match(f, ctrl, false))
1994                                         goto try_fun_setup;
1995                 } else {
1996                         struct usb_configuration *c;
1997                         list_for_each_entry(c, &cdev->configs, list)
1998                                 list_for_each_entry(f, &c->functions, list)
1999                                         if (f->req_match &&
2000                                             f->req_match(f, ctrl, true))
2001                                                 goto try_fun_setup;
2002                 }
2003                 f = NULL;
2004
2005                 switch (ctrl->bRequestType & USB_RECIP_MASK) {
2006                 case USB_RECIP_INTERFACE:
2007                         if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2008                                 break;
2009                         f = cdev->config->interface[intf];
2010                         break;
2011
2012                 case USB_RECIP_ENDPOINT:
2013                         if (!cdev->config)
2014                                 break;
2015                         endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
2016                         list_for_each_entry(f, &cdev->config->functions, list) {
2017                                 if (test_bit(endp, f->endpoints))
2018                                         break;
2019                         }
2020                         if (&f->list == &cdev->config->functions)
2021                                 f = NULL;
2022                         break;
2023                 }
2024 try_fun_setup:
2025                 if (f && f->setup)
2026                         value = f->setup(f, ctrl);
2027                 else {
2028                         struct usb_configuration        *c;
2029
2030                         c = cdev->config;
2031                         if (!c)
2032                                 goto done;
2033
2034                         /* try current config's setup */
2035                         if (c->setup) {
2036                                 value = c->setup(c, ctrl);
2037                                 goto done;
2038                         }
2039
2040                         /* try the only function in the current config */
2041                         if (!list_is_singular(&c->functions))
2042                                 goto done;
2043                         f = list_first_entry(&c->functions, struct usb_function,
2044                                              list);
2045                         if (f->setup)
2046                                 value = f->setup(f, ctrl);
2047                 }
2048
2049                 goto done;
2050         }
2051
2052         /* respond with data transfer before status phase? */
2053         if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2054                 req->length = value;
2055                 req->context = cdev;
2056                 req->zero = value < w_length;
2057                 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2058                 if (value < 0) {
2059                         DBG(cdev, "ep_queue --> %d\n", value);
2060                         req->status = 0;
2061                         composite_setup_complete(gadget->ep0, req);
2062                 }
2063         } else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2064                 WARN(cdev,
2065                         "%s: Delayed status not supported for w_length != 0",
2066                         __func__);
2067         }
2068
2069 done:
2070         /* device either stalls (value < 0) or reports success */
2071         return value;
2072 }
2073
2074 void composite_disconnect(struct usb_gadget *gadget)
2075 {
2076         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2077         unsigned long                   flags;
2078
2079         /* REVISIT:  should we have config and device level
2080          * disconnect callbacks?
2081          */
2082         spin_lock_irqsave(&cdev->lock, flags);
2083         cdev->suspended = 0;
2084         if (cdev->config)
2085                 reset_config(cdev);
2086         if (cdev->driver->disconnect)
2087                 cdev->driver->disconnect(cdev);
2088         spin_unlock_irqrestore(&cdev->lock, flags);
2089 }
2090
2091 /*-------------------------------------------------------------------------*/
2092
2093 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2094                               char *buf)
2095 {
2096         struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2097         struct usb_composite_dev *cdev = get_gadget_data(gadget);
2098
2099         return sprintf(buf, "%d\n", cdev->suspended);
2100 }
2101 static DEVICE_ATTR_RO(suspended);
2102
2103 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2104 {
2105         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2106         struct usb_gadget_strings       *gstr = cdev->driver->strings[0];
2107         struct usb_string               *dev_str = gstr->strings;
2108
2109         /* composite_disconnect() must already have been called
2110          * by the underlying peripheral controller driver!
2111          * so there's no i/o concurrency that could affect the
2112          * state protected by cdev->lock.
2113          */
2114         WARN_ON(cdev->config);
2115
2116         while (!list_empty(&cdev->configs)) {
2117                 struct usb_configuration        *c;
2118                 c = list_first_entry(&cdev->configs,
2119                                 struct usb_configuration, list);
2120                 remove_config(cdev, c);
2121         }
2122         if (cdev->driver->unbind && unbind_driver)
2123                 cdev->driver->unbind(cdev);
2124
2125         composite_dev_cleanup(cdev);
2126
2127         if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2128                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2129
2130         kfree(cdev->def_manufacturer);
2131         kfree(cdev);
2132         set_gadget_data(gadget, NULL);
2133 }
2134
2135 static void composite_unbind(struct usb_gadget *gadget)
2136 {
2137         __composite_unbind(gadget, true);
2138 }
2139
2140 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2141                 const struct usb_device_descriptor *old)
2142 {
2143         __le16 idVendor;
2144         __le16 idProduct;
2145         __le16 bcdDevice;
2146         u8 iSerialNumber;
2147         u8 iManufacturer;
2148         u8 iProduct;
2149
2150         /*
2151          * these variables may have been set in
2152          * usb_composite_overwrite_options()
2153          */
2154         idVendor = new->idVendor;
2155         idProduct = new->idProduct;
2156         bcdDevice = new->bcdDevice;
2157         iSerialNumber = new->iSerialNumber;
2158         iManufacturer = new->iManufacturer;
2159         iProduct = new->iProduct;
2160
2161         *new = *old;
2162         if (idVendor)
2163                 new->idVendor = idVendor;
2164         if (idProduct)
2165                 new->idProduct = idProduct;
2166         if (bcdDevice)
2167                 new->bcdDevice = bcdDevice;
2168         else
2169                 new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2170         if (iSerialNumber)
2171                 new->iSerialNumber = iSerialNumber;
2172         if (iManufacturer)
2173                 new->iManufacturer = iManufacturer;
2174         if (iProduct)
2175                 new->iProduct = iProduct;
2176 }
2177
2178 int composite_dev_prepare(struct usb_composite_driver *composite,
2179                 struct usb_composite_dev *cdev)
2180 {
2181         struct usb_gadget *gadget = cdev->gadget;
2182         int ret = -ENOMEM;
2183
2184         /* preallocate control response and buffer */
2185         cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2186         if (!cdev->req)
2187                 return -ENOMEM;
2188
2189         cdev->req->buf = kzalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2190         if (!cdev->req->buf)
2191                 goto fail;
2192
2193         ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2194         if (ret)
2195                 goto fail_dev;
2196
2197         cdev->req->complete = composite_setup_complete;
2198         cdev->req->context = cdev;
2199         gadget->ep0->driver_data = cdev;
2200
2201         cdev->driver = composite;
2202
2203         /*
2204          * As per USB compliance update, a device that is actively drawing
2205          * more than 100mA from USB must report itself as bus-powered in
2206          * the GetStatus(DEVICE) call.
2207          */
2208         if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2209                 usb_gadget_set_selfpowered(gadget);
2210
2211         /* interface and string IDs start at zero via kzalloc.
2212          * we force endpoints to start unassigned; few controller
2213          * drivers will zero ep->driver_data.
2214          */
2215         usb_ep_autoconfig_reset(gadget);
2216         return 0;
2217 fail_dev:
2218         kfree(cdev->req->buf);
2219 fail:
2220         usb_ep_free_request(gadget->ep0, cdev->req);
2221         cdev->req = NULL;
2222         return ret;
2223 }
2224
2225 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2226                                   struct usb_ep *ep0)
2227 {
2228         int ret = 0;
2229
2230         cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2231         if (!cdev->os_desc_req) {
2232                 ret = -ENOMEM;
2233                 goto end;
2234         }
2235
2236         cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2237                                          GFP_KERNEL);
2238         if (!cdev->os_desc_req->buf) {
2239                 ret = -ENOMEM;
2240                 usb_ep_free_request(ep0, cdev->os_desc_req);
2241                 goto end;
2242         }
2243         cdev->os_desc_req->context = cdev;
2244         cdev->os_desc_req->complete = composite_setup_complete;
2245 end:
2246         return ret;
2247 }
2248
2249 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2250 {
2251         struct usb_gadget_string_container *uc, *tmp;
2252
2253         list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2254                 list_del(&uc->list);
2255                 kfree(uc);
2256         }
2257         if (cdev->os_desc_req) {
2258                 if (cdev->os_desc_pending)
2259                         usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2260
2261                 kfree(cdev->os_desc_req->buf);
2262                 cdev->os_desc_req->buf = NULL;
2263                 usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2264                 cdev->os_desc_req = NULL;
2265         }
2266         if (cdev->req) {
2267                 if (cdev->setup_pending)
2268                         usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2269
2270                 kfree(cdev->req->buf);
2271                 cdev->req->buf = NULL;
2272                 usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2273                 cdev->req = NULL;
2274         }
2275         cdev->next_string_id = 0;
2276         device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2277 }
2278
2279 static int composite_bind(struct usb_gadget *gadget,
2280                 struct usb_gadget_driver *gdriver)
2281 {
2282         struct usb_composite_dev        *cdev;
2283         struct usb_composite_driver     *composite = to_cdriver(gdriver);
2284         int                             status = -ENOMEM;
2285
2286         cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2287         if (!cdev)
2288                 return status;
2289
2290         spin_lock_init(&cdev->lock);
2291         cdev->gadget = gadget;
2292         set_gadget_data(gadget, cdev);
2293         INIT_LIST_HEAD(&cdev->configs);
2294         INIT_LIST_HEAD(&cdev->gstrings);
2295
2296         status = composite_dev_prepare(composite, cdev);
2297         if (status)
2298                 goto fail;
2299
2300         /* composite gadget needs to assign strings for whole device (like
2301          * serial number), register function drivers, potentially update
2302          * power state and consumption, etc
2303          */
2304         status = composite->bind(cdev);
2305         if (status < 0)
2306                 goto fail;
2307
2308         if (cdev->use_os_string) {
2309                 status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2310                 if (status)
2311                         goto fail;
2312         }
2313
2314         update_unchanged_dev_desc(&cdev->desc, composite->dev);
2315
2316         /* has userspace failed to provide a serial number? */
2317         if (composite->needs_serial && !cdev->desc.iSerialNumber)
2318                 WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2319
2320         INFO(cdev, "%s ready\n", composite->name);
2321         return 0;
2322
2323 fail:
2324         __composite_unbind(gadget, false);
2325         return status;
2326 }
2327
2328 /*-------------------------------------------------------------------------*/
2329
2330 void composite_suspend(struct usb_gadget *gadget)
2331 {
2332         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2333         struct usb_function             *f;
2334
2335         /* REVISIT:  should we have config level
2336          * suspend/resume callbacks?
2337          */
2338         DBG(cdev, "suspend\n");
2339         if (cdev->config) {
2340                 list_for_each_entry(f, &cdev->config->functions, list) {
2341                         if (f->suspend)
2342                                 f->suspend(f);
2343                 }
2344         }
2345         if (cdev->driver->suspend)
2346                 cdev->driver->suspend(cdev);
2347
2348         cdev->suspended = 1;
2349
2350         usb_gadget_set_selfpowered(gadget);
2351         usb_gadget_vbus_draw(gadget, 2);
2352 }
2353
2354 void composite_resume(struct usb_gadget *gadget)
2355 {
2356         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
2357         struct usb_function             *f;
2358         unsigned                        maxpower;
2359
2360         /* REVISIT:  should we have config level
2361          * suspend/resume callbacks?
2362          */
2363         DBG(cdev, "resume\n");
2364         if (cdev->driver->resume)
2365                 cdev->driver->resume(cdev);
2366         if (cdev->config) {
2367                 list_for_each_entry(f, &cdev->config->functions, list) {
2368                         if (f->resume)
2369                                 f->resume(f);
2370                 }
2371
2372                 maxpower = cdev->config->MaxPower ?
2373                         cdev->config->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
2374                 if (gadget->speed < USB_SPEED_SUPER)
2375                         maxpower = min(maxpower, 500U);
2376                 else
2377                         maxpower = min(maxpower, 900U);
2378
2379                 if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2380                         usb_gadget_clear_selfpowered(gadget);
2381
2382                 usb_gadget_vbus_draw(gadget, maxpower);
2383         }
2384
2385         cdev->suspended = 0;
2386 }
2387
2388 /*-------------------------------------------------------------------------*/
2389
2390 static const struct usb_gadget_driver composite_driver_template = {
2391         .bind           = composite_bind,
2392         .unbind         = composite_unbind,
2393
2394         .setup          = composite_setup,
2395         .reset          = composite_disconnect,
2396         .disconnect     = composite_disconnect,
2397
2398         .suspend        = composite_suspend,
2399         .resume         = composite_resume,
2400
2401         .driver = {
2402                 .owner          = THIS_MODULE,
2403         },
2404 };
2405
2406 /**
2407  * usb_composite_probe() - register a composite driver
2408  * @driver: the driver to register
2409  *
2410  * Context: single threaded during gadget setup
2411  *
2412  * This function is used to register drivers using the composite driver
2413  * framework.  The return value is zero, or a negative errno value.
2414  * Those values normally come from the driver's @bind method, which does
2415  * all the work of setting up the driver to match the hardware.
2416  *
2417  * On successful return, the gadget is ready to respond to requests from
2418  * the host, unless one of its components invokes usb_gadget_disconnect()
2419  * while it was binding.  That would usually be done in order to wait for
2420  * some userspace participation.
2421  */
2422 int usb_composite_probe(struct usb_composite_driver *driver)
2423 {
2424         struct usb_gadget_driver *gadget_driver;
2425
2426         if (!driver || !driver->dev || !driver->bind)
2427                 return -EINVAL;
2428
2429         if (!driver->name)
2430                 driver->name = "composite";
2431
2432         driver->gadget_driver = composite_driver_template;
2433         gadget_driver = &driver->gadget_driver;
2434
2435         gadget_driver->function =  (char *) driver->name;
2436         gadget_driver->driver.name = driver->name;
2437         gadget_driver->max_speed = driver->max_speed;
2438
2439         return usb_gadget_probe_driver(gadget_driver);
2440 }
2441 EXPORT_SYMBOL_GPL(usb_composite_probe);
2442
2443 /**
2444  * usb_composite_unregister() - unregister a composite driver
2445  * @driver: the driver to unregister
2446  *
2447  * This function is used to unregister drivers using the composite
2448  * driver framework.
2449  */
2450 void usb_composite_unregister(struct usb_composite_driver *driver)
2451 {
2452         usb_gadget_unregister_driver(&driver->gadget_driver);
2453 }
2454 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2455
2456 /**
2457  * usb_composite_setup_continue() - Continue with the control transfer
2458  * @cdev: the composite device who's control transfer was kept waiting
2459  *
2460  * This function must be called by the USB function driver to continue
2461  * with the control transfer's data/status stage in case it had requested to
2462  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2463  * can request the composite framework to delay the setup request's data/status
2464  * stages by returning USB_GADGET_DELAYED_STATUS.
2465  */
2466 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2467 {
2468         int                     value;
2469         struct usb_request      *req = cdev->req;
2470         unsigned long           flags;
2471
2472         DBG(cdev, "%s\n", __func__);
2473         spin_lock_irqsave(&cdev->lock, flags);
2474
2475         if (cdev->delayed_status == 0) {
2476                 WARN(cdev, "%s: Unexpected call\n", __func__);
2477
2478         } else if (--cdev->delayed_status == 0) {
2479                 DBG(cdev, "%s: Completing delayed status\n", __func__);
2480                 req->length = 0;
2481                 req->context = cdev;
2482                 value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2483                 if (value < 0) {
2484                         DBG(cdev, "ep_queue --> %d\n", value);
2485                         req->status = 0;
2486                         composite_setup_complete(cdev->gadget->ep0, req);
2487                 }
2488         }
2489
2490         spin_unlock_irqrestore(&cdev->lock, flags);
2491 }
2492 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2493
2494 static char *composite_default_mfr(struct usb_gadget *gadget)
2495 {
2496         char *mfr;
2497         int len;
2498
2499         len = snprintf(NULL, 0, "%s %s with %s", init_utsname()->sysname,
2500                         init_utsname()->release, gadget->name);
2501         len++;
2502         mfr = kmalloc(len, GFP_KERNEL);
2503         if (!mfr)
2504                 return NULL;
2505         snprintf(mfr, len, "%s %s with %s", init_utsname()->sysname,
2506                         init_utsname()->release, gadget->name);
2507         return mfr;
2508 }
2509
2510 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2511                 struct usb_composite_overwrite *covr)
2512 {
2513         struct usb_device_descriptor    *desc = &cdev->desc;
2514         struct usb_gadget_strings       *gstr = cdev->driver->strings[0];
2515         struct usb_string               *dev_str = gstr->strings;
2516
2517         if (covr->idVendor)
2518                 desc->idVendor = cpu_to_le16(covr->idVendor);
2519
2520         if (covr->idProduct)
2521                 desc->idProduct = cpu_to_le16(covr->idProduct);
2522
2523         if (covr->bcdDevice)
2524                 desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2525
2526         if (covr->serial_number) {
2527                 desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2528                 dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2529         }
2530         if (covr->manufacturer) {
2531                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2532                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2533
2534         } else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2535                 desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2536                 cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2537                 dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2538         }
2539
2540         if (covr->product) {
2541                 desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2542                 dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2543         }
2544 }
2545 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2546
2547 MODULE_LICENSE("GPL");
2548 MODULE_AUTHOR("David Brownell");