OSDN Git Service

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