mtd: spinand: toshiba: Support for new Kioxia Serial NAND
[oweals/u-boot.git] / drivers / usb / gadget / composite.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * composite.c - infrastructure for Composite USB Gadgets
4  *
5  * Copyright (C) 2006-2008 David Brownell
6  * U-Boot porting: Lukasz Majewski <l.majewski@samsung.com>
7  */
8 #undef DEBUG
9
10 #include <log.h>
11 #include <dm/devres.h>
12 #include <linux/bitops.h>
13 #include <linux/bug.h>
14 #include <linux/usb/composite.h>
15
16 #define USB_BUFSIZ      4096
17
18 /* Helper type for accessing packed u16 pointers */
19 typedef struct { __le16 val; } __packed __le16_packed;
20
21 static struct usb_composite_driver *composite;
22
23 static inline void le16_add_cpu_packed(__le16_packed *var, u16 val)
24 {
25         var->val = cpu_to_le16(le16_to_cpu(var->val) + val);
26 }
27
28 /**
29  * usb_add_function() - add a function to a configuration
30  * @config: the configuration
31  * @function: the function being added
32  * Context: single threaded during gadget setup
33  *
34  * After initialization, each configuration must have one or more
35  * functions added to it.  Adding a function involves calling its @bind()
36  * method to allocate resources such as interface and string identifiers
37  * and endpoints.
38  *
39  * This function returns the value of the function's bind(), which is
40  * zero for success else a negative errno value.
41  */
42 int usb_add_function(struct usb_configuration *config,
43                 struct usb_function *function)
44 {
45         int     value = -EINVAL;
46
47         debug("adding '%s'/%p to config '%s'/%p\n",
48                         function->name, function,
49                         config->label, config);
50
51         if (!function->set_alt || !function->disable)
52                 goto done;
53
54         function->config = config;
55         list_add_tail(&function->list, &config->functions);
56
57         if (function->bind) {
58                 value = function->bind(config, function);
59                 if (value < 0) {
60                         list_del(&function->list);
61                         function->config = NULL;
62                 }
63         } else
64                 value = 0;
65
66         if (!config->fullspeed && function->descriptors)
67                 config->fullspeed = 1;
68         if (!config->highspeed && function->hs_descriptors)
69                 config->highspeed = 1;
70
71 done:
72         if (value)
73                 debug("adding '%s'/%p --> %d\n",
74                                 function->name, function, value);
75         return value;
76 }
77
78 /**
79  * usb_function_deactivate - prevent function and gadget enumeration
80  * @function: the function that isn't yet ready to respond
81  *
82  * Blocks response of the gadget driver to host enumeration by
83  * preventing the data line pullup from being activated.  This is
84  * normally called during @bind() processing to change from the
85  * initial "ready to respond" state, or when a required resource
86  * becomes available.
87  *
88  * For example, drivers that serve as a passthrough to a userspace
89  * daemon can block enumeration unless that daemon (such as an OBEX,
90  * MTP, or print server) is ready to handle host requests.
91  *
92  * Not all systems support software control of their USB peripheral
93  * data pullups.
94  *
95  * Returns zero on success, else negative errno.
96  */
97 int usb_function_deactivate(struct usb_function *function)
98 {
99         struct usb_composite_dev        *cdev = function->config->cdev;
100         int                             status = 0;
101
102         if (cdev->deactivations == 0)
103                 status = usb_gadget_disconnect(cdev->gadget);
104         if (status == 0)
105                 cdev->deactivations++;
106
107         return status;
108 }
109
110 /**
111  * usb_function_activate - allow function and gadget enumeration
112  * @function: function on which usb_function_activate() was called
113  *
114  * Reverses effect of usb_function_deactivate().  If no more functions
115  * are delaying their activation, the gadget driver will respond to
116  * host enumeration procedures.
117  *
118  * Returns zero on success, else negative errno.
119  */
120 int usb_function_activate(struct usb_function *function)
121 {
122         struct usb_composite_dev        *cdev = function->config->cdev;
123         int                             status = 0;
124
125         if (cdev->deactivations == 0)
126                 status = -EINVAL;
127         else {
128                 cdev->deactivations--;
129                 if (cdev->deactivations == 0)
130                         status = usb_gadget_connect(cdev->gadget);
131         }
132
133         return status;
134 }
135
136 /**
137  * usb_interface_id() - allocate an unused interface ID
138  * @config: configuration associated with the interface
139  * @function: function handling the interface
140  * Context: single threaded during gadget setup
141  *
142  * usb_interface_id() is called from usb_function.bind() callbacks to
143  * allocate new interface IDs.  The function driver will then store that
144  * ID in interface, association, CDC union, and other descriptors.  It
145  * will also handle any control requests targetted at that interface,
146  * particularly changing its altsetting via set_alt().  There may
147  * also be class-specific or vendor-specific requests to handle.
148  *
149  * All interface identifier should be allocated using this routine, to
150  * ensure that for example different functions don't wrongly assign
151  * different meanings to the same identifier.  Note that since interface
152  * identifers are configuration-specific, functions used in more than
153  * one configuration (or more than once in a given configuration) need
154  * multiple versions of the relevant descriptors.
155  *
156  * Returns the interface ID which was allocated; or -ENODEV if no
157  * more interface IDs can be allocated.
158  */
159 int usb_interface_id(struct usb_configuration *config,
160                 struct usb_function *function)
161 {
162         unsigned char id = config->next_interface_id;
163
164         if (id < MAX_CONFIG_INTERFACES) {
165                 config->interface[id] = function;
166                 config->next_interface_id = id + 1;
167                 return id;
168         }
169         return -ENODEV;
170 }
171
172 static int config_buf(struct usb_configuration *config,
173                 enum usb_device_speed speed, void *buf, u8 type)
174 {
175         int                             len = USB_BUFSIZ - USB_DT_CONFIG_SIZE;
176         void                            *next = buf + USB_DT_CONFIG_SIZE;
177         struct usb_descriptor_header    **descriptors;
178         struct usb_config_descriptor    *c;
179         int                             status;
180         struct usb_function             *f;
181
182         /* write the config descriptor */
183         c = buf;
184         c->bLength = USB_DT_CONFIG_SIZE;
185         c->bDescriptorType = type;
186
187         c->bNumInterfaces = config->next_interface_id;
188         c->bConfigurationValue = config->bConfigurationValue;
189         c->iConfiguration = config->iConfiguration;
190         c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
191         c->bMaxPower = config->bMaxPower ? : (CONFIG_USB_GADGET_VBUS_DRAW / 2);
192
193         /* There may be e.g. OTG descriptors */
194         if (config->descriptors) {
195                 status = usb_descriptor_fillbuf(next, len,
196                                 config->descriptors);
197                 if (status < 0)
198                         return status;
199                 len -= status;
200                 next += status;
201         }
202
203         /* add each function's descriptors */
204         list_for_each_entry(f, &config->functions, list) {
205                 if (speed == USB_SPEED_HIGH)
206                         descriptors = f->hs_descriptors;
207                 else
208                         descriptors = f->descriptors;
209                 if (!descriptors)
210                         continue;
211                 status = usb_descriptor_fillbuf(next, len,
212                         (const struct usb_descriptor_header **) descriptors);
213                 if (status < 0)
214                         return status;
215                 len -= status;
216                 next += status;
217         }
218
219         len = next - buf;
220         c->wTotalLength = cpu_to_le16(len);
221         return len;
222 }
223
224 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
225 {
226         enum usb_device_speed           speed = USB_SPEED_UNKNOWN;
227         struct usb_gadget               *gadget = cdev->gadget;
228         u8                              type = w_value >> 8;
229         int                             hs = 0;
230         struct usb_configuration        *c;
231
232         if (gadget_is_dualspeed(gadget)) {
233                 if (gadget->speed == USB_SPEED_HIGH)
234                         hs = 1;
235                 if (type == USB_DT_OTHER_SPEED_CONFIG)
236                         hs = !hs;
237                 if (hs)
238                         speed = USB_SPEED_HIGH;
239         }
240
241         w_value &= 0xff;
242         list_for_each_entry(c, &cdev->configs, list) {
243                 if (speed == USB_SPEED_HIGH) {
244                         if (!c->highspeed)
245                                 continue;
246                 } else {
247                         if (!c->fullspeed)
248                                 continue;
249                 }
250                 if (w_value == 0)
251                         return config_buf(c, speed, cdev->req->buf, type);
252                 w_value--;
253         }
254         return -EINVAL;
255 }
256
257 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
258 {
259         struct usb_gadget               *gadget = cdev->gadget;
260         unsigned                        count = 0;
261         int                             hs = 0;
262         struct usb_configuration        *c;
263
264         if (gadget_is_dualspeed(gadget)) {
265                 if (gadget->speed == USB_SPEED_HIGH)
266                         hs = 1;
267                 if (type == USB_DT_DEVICE_QUALIFIER)
268                         hs = !hs;
269         }
270         list_for_each_entry(c, &cdev->configs, list) {
271                 /* ignore configs that won't work at this speed */
272                 if (hs) {
273                         if (!c->highspeed)
274                                 continue;
275                 } else {
276                         if (!c->fullspeed)
277                                 continue;
278                 }
279                 count++;
280         }
281         return count;
282 }
283
284 static void device_qual(struct usb_composite_dev *cdev)
285 {
286         struct usb_qualifier_descriptor *qual = cdev->req->buf;
287
288         qual->bLength = sizeof(*qual);
289         qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
290         /* POLICY: same bcdUSB and device type info at both speeds */
291         qual->bcdUSB = cdev->desc.bcdUSB;
292         qual->bDeviceClass = cdev->desc.bDeviceClass;
293         qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
294         qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
295         /* ASSUME same EP0 fifo size at both speeds */
296         qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
297         qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
298         qual->bRESERVED = 0;
299 }
300
301 static void reset_config(struct usb_composite_dev *cdev)
302 {
303         struct usb_function             *f;
304
305         debug("%s:\n", __func__);
306
307         list_for_each_entry(f, &cdev->config->functions, list) {
308                 if (f->disable)
309                         f->disable(f);
310
311                 bitmap_zero(f->endpoints, 32);
312         }
313         cdev->config = NULL;
314 }
315
316 static int set_config(struct usb_composite_dev *cdev,
317                 const struct usb_ctrlrequest *ctrl, unsigned number)
318 {
319         struct usb_gadget       *gadget = cdev->gadget;
320         unsigned                power = gadget_is_otg(gadget) ? 8 : 100;
321         struct usb_descriptor_header **descriptors;
322         int                     result = -EINVAL;
323         struct usb_endpoint_descriptor *ep;
324         struct usb_configuration *c = NULL;
325         int                     addr;
326         int                     tmp;
327         struct usb_function     *f;
328
329         if (cdev->config)
330                 reset_config(cdev);
331
332         if (number) {
333                 list_for_each_entry(c, &cdev->configs, list) {
334                         if (c->bConfigurationValue == number) {
335                                 result = 0;
336                                 break;
337                         }
338                 }
339                 if (result < 0)
340                         goto done;
341         } else
342                 result = 0;
343
344         debug("%s: %s speed config #%d: %s\n", __func__,
345              ({ char *speed;
346                      switch (gadget->speed) {
347                      case USB_SPEED_LOW:
348                              speed = "low";
349                              break;
350                      case USB_SPEED_FULL:
351                              speed = "full";
352                              break;
353                      case USB_SPEED_HIGH:
354                              speed = "high";
355                              break;
356                      default:
357                              speed = "?";
358                              break;
359                      };
360                      speed;
361              }), number, c ? c->label : "unconfigured");
362
363         if (!c)
364                 goto done;
365
366         cdev->config = c;
367
368         /* Initialize all interfaces by setting them to altsetting zero. */
369         for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
370                 f = c->interface[tmp];
371                 if (!f)
372                         break;
373
374                 /*
375                  * Record which endpoints are used by the function. This is used
376                  * to dispatch control requests targeted at that endpoint to the
377                  * function's setup callback instead of the current
378                  * configuration's setup callback.
379                  */
380                 if (gadget->speed == USB_SPEED_HIGH)
381                         descriptors = f->hs_descriptors;
382                 else
383                         descriptors = f->descriptors;
384
385                 for (; *descriptors; ++descriptors) {
386                         if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
387                                 continue;
388
389                         ep = (struct usb_endpoint_descriptor *)*descriptors;
390                         addr = ((ep->bEndpointAddress & 0x80) >> 3)
391                              |  (ep->bEndpointAddress & 0x0f);
392                         generic_set_bit(addr, f->endpoints);
393                 }
394
395                 result = f->set_alt(f, tmp, 0);
396                 if (result < 0) {
397                         debug("interface %d (%s/%p) alt 0 --> %d\n",
398                                         tmp, f->name, f, result);
399
400                         reset_config(cdev);
401                         goto done;
402                 }
403         }
404
405         /* when we return, be sure our power usage is valid */
406         power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
407 done:
408         usb_gadget_vbus_draw(gadget, power);
409         return result;
410 }
411
412 /**
413  * usb_add_config() - add a configuration to a device.
414  * @cdev: wraps the USB gadget
415  * @config: the configuration, with bConfigurationValue assigned
416  * Context: single threaded during gadget setup
417  *
418  * One of the main tasks of a composite driver's bind() routine is to
419  * add each of the configurations it supports, using this routine.
420  *
421  * This function returns the value of the configuration's bind(), which
422  * is zero for success else a negative errno value.  Binding configurations
423  * assigns global resources including string IDs, and per-configuration
424  * resources such as interface IDs and endpoints.
425  */
426 int usb_add_config(struct usb_composite_dev *cdev,
427                 struct usb_configuration *config)
428 {
429         int                             status = -EINVAL;
430         struct usb_configuration        *c;
431         struct usb_function             *f;
432         unsigned int                    i;
433
434         debug("%s: adding config #%u '%s'/%p\n", __func__,
435                         config->bConfigurationValue,
436                         config->label, config);
437
438         if (!config->bConfigurationValue || !config->bind)
439                 goto done;
440
441         /* Prevent duplicate configuration identifiers */
442         list_for_each_entry(c, &cdev->configs, list) {
443                 if (c->bConfigurationValue == config->bConfigurationValue) {
444                         status = -EBUSY;
445                         goto done;
446                 }
447         }
448
449         config->cdev = cdev;
450         list_add_tail(&config->list, &cdev->configs);
451
452         INIT_LIST_HEAD(&config->functions);
453         config->next_interface_id = 0;
454
455         status = config->bind(config);
456         if (status < 0) {
457                 list_del(&config->list);
458                 config->cdev = NULL;
459         } else {
460                 debug("cfg %d/%p speeds:%s%s\n",
461                         config->bConfigurationValue, config,
462                         config->highspeed ? " high" : "",
463                         config->fullspeed
464                                 ? (gadget_is_dualspeed(cdev->gadget)
465                                         ? " full"
466                                         : " full/low")
467                                 : "");
468
469                 for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
470                         f = config->interface[i];
471                         if (!f)
472                                 continue;
473                         debug("%s: interface %d = %s/%p\n",
474                               __func__, i, f->name, f);
475                 }
476         }
477
478         usb_ep_autoconfig_reset(cdev->gadget);
479
480 done:
481         if (status)
482                 debug("added config '%s'/%u --> %d\n", config->label,
483                                 config->bConfigurationValue, status);
484         return status;
485 }
486
487 /*
488  * We support strings in multiple languages ... string descriptor zero
489  * says which languages are supported.  The typical case will be that
490  * only one language (probably English) is used, with I18N handled on
491  * the host side.
492  */
493
494 static void collect_langs(struct usb_gadget_strings **sp, void *buf)
495 {
496         const struct usb_gadget_strings *s;
497         u16                             language;
498         __le16_packed                   *tmp;
499         __le16_packed                   *end = (buf + 252);
500
501         while (*sp) {
502                 s = *sp;
503                 language = cpu_to_le16(s->language);
504                 for (tmp = buf; tmp->val && tmp < end; tmp++) {
505                         if (tmp->val == language)
506                                 goto repeat;
507                 }
508                 tmp->val = language;
509 repeat:
510                 sp++;
511         }
512 }
513
514 static int lookup_string(
515         struct usb_gadget_strings       **sp,
516         void                            *buf,
517         u16                             language,
518         int                             id
519 )
520 {
521         int                             value;
522         struct usb_gadget_strings       *s;
523
524         while (*sp) {
525                 s = *sp++;
526                 if (s->language != language)
527                         continue;
528                 value = usb_gadget_get_string(s, id, buf);
529                 if (value > 0)
530                         return value;
531         }
532         return -EINVAL;
533 }
534
535 static int get_string(struct usb_composite_dev *cdev,
536                 void *buf, u16 language, int id)
537 {
538         struct usb_string_descriptor    *s = buf;
539         struct usb_gadget_strings       **sp;
540         int                             len;
541         struct usb_configuration        *c;
542         struct usb_function             *f;
543
544         /*
545          * Yes, not only is USB's I18N support probably more than most
546          * folk will ever care about ... also, it's all supported here.
547          * (Except for UTF8 support for Unicode's "Astral Planes".)
548          */
549
550         /* 0 == report all available language codes */
551         if (id == 0) {
552                 memset(s, 0, 256);
553                 s->bDescriptorType = USB_DT_STRING;
554
555                 sp = composite->strings;
556                 if (sp)
557                         collect_langs(sp, s->wData);
558
559                 list_for_each_entry(c, &cdev->configs, list) {
560                         sp = c->strings;
561                         if (sp)
562                                 collect_langs(sp, s->wData);
563
564                         list_for_each_entry(f, &c->functions, list) {
565                                 sp = f->strings;
566                                 if (sp)
567                                         collect_langs(sp, s->wData);
568                         }
569                 }
570
571                 for (len = 0; len <= 126 && s->wData[len]; len++)
572                         continue;
573                 if (!len)
574                         return -EINVAL;
575
576                 s->bLength = 2 * (len + 1);
577                 return s->bLength;
578         }
579
580         /*
581          * Otherwise, look up and return a specified string.  String IDs
582          * are device-scoped, so we look up each string table we're told
583          * about.  These lookups are infrequent; simpler-is-better here.
584          */
585         if (composite->strings) {
586                 len = lookup_string(composite->strings, buf, language, id);
587                 if (len > 0)
588                         return len;
589         }
590         list_for_each_entry(c, &cdev->configs, list) {
591                 if (c->strings) {
592                         len = lookup_string(c->strings, buf, language, id);
593                         if (len > 0)
594                                 return len;
595                 }
596                 list_for_each_entry(f, &c->functions, list) {
597                         if (!f->strings)
598                                 continue;
599                         len = lookup_string(f->strings, buf, language, id);
600                         if (len > 0)
601                                 return len;
602                 }
603         }
604         return -EINVAL;
605 }
606
607 /**
608  * usb_string_id() - allocate an unused string ID
609  * @cdev: the device whose string descriptor IDs are being allocated
610  * Context: single threaded during gadget setup
611  *
612  * @usb_string_id() is called from bind() callbacks to allocate
613  * string IDs.  Drivers for functions, configurations, or gadgets will
614  * then store that ID in the appropriate descriptors and string table.
615  *
616  * All string identifier should be allocated using this,
617  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
618  * that for example different functions don't wrongly assign different
619  * meanings to the same identifier.
620  */
621 int usb_string_id(struct usb_composite_dev *cdev)
622 {
623         if (cdev->next_string_id < 254) {
624                 /*
625                  * string id 0 is reserved by USB spec for list of
626                  * supported languages
627                  * 255 reserved as well? -- mina86
628                  */
629                 cdev->next_string_id++;
630                 return cdev->next_string_id;
631         }
632         return -ENODEV;
633 }
634
635 /**
636  * usb_string_ids() - allocate unused string IDs in batch
637  * @cdev: the device whose string descriptor IDs are being allocated
638  * @str: an array of usb_string objects to assign numbers to
639  * Context: single threaded during gadget setup
640  *
641  * @usb_string_ids() is called from bind() callbacks to allocate
642  * string IDs.  Drivers for functions, configurations, or gadgets will
643  * then copy IDs from the string table to the appropriate descriptors
644  * and string table for other languages.
645  *
646  * All string identifier should be allocated using this,
647  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
648  * example different functions don't wrongly assign different meanings
649  * to the same identifier.
650  */
651 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
652 {
653         u8 next = cdev->next_string_id;
654
655         for (; str->s; ++str) {
656                 if (next >= 254)
657                         return -ENODEV;
658                 str->id = ++next;
659         }
660
661         cdev->next_string_id = next;
662
663         return 0;
664 }
665
666 /**
667  * usb_string_ids_n() - allocate unused string IDs in batch
668  * @c: the device whose string descriptor IDs are being allocated
669  * @n: number of string IDs to allocate
670  * Context: single threaded during gadget setup
671  *
672  * Returns the first requested ID.  This ID and next @n-1 IDs are now
673  * valid IDs.  At least provided that @n is non-zero because if it
674  * is, returns last requested ID which is now very useful information.
675  *
676  * @usb_string_ids_n() is called from bind() callbacks to allocate
677  * string IDs.  Drivers for functions, configurations, or gadgets will
678  * then store that ID in the appropriate descriptors and string table.
679  *
680  * All string identifier should be allocated using this,
681  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
682  * example different functions don't wrongly assign different meanings
683  * to the same identifier.
684  */
685 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
686 {
687         u8 next = c->next_string_id;
688
689         if (n > 254 || next + n > 254)
690                 return -ENODEV;
691
692         c->next_string_id += n;
693         return next + 1;
694 }
695
696 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
697 {
698         if (req->status || req->actual != req->length)
699                 debug("%s: setup complete --> %d, %d/%d\n", __func__,
700                                 req->status, req->actual, req->length);
701 }
702
703 static int bos_desc(struct usb_composite_dev *cdev)
704 {
705         struct usb_ext_cap_descriptor   *usb_ext;
706         struct usb_bos_descriptor       *bos = cdev->req->buf;
707
708         bos->bLength = USB_DT_BOS_SIZE;
709         bos->bDescriptorType = USB_DT_BOS;
710
711         bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
712         bos->bNumDeviceCaps = 0;
713
714         /*
715          * A SuperSpeed device shall include the USB2.0 extension descriptor
716          * and shall support LPM when operating in USB2.0 HS mode.
717          */
718         usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
719         bos->bNumDeviceCaps++;
720         le16_add_cpu_packed((__le16_packed *)&bos->wTotalLength,
721                             USB_DT_USB_EXT_CAP_SIZE);
722         usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
723         usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
724         usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
725         usb_ext->bmAttributes =
726                 cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
727
728         /*
729          * The Superspeed USB Capability descriptor shall be implemented
730          * by all SuperSpeed devices.
731          */
732         if (gadget_is_superspeed(cdev->gadget)) {
733                 struct usb_ss_cap_descriptor *ss_cap;
734
735                 ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
736                 bos->bNumDeviceCaps++;
737                 le16_add_cpu_packed((__le16_packed *)&bos->wTotalLength,
738                                     USB_DT_USB_SS_CAP_SIZE);
739                 ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
740                 ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
741                 ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
742                 ss_cap->bmAttributes = 0; /* LTM is not supported yet */
743                 ss_cap->wSpeedSupported =
744                         cpu_to_le16(USB_LOW_SPEED_OPERATION |
745                                     USB_FULL_SPEED_OPERATION |
746                                     USB_HIGH_SPEED_OPERATION |
747                                     USB_5GBPS_OPERATION);
748                 ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
749                 ss_cap->bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
750                 ss_cap->bU2DevExitLat =
751                         cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
752         }
753         return le16_to_cpu(bos->wTotalLength);
754 }
755
756 /*
757  * The setup() callback implements all the ep0 functionality that's
758  * not handled lower down, in hardware or the hardware driver(like
759  * device and endpoint feature flags, and their status).  It's all
760  * housekeeping for the gadget function we're implementing.  Most of
761  * the work is in config and function specific setup.
762  */
763 static int
764 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
765 {
766         u16                             w_length = le16_to_cpu(ctrl->wLength);
767         u16                             w_index = le16_to_cpu(ctrl->wIndex);
768         u16                             w_value = le16_to_cpu(ctrl->wValue);
769         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
770         u8                              intf = w_index & 0xFF;
771         int                             value = -EOPNOTSUPP;
772         struct usb_request              *req = cdev->req;
773         struct usb_function             *f = NULL;
774         int                             standard;
775         u8                              endp;
776         struct usb_configuration        *c;
777
778         /*
779          * partial re-init of the response message; the function or the
780          * gadget might need to intercept e.g. a control-OUT completion
781          * when we delegate to it.
782          */
783         req->zero = 0;
784         req->complete = composite_setup_complete;
785         req->length = USB_BUFSIZ;
786         gadget->ep0->driver_data = cdev;
787         standard = (ctrl->bRequestType & USB_TYPE_MASK)
788                                                 == USB_TYPE_STANDARD;
789         if (!standard)
790                 goto unknown;
791
792         switch (ctrl->bRequest) {
793
794         /* we handle all standard USB descriptors */
795         case USB_REQ_GET_DESCRIPTOR:
796                 if (ctrl->bRequestType != USB_DIR_IN)
797                         goto unknown;
798                 switch (w_value >> 8) {
799
800                 case USB_DT_DEVICE:
801                         cdev->desc.bNumConfigurations =
802                                 count_configs(cdev, USB_DT_DEVICE);
803
804                         /*
805                          * If the speed is Super speed, then the supported
806                          * max packet size is 512 and it should be sent as
807                          * exponent of 2. So, 9(2^9=512) should be filled in
808                          * bMaxPacketSize0. Also fill USB version as 3.0
809                          * if speed is Super speed.
810                          */
811                         if (cdev->gadget->speed == USB_SPEED_SUPER) {
812                                 cdev->desc.bMaxPacketSize0 = 9;
813                                 cdev->desc.bcdUSB = cpu_to_le16(0x0300);
814                         } else {
815                                 cdev->desc.bMaxPacketSize0 =
816                                         cdev->gadget->ep0->maxpacket;
817                         }
818                         value = min(w_length, (u16) sizeof cdev->desc);
819                         memcpy(req->buf, &cdev->desc, value);
820                         break;
821                 case USB_DT_DEVICE_QUALIFIER:
822                         if (!gadget_is_dualspeed(gadget))
823                                 break;
824                         device_qual(cdev);
825                         value = min_t(int, w_length,
826                                       sizeof(struct usb_qualifier_descriptor));
827                         break;
828                 case USB_DT_OTHER_SPEED_CONFIG:
829                         if (!gadget_is_dualspeed(gadget))
830                                 break;
831
832                 case USB_DT_CONFIG:
833                         value = config_desc(cdev, w_value);
834                         if (value >= 0)
835                                 value = min(w_length, (u16) value);
836                         break;
837                 case USB_DT_STRING:
838                         value = get_string(cdev, req->buf,
839                                         w_index, w_value & 0xff);
840                         if (value >= 0)
841                                 value = min(w_length, (u16) value);
842                         break;
843                 case USB_DT_BOS:
844                         if (gadget_is_superspeed(cdev->gadget))
845                                 value = bos_desc(cdev);
846                         if (value >= 0)
847                                 value = min(w_length, (u16)value);
848                         break;
849                 default:
850                         goto unknown;
851                 }
852                 break;
853
854         /* any number of configs can work */
855         case USB_REQ_SET_CONFIGURATION:
856                 if (ctrl->bRequestType != 0)
857                         goto unknown;
858                 if (gadget_is_otg(gadget)) {
859                         if (gadget->a_hnp_support)
860                                 debug("HNP available\n");
861                         else if (gadget->a_alt_hnp_support)
862                                 debug("HNP on another port\n");
863                         else
864                                 debug("HNP inactive\n");
865                 }
866
867                 value = set_config(cdev, ctrl, w_value);
868                 break;
869         case USB_REQ_GET_CONFIGURATION:
870                 if (ctrl->bRequestType != USB_DIR_IN)
871                         goto unknown;
872                 if (cdev->config)
873                         *(u8 *)req->buf = cdev->config->bConfigurationValue;
874                 else
875                         *(u8 *)req->buf = 0;
876                 value = min(w_length, (u16) 1);
877                 break;
878
879         /*
880          * function drivers must handle get/set altsetting; if there's
881          * no get() method, we know only altsetting zero works.
882          */
883         case USB_REQ_SET_INTERFACE:
884                 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
885                         goto unknown;
886                 if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
887                         break;
888                 f = cdev->config->interface[intf];
889                 if (!f)
890                         break;
891                 if (w_value && !f->set_alt)
892                         break;
893                 value = f->set_alt(f, w_index, w_value);
894                 break;
895         case USB_REQ_GET_INTERFACE:
896                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
897                         goto unknown;
898                 if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
899                         break;
900                 f = cdev->config->interface[intf];
901                 if (!f)
902                         break;
903                 /* lots of interfaces only need altsetting zero... */
904                 value = f->get_alt ? f->get_alt(f, w_index) : 0;
905                 if (value < 0)
906                         break;
907                 *((u8 *)req->buf) = value;
908                 value = min(w_length, (u16) 1);
909                 break;
910         default:
911 unknown:
912                 debug("non-core control req%02x.%02x v%04x i%04x l%d\n",
913                         ctrl->bRequestType, ctrl->bRequest,
914                         w_value, w_index, w_length);
915
916                 if (!cdev->config)
917                         goto done;
918
919                 /*
920                  * functions always handle their interfaces and endpoints...
921                  * punt other recipients (other, WUSB, ...) to the current
922                  * configuration code.
923                  */
924                 switch (ctrl->bRequestType & USB_RECIP_MASK) {
925                 case USB_RECIP_INTERFACE:
926                         f = cdev->config->interface[intf];
927                         break;
928
929                 case USB_RECIP_ENDPOINT:
930                         endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
931                         list_for_each_entry(f, &cdev->config->functions, list) {
932                                 if (test_bit(endp, f->endpoints))
933                                         break;
934                         }
935                         if (&f->list == &cdev->config->functions)
936                                 f = NULL;
937                         break;
938                 /*
939                  * dfu-util (version 0.5) sets bmRequestType.Receipent = Device
940                  * for non-standard request (w_value = 0x21,
941                  * bRequest = GET_DESCRIPTOR in this case).
942                  * When only one interface is registered (as it is done now),
943                  * then this request shall be handled as it was requested for
944                  * interface.
945                  *
946                  * In the below code it is checked if only one interface is
947                  * present and proper function for it is extracted. Due to that
948                  * function's setup (f->setup) is called to handle this
949                  * special non-standard request.
950                  */
951                 case USB_RECIP_DEVICE:
952                         debug("cdev->config->next_interface_id: %d intf: %d\n",
953                                cdev->config->next_interface_id, intf);
954                         if (cdev->config->next_interface_id == 1)
955                                 f = cdev->config->interface[intf];
956                         break;
957                 }
958
959                 if (f && f->setup)
960                         value = f->setup(f, ctrl);
961                 else {
962                         c = cdev->config;
963                         if (c->setup)
964                                 value = c->setup(c, ctrl);
965                 }
966
967                 goto done;
968         }
969
970         /* respond with data transfer before status phase? */
971         if (value >= 0) {
972                 req->length = value;
973                 req->zero = value < w_length;
974                 value = usb_ep_queue(gadget->ep0, req, GFP_KERNEL);
975                 if (value < 0) {
976                         debug("ep_queue --> %d\n", value);
977                         req->status = 0;
978                         composite_setup_complete(gadget->ep0, req);
979                 }
980         }
981
982 done:
983         /* device either stalls (value < 0) or reports success */
984         return value;
985 }
986
987 static void composite_disconnect(struct usb_gadget *gadget)
988 {
989         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
990
991         if (cdev->config)
992                 reset_config(cdev);
993         if (composite->disconnect)
994                 composite->disconnect(cdev);
995 }
996
997 static void composite_unbind(struct usb_gadget *gadget)
998 {
999         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1000         struct usb_configuration        *c;
1001         struct usb_function             *f;
1002
1003         /*
1004          * composite_disconnect() must already have been called
1005          * by the underlying peripheral controller driver!
1006          * so there's no i/o concurrency that could affect the
1007          * state protected by cdev->lock.
1008          */
1009 #ifdef __UBOOT__
1010         assert_noisy(!cdev->config);
1011 #else
1012         BUG_ON(cdev->config);
1013 #endif
1014
1015         while (!list_empty(&cdev->configs)) {
1016                 c = list_first_entry(&cdev->configs,
1017                                 struct usb_configuration, list);
1018                 while (!list_empty(&c->functions)) {
1019                         f = list_first_entry(&c->functions,
1020                                         struct usb_function, list);
1021                         list_del(&f->list);
1022                         if (f->unbind) {
1023                                 debug("unbind function '%s'/%p\n",
1024                                                 f->name, f);
1025                                 f->unbind(c, f);
1026                         }
1027                 }
1028                 list_del(&c->list);
1029                 if (c->unbind) {
1030                         debug("unbind config '%s'/%p\n", c->label, c);
1031                         c->unbind(c);
1032                 }
1033                 free(c);
1034         }
1035         if (composite->unbind)
1036                 composite->unbind(cdev);
1037
1038         if (cdev->req) {
1039                 kfree(cdev->req->buf);
1040                 usb_ep_free_request(gadget->ep0, cdev->req);
1041         }
1042         kfree(cdev);
1043         set_gadget_data(gadget, NULL);
1044
1045         composite = NULL;
1046 }
1047
1048 static int composite_bind(struct usb_gadget *gadget)
1049 {
1050         int                             status = -ENOMEM;
1051         struct usb_composite_dev        *cdev;
1052
1053         cdev = calloc(sizeof *cdev, 1);
1054         if (!cdev)
1055                 return status;
1056
1057         cdev->gadget = gadget;
1058         set_gadget_data(gadget, cdev);
1059         INIT_LIST_HEAD(&cdev->configs);
1060
1061         /* preallocate control response and buffer */
1062         cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1063         if (!cdev->req)
1064                 goto fail;
1065         cdev->req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, USB_BUFSIZ);
1066         if (!cdev->req->buf)
1067                 goto fail;
1068         cdev->req->complete = composite_setup_complete;
1069         gadget->ep0->driver_data = cdev;
1070
1071         cdev->bufsiz = USB_BUFSIZ;
1072         cdev->driver = composite;
1073
1074         usb_gadget_set_selfpowered(gadget);
1075         usb_ep_autoconfig_reset(cdev->gadget);
1076
1077         status = composite->bind(cdev);
1078         if (status < 0)
1079                 goto fail;
1080
1081         memcpy(&cdev->desc, composite->dev,
1082                sizeof(struct usb_device_descriptor));
1083         cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1084
1085         debug("%s: ready\n", composite->name);
1086         return 0;
1087
1088 fail:
1089         composite_unbind(gadget);
1090         return status;
1091 }
1092
1093 static void
1094 composite_suspend(struct usb_gadget *gadget)
1095 {
1096         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1097         struct usb_function             *f;
1098
1099         debug("%s: suspend\n", __func__);
1100         if (cdev->config) {
1101                 list_for_each_entry(f, &cdev->config->functions, list) {
1102                         if (f->suspend)
1103                                 f->suspend(f);
1104                 }
1105         }
1106         if (composite->suspend)
1107                 composite->suspend(cdev);
1108
1109         cdev->suspended = 1;
1110 }
1111
1112 static void
1113 composite_resume(struct usb_gadget *gadget)
1114 {
1115         struct usb_composite_dev        *cdev = get_gadget_data(gadget);
1116         struct usb_function             *f;
1117
1118         debug("%s: resume\n", __func__);
1119         if (composite->resume)
1120                 composite->resume(cdev);
1121         if (cdev->config) {
1122                 list_for_each_entry(f, &cdev->config->functions, list) {
1123                         if (f->resume)
1124                                 f->resume(f);
1125                 }
1126         }
1127
1128         cdev->suspended = 0;
1129 }
1130
1131 static struct usb_gadget_driver composite_driver = {
1132         .speed          = USB_SPEED_HIGH,
1133
1134         .bind           = composite_bind,
1135         .unbind         = composite_unbind,
1136
1137         .setup          = composite_setup,
1138         .reset          = composite_disconnect,
1139         .disconnect     = composite_disconnect,
1140
1141         .suspend        = composite_suspend,
1142         .resume         = composite_resume,
1143 };
1144
1145 /**
1146  * usb_composite_register() - register a composite driver
1147  * @driver: the driver to register
1148  * Context: single threaded during gadget setup
1149  *
1150  * This function is used to register drivers using the composite driver
1151  * framework.  The return value is zero, or a negative errno value.
1152  * Those values normally come from the driver's @bind method, which does
1153  * all the work of setting up the driver to match the hardware.
1154  *
1155  * On successful return, the gadget is ready to respond to requests from
1156  * the host, unless one of its components invokes usb_gadget_disconnect()
1157  * while it was binding.  That would usually be done in order to wait for
1158  * some userspace participation.
1159  */
1160 int usb_composite_register(struct usb_composite_driver *driver)
1161 {
1162         int res;
1163
1164         if (!driver || !driver->dev || !driver->bind || composite)
1165                 return -EINVAL;
1166
1167         if (!driver->name)
1168                 driver->name = "composite";
1169         composite = driver;
1170
1171         res = usb_gadget_register_driver(&composite_driver);
1172         if (res != 0)
1173                 composite = NULL;
1174
1175         return res;
1176 }
1177
1178 /**
1179  * usb_composite_unregister() - unregister a composite driver
1180  * @driver: the driver to unregister
1181  *
1182  * This function is used to unregister drivers using the composite
1183  * driver framework.
1184  */
1185 void usb_composite_unregister(struct usb_composite_driver *driver)
1186 {
1187         if (composite != driver)
1188                 return;
1189         usb_gadget_unregister_driver(&composite_driver);
1190         composite = NULL;
1191 }