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