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