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