xref: /openbmc/u-boot/drivers/usb/gadget/composite.c (revision ebce73f0)
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 void device_qual(struct usb_composite_dev *cdev)
275 {
276 	struct usb_qualifier_descriptor	*qual = cdev->req->buf;
277 
278 	qual->bLength = sizeof(*qual);
279 	qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
280 	/* POLICY: same bcdUSB and device type info at both speeds */
281 	qual->bcdUSB = cdev->desc.bcdUSB;
282 	qual->bDeviceClass = cdev->desc.bDeviceClass;
283 	qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
284 	qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
285 	/* ASSUME same EP0 fifo size at both speeds */
286 	qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
287 	qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
288 	qual->bRESERVED = 0;
289 }
290 
291 static void reset_config(struct usb_composite_dev *cdev)
292 {
293 	struct usb_function		*f;
294 
295 	debug("%s:\n", __func__);
296 
297 	list_for_each_entry(f, &cdev->config->functions, list) {
298 		if (f->disable)
299 			f->disable(f);
300 
301 		bitmap_zero(f->endpoints, 32);
302 	}
303 	cdev->config = NULL;
304 }
305 
306 static int set_config(struct usb_composite_dev *cdev,
307 		const struct usb_ctrlrequest *ctrl, unsigned number)
308 {
309 	struct usb_gadget	*gadget = cdev->gadget;
310 	unsigned		power = gadget_is_otg(gadget) ? 8 : 100;
311 	struct usb_descriptor_header **descriptors;
312 	int			result = -EINVAL;
313 	struct usb_endpoint_descriptor *ep;
314 	struct usb_configuration *c = NULL;
315 	int                     addr;
316 	int			tmp;
317 	struct usb_function	*f;
318 
319 	if (cdev->config)
320 		reset_config(cdev);
321 
322 	if (number) {
323 		list_for_each_entry(c, &cdev->configs, list) {
324 			if (c->bConfigurationValue == number) {
325 				result = 0;
326 				break;
327 			}
328 		}
329 		if (result < 0)
330 			goto done;
331 	} else
332 		result = 0;
333 
334 	debug("%s: %s speed config #%d: %s\n", __func__,
335 	     ({ char *speed;
336 		     switch (gadget->speed) {
337 		     case USB_SPEED_LOW:
338 			     speed = "low";
339 			     break;
340 		     case USB_SPEED_FULL:
341 			     speed = "full";
342 			     break;
343 		     case USB_SPEED_HIGH:
344 			     speed = "high";
345 			     break;
346 		     default:
347 			     speed = "?";
348 			     break;
349 		     };
350 		     speed;
351 	     }), number, c ? c->label : "unconfigured");
352 
353 	if (!c)
354 		goto done;
355 
356 	cdev->config = c;
357 
358 	/* Initialize all interfaces by setting them to altsetting zero. */
359 	for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
360 		f = c->interface[tmp];
361 		if (!f)
362 			break;
363 
364 		/*
365 		 * Record which endpoints are used by the function. This is used
366 		 * to dispatch control requests targeted at that endpoint to the
367 		 * function's setup callback instead of the current
368 		 * configuration's setup callback.
369 		 */
370 		if (gadget->speed == USB_SPEED_HIGH)
371 			descriptors = f->hs_descriptors;
372 		else
373 			descriptors = f->descriptors;
374 
375 		for (; *descriptors; ++descriptors) {
376 			if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
377 				continue;
378 
379 			ep = (struct usb_endpoint_descriptor *)*descriptors;
380 			addr = ((ep->bEndpointAddress & 0x80) >> 3)
381 			     |	(ep->bEndpointAddress & 0x0f);
382 			__set_bit(addr, f->endpoints);
383 		}
384 
385 		result = f->set_alt(f, tmp, 0);
386 		if (result < 0) {
387 			debug("interface %d (%s/%p) alt 0 --> %d\n",
388 					tmp, f->name, f, result);
389 
390 			reset_config(cdev);
391 			goto done;
392 		}
393 	}
394 
395 	/* when we return, be sure our power usage is valid */
396 	power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
397 done:
398 	usb_gadget_vbus_draw(gadget, power);
399 	return result;
400 }
401 
402 /**
403  * usb_add_config() - add a configuration to a device.
404  * @cdev: wraps the USB gadget
405  * @config: the configuration, with bConfigurationValue assigned
406  * Context: single threaded during gadget setup
407  *
408  * One of the main tasks of a composite driver's bind() routine is to
409  * add each of the configurations it supports, using this routine.
410  *
411  * This function returns the value of the configuration's bind(), which
412  * is zero for success else a negative errno value.  Binding configurations
413  * assigns global resources including string IDs, and per-configuration
414  * resources such as interface IDs and endpoints.
415  */
416 int usb_add_config(struct usb_composite_dev *cdev,
417 		struct usb_configuration *config)
418 {
419 	int				status = -EINVAL;
420 	struct usb_configuration	*c;
421 	struct usb_function		*f;
422 	unsigned int			i;
423 
424 	debug("%s: adding config #%u '%s'/%p\n", __func__,
425 			config->bConfigurationValue,
426 			config->label, config);
427 
428 	if (!config->bConfigurationValue || !config->bind)
429 		goto done;
430 
431 	/* Prevent duplicate configuration identifiers */
432 	list_for_each_entry(c, &cdev->configs, list) {
433 		if (c->bConfigurationValue == config->bConfigurationValue) {
434 			status = -EBUSY;
435 			goto done;
436 		}
437 	}
438 
439 	config->cdev = cdev;
440 	list_add_tail(&config->list, &cdev->configs);
441 
442 	INIT_LIST_HEAD(&config->functions);
443 	config->next_interface_id = 0;
444 
445 	status = config->bind(config);
446 	if (status < 0) {
447 		list_del(&config->list);
448 		config->cdev = NULL;
449 	} else {
450 		debug("cfg %d/%p speeds:%s%s\n",
451 			config->bConfigurationValue, config,
452 			config->highspeed ? " high" : "",
453 			config->fullspeed
454 				? (gadget_is_dualspeed(cdev->gadget)
455 					? " full"
456 					: " full/low")
457 				: "");
458 
459 		for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
460 			f = config->interface[i];
461 			if (!f)
462 				continue;
463 			debug("%s: interface %d = %s/%p\n",
464 			      __func__, i, f->name, f);
465 		}
466 	}
467 
468 	usb_ep_autoconfig_reset(cdev->gadget);
469 
470 done:
471 	if (status)
472 		debug("added config '%s'/%u --> %d\n", config->label,
473 				config->bConfigurationValue, status);
474 	return status;
475 }
476 
477 /*
478  * We support strings in multiple languages ... string descriptor zero
479  * says which languages are supported.	The typical case will be that
480  * only one language (probably English) is used, with I18N handled on
481  * the host side.
482  */
483 
484 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
485 {
486 	const struct usb_gadget_strings	*s;
487 	u16				language;
488 	__le16				*tmp;
489 
490 	while (*sp) {
491 		s = *sp;
492 		language = cpu_to_le16(s->language);
493 		for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
494 			if (*tmp == language)
495 				goto repeat;
496 		}
497 		*tmp++ = language;
498 repeat:
499 		sp++;
500 	}
501 }
502 
503 static int lookup_string(
504 	struct usb_gadget_strings	**sp,
505 	void				*buf,
506 	u16				language,
507 	int				id
508 )
509 {
510 	int				value;
511 	struct usb_gadget_strings	*s;
512 
513 	while (*sp) {
514 		s = *sp++;
515 		if (s->language != language)
516 			continue;
517 		value = usb_gadget_get_string(s, id, buf);
518 		if (value > 0)
519 			return value;
520 	}
521 	return -EINVAL;
522 }
523 
524 static int get_string(struct usb_composite_dev *cdev,
525 		void *buf, u16 language, int id)
526 {
527 	struct usb_string_descriptor	*s = buf;
528 	struct usb_gadget_strings	**sp;
529 	int				len;
530 	struct usb_configuration	*c;
531 	struct usb_function		*f;
532 
533 	/*
534 	 * Yes, not only is USB's I18N support probably more than most
535 	 * folk will ever care about ... also, it's all supported here.
536 	 * (Except for UTF8 support for Unicode's "Astral Planes".)
537 	 */
538 
539 	/* 0 == report all available language codes */
540 	if (id == 0) {
541 		memset(s, 0, 256);
542 		s->bDescriptorType = USB_DT_STRING;
543 
544 		sp = composite->strings;
545 		if (sp)
546 			collect_langs(sp, s->wData);
547 
548 		list_for_each_entry(c, &cdev->configs, list) {
549 			sp = c->strings;
550 			if (sp)
551 				collect_langs(sp, s->wData);
552 
553 			list_for_each_entry(f, &c->functions, list) {
554 				sp = f->strings;
555 				if (sp)
556 					collect_langs(sp, s->wData);
557 			}
558 		}
559 
560 		for (len = 0; len <= 126 && s->wData[len]; len++)
561 			continue;
562 		if (!len)
563 			return -EINVAL;
564 
565 		s->bLength = 2 * (len + 1);
566 		return s->bLength;
567 	}
568 
569 	/*
570 	 * Otherwise, look up and return a specified string.  String IDs
571 	 * are device-scoped, so we look up each string table we're told
572 	 * about.  These lookups are infrequent; simpler-is-better here.
573 	 */
574 	if (composite->strings) {
575 		len = lookup_string(composite->strings, buf, language, id);
576 		if (len > 0)
577 			return len;
578 	}
579 	list_for_each_entry(c, &cdev->configs, list) {
580 		if (c->strings) {
581 			len = lookup_string(c->strings, buf, language, id);
582 			if (len > 0)
583 				return len;
584 		}
585 		list_for_each_entry(f, &c->functions, list) {
586 			if (!f->strings)
587 				continue;
588 			len = lookup_string(f->strings, buf, language, id);
589 			if (len > 0)
590 				return len;
591 		}
592 	}
593 	return -EINVAL;
594 }
595 
596 /**
597  * usb_string_id() - allocate an unused string ID
598  * @cdev: the device whose string descriptor IDs are being allocated
599  * Context: single threaded during gadget setup
600  *
601  * @usb_string_id() is called from bind() callbacks to allocate
602  * string IDs.	Drivers for functions, configurations, or gadgets will
603  * then store that ID in the appropriate descriptors and string table.
604  *
605  * All string identifier should be allocated using this,
606  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
607  * that for example different functions don't wrongly assign different
608  * meanings to the same identifier.
609  */
610 int usb_string_id(struct usb_composite_dev *cdev)
611 {
612 	if (cdev->next_string_id < 254) {
613 		/*
614 		 * string id 0 is reserved by USB spec for list of
615 		 * supported languages
616 		 * 255 reserved as well? -- mina86
617 		 */
618 		cdev->next_string_id++;
619 		return cdev->next_string_id;
620 	}
621 	return -ENODEV;
622 }
623 
624 /**
625  * usb_string_ids() - allocate unused string IDs in batch
626  * @cdev: the device whose string descriptor IDs are being allocated
627  * @str: an array of usb_string objects to assign numbers to
628  * Context: single threaded during gadget setup
629  *
630  * @usb_string_ids() is called from bind() callbacks to allocate
631  * string IDs.	Drivers for functions, configurations, or gadgets will
632  * then copy IDs from the string table to the appropriate descriptors
633  * and string table for other languages.
634  *
635  * All string identifier should be allocated using this,
636  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
637  * example different functions don't wrongly assign different meanings
638  * to the same identifier.
639  */
640 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
641 {
642 	u8 next = cdev->next_string_id;
643 
644 	for (; str->s; ++str) {
645 		if (next >= 254)
646 			return -ENODEV;
647 		str->id = ++next;
648 	}
649 
650 	cdev->next_string_id = next;
651 
652 	return 0;
653 }
654 
655 /**
656  * usb_string_ids_n() - allocate unused string IDs in batch
657  * @c: the device whose string descriptor IDs are being allocated
658  * @n: number of string IDs to allocate
659  * Context: single threaded during gadget setup
660  *
661  * Returns the first requested ID.  This ID and next @n-1 IDs are now
662  * valid IDs.  At least provided that @n is non-zero because if it
663  * is, returns last requested ID which is now very useful information.
664  *
665  * @usb_string_ids_n() is called from bind() callbacks to allocate
666  * string IDs.	Drivers for functions, configurations, or gadgets will
667  * then store that ID in the appropriate descriptors and string table.
668  *
669  * All string identifier should be allocated using this,
670  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
671  * example different functions don't wrongly assign different meanings
672  * to the same identifier.
673  */
674 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
675 {
676 	u8 next = c->next_string_id;
677 
678 	if (n > 254 || next + n > 254)
679 		return -ENODEV;
680 
681 	c->next_string_id += n;
682 	return next + 1;
683 }
684 
685 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
686 {
687 	if (req->status || req->actual != req->length)
688 		debug("%s: setup complete --> %d, %d/%d\n", __func__,
689 				req->status, req->actual, req->length);
690 }
691 
692 /*
693  * The setup() callback implements all the ep0 functionality that's
694  * not handled lower down, in hardware or the hardware driver(like
695  * device and endpoint feature flags, and their status).  It's all
696  * housekeeping for the gadget function we're implementing.  Most of
697  * the work is in config and function specific setup.
698  */
699 static int
700 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
701 {
702 	u16				w_length = le16_to_cpu(ctrl->wLength);
703 	u16				w_index = le16_to_cpu(ctrl->wIndex);
704 	u16				w_value = le16_to_cpu(ctrl->wValue);
705 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
706 	u8				intf = w_index & 0xFF;
707 	int				value = -EOPNOTSUPP;
708 	struct usb_request		*req = cdev->req;
709 	struct usb_function		*f = NULL;
710 	int				standard;
711 	u8				endp;
712 	struct usb_configuration	*c;
713 
714 	/*
715 	 * partial re-init of the response message; the function or the
716 	 * gadget might need to intercept e.g. a control-OUT completion
717 	 * when we delegate to it.
718 	 */
719 	req->zero = 0;
720 	req->complete = composite_setup_complete;
721 	req->length = USB_BUFSIZ;
722 	gadget->ep0->driver_data = cdev;
723 	standard = (ctrl->bRequestType & USB_TYPE_MASK)
724 						== USB_TYPE_STANDARD;
725 	if (!standard)
726 		goto unknown;
727 
728 	switch (ctrl->bRequest) {
729 
730 	/* we handle all standard USB descriptors */
731 	case USB_REQ_GET_DESCRIPTOR:
732 		if (ctrl->bRequestType != USB_DIR_IN)
733 			goto unknown;
734 		switch (w_value >> 8) {
735 
736 		case USB_DT_DEVICE:
737 			cdev->desc.bNumConfigurations =
738 				count_configs(cdev, USB_DT_DEVICE);
739 			cdev->desc.bMaxPacketSize0 =
740 				cdev->gadget->ep0->maxpacket;
741 			value = min(w_length, (u16) sizeof cdev->desc);
742 			memcpy(req->buf, &cdev->desc, value);
743 			break;
744 		case USB_DT_DEVICE_QUALIFIER:
745 			if (!gadget_is_dualspeed(gadget))
746 				break;
747 			device_qual(cdev);
748 			value = min_t(int, w_length,
749 				      sizeof(struct usb_qualifier_descriptor));
750 			break;
751 		case USB_DT_OTHER_SPEED_CONFIG:
752 			if (!gadget_is_dualspeed(gadget))
753 				break;
754 
755 		case USB_DT_CONFIG:
756 			value = config_desc(cdev, w_value);
757 			if (value >= 0)
758 				value = min(w_length, (u16) value);
759 			break;
760 		case USB_DT_STRING:
761 			value = get_string(cdev, req->buf,
762 					w_index, w_value & 0xff);
763 			if (value >= 0)
764 				value = min(w_length, (u16) value);
765 			break;
766 		case USB_DT_BOS:
767 			/*
768 			 * The USB compliance test (USB 2.0 Command Verifier)
769 			 * issues this request. We should not run into the
770 			 * default path here. But return for now until
771 			 * the superspeed support is added.
772 			 */
773 			break;
774 		default:
775 			goto unknown;
776 		}
777 		break;
778 
779 	/* any number of configs can work */
780 	case USB_REQ_SET_CONFIGURATION:
781 		if (ctrl->bRequestType != 0)
782 			goto unknown;
783 		if (gadget_is_otg(gadget)) {
784 			if (gadget->a_hnp_support)
785 				debug("HNP available\n");
786 			else if (gadget->a_alt_hnp_support)
787 				debug("HNP on another port\n");
788 			else
789 				debug("HNP inactive\n");
790 		}
791 
792 		value = set_config(cdev, ctrl, w_value);
793 		break;
794 	case USB_REQ_GET_CONFIGURATION:
795 		if (ctrl->bRequestType != USB_DIR_IN)
796 			goto unknown;
797 		if (cdev->config)
798 			*(u8 *)req->buf = cdev->config->bConfigurationValue;
799 		else
800 			*(u8 *)req->buf = 0;
801 		value = min(w_length, (u16) 1);
802 		break;
803 
804 	/*
805 	 * function drivers must handle get/set altsetting; if there's
806 	 * no get() method, we know only altsetting zero works.
807 	 */
808 	case USB_REQ_SET_INTERFACE:
809 		if (ctrl->bRequestType != USB_RECIP_INTERFACE)
810 			goto unknown;
811 		if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
812 			break;
813 		f = cdev->config->interface[intf];
814 		if (!f)
815 			break;
816 		if (w_value && !f->set_alt)
817 			break;
818 		value = f->set_alt(f, w_index, w_value);
819 		break;
820 	case USB_REQ_GET_INTERFACE:
821 		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
822 			goto unknown;
823 		if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
824 			break;
825 		f = cdev->config->interface[intf];
826 		if (!f)
827 			break;
828 		/* lots of interfaces only need altsetting zero... */
829 		value = f->get_alt ? f->get_alt(f, w_index) : 0;
830 		if (value < 0)
831 			break;
832 		*((u8 *)req->buf) = value;
833 		value = min(w_length, (u16) 1);
834 		break;
835 	default:
836 unknown:
837 		debug("non-core control req%02x.%02x v%04x i%04x l%d\n",
838 			ctrl->bRequestType, ctrl->bRequest,
839 			w_value, w_index, w_length);
840 
841 		/*
842 		 * functions always handle their interfaces and endpoints...
843 		 * punt other recipients (other, WUSB, ...) to the current
844 		 * configuration code.
845 		 */
846 		switch (ctrl->bRequestType & USB_RECIP_MASK) {
847 		case USB_RECIP_INTERFACE:
848 			f = cdev->config->interface[intf];
849 			break;
850 
851 		case USB_RECIP_ENDPOINT:
852 			endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
853 			list_for_each_entry(f, &cdev->config->functions, list) {
854 				if (test_bit(endp, f->endpoints))
855 					break;
856 			}
857 			if (&f->list == &cdev->config->functions)
858 				f = NULL;
859 			break;
860 		/*
861 		 * dfu-util (version 0.5) sets bmRequestType.Receipent = Device
862 		 * for non-standard request (w_value = 0x21,
863 		 * bRequest = GET_DESCRIPTOR in this case).
864 		 * When only one interface is registered (as it is done now),
865 		 * then this request shall be handled as it was requested for
866 		 * interface.
867 		 *
868 		 * In the below code it is checked if only one interface is
869 		 * present and proper function for it is extracted. Due to that
870 		 * function's setup (f->setup) is called to handle this
871 		 * special non-standard request.
872 		 */
873 		case USB_RECIP_DEVICE:
874 			debug("cdev->config->next_interface_id: %d intf: %d\n",
875 			       cdev->config->next_interface_id, intf);
876 			if (cdev->config->next_interface_id == 1)
877 				f = cdev->config->interface[intf];
878 			break;
879 		}
880 
881 		if (f && f->setup)
882 			value = f->setup(f, ctrl);
883 		else {
884 			c = cdev->config;
885 			if (c && c->setup)
886 				value = c->setup(c, ctrl);
887 		}
888 
889 		goto done;
890 	}
891 
892 	/* respond with data transfer before status phase? */
893 	if (value >= 0) {
894 		req->length = value;
895 		req->zero = value < w_length;
896 		value = usb_ep_queue(gadget->ep0, req, GFP_KERNEL);
897 		if (value < 0) {
898 			debug("ep_queue --> %d\n", value);
899 			req->status = 0;
900 			composite_setup_complete(gadget->ep0, req);
901 		}
902 	}
903 
904 done:
905 	/* device either stalls (value < 0) or reports success */
906 	return value;
907 }
908 
909 static void composite_disconnect(struct usb_gadget *gadget)
910 {
911 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
912 
913 	if (cdev->config)
914 		reset_config(cdev);
915 	if (composite->disconnect)
916 		composite->disconnect(cdev);
917 }
918 
919 static void composite_unbind(struct usb_gadget *gadget)
920 {
921 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
922 	struct usb_configuration	*c;
923 	struct usb_function		*f;
924 
925 	/*
926 	 * composite_disconnect() must already have been called
927 	 * by the underlying peripheral controller driver!
928 	 * so there's no i/o concurrency that could affect the
929 	 * state protected by cdev->lock.
930 	 */
931 	BUG_ON(cdev->config);
932 
933 	while (!list_empty(&cdev->configs)) {
934 		c = list_first_entry(&cdev->configs,
935 				struct usb_configuration, list);
936 		while (!list_empty(&c->functions)) {
937 			f = list_first_entry(&c->functions,
938 					struct usb_function, list);
939 			list_del(&f->list);
940 			if (f->unbind) {
941 				debug("unbind function '%s'/%p\n",
942 						f->name, f);
943 				f->unbind(c, f);
944 			}
945 		}
946 		list_del(&c->list);
947 		if (c->unbind) {
948 			debug("unbind config '%s'/%p\n", c->label, c);
949 			c->unbind(c);
950 		}
951 		free(c);
952 	}
953 	if (composite->unbind)
954 		composite->unbind(cdev);
955 
956 	if (cdev->req) {
957 		kfree(cdev->req->buf);
958 		usb_ep_free_request(gadget->ep0, cdev->req);
959 	}
960 	kfree(cdev);
961 	set_gadget_data(gadget, NULL);
962 
963 	composite = NULL;
964 }
965 
966 static int composite_bind(struct usb_gadget *gadget)
967 {
968 	int				status = -ENOMEM;
969 	struct usb_composite_dev	*cdev;
970 
971 	cdev = calloc(sizeof *cdev, 1);
972 	if (!cdev)
973 		return status;
974 
975 	cdev->gadget = gadget;
976 	set_gadget_data(gadget, cdev);
977 	INIT_LIST_HEAD(&cdev->configs);
978 
979 	/* preallocate control response and buffer */
980 	cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
981 	if (!cdev->req)
982 		goto fail;
983 	cdev->req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, USB_BUFSIZ);
984 	if (!cdev->req->buf)
985 		goto fail;
986 	cdev->req->complete = composite_setup_complete;
987 	gadget->ep0->driver_data = cdev;
988 
989 	cdev->bufsiz = USB_BUFSIZ;
990 	cdev->driver = composite;
991 
992 	usb_gadget_set_selfpowered(gadget);
993 	usb_ep_autoconfig_reset(cdev->gadget);
994 
995 	status = composite->bind(cdev);
996 	if (status < 0)
997 		goto fail;
998 
999 	memcpy(&cdev->desc, composite->dev,
1000 	       sizeof(struct usb_device_descriptor));
1001 	cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1002 
1003 	debug("%s: ready\n", composite->name);
1004 	return 0;
1005 
1006 fail:
1007 	composite_unbind(gadget);
1008 	return status;
1009 }
1010 
1011 static void
1012 composite_suspend(struct usb_gadget *gadget)
1013 {
1014 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1015 	struct usb_function		*f;
1016 
1017 	debug("%s: suspend\n", __func__);
1018 	if (cdev->config) {
1019 		list_for_each_entry(f, &cdev->config->functions, list) {
1020 			if (f->suspend)
1021 				f->suspend(f);
1022 		}
1023 	}
1024 	if (composite->suspend)
1025 		composite->suspend(cdev);
1026 
1027 	cdev->suspended = 1;
1028 }
1029 
1030 static void
1031 composite_resume(struct usb_gadget *gadget)
1032 {
1033 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1034 	struct usb_function		*f;
1035 
1036 	debug("%s: resume\n", __func__);
1037 	if (composite->resume)
1038 		composite->resume(cdev);
1039 	if (cdev->config) {
1040 		list_for_each_entry(f, &cdev->config->functions, list) {
1041 			if (f->resume)
1042 				f->resume(f);
1043 		}
1044 	}
1045 
1046 	cdev->suspended = 0;
1047 }
1048 
1049 static struct usb_gadget_driver composite_driver = {
1050 	.speed		= USB_SPEED_HIGH,
1051 
1052 	.bind		= composite_bind,
1053 	.unbind         = composite_unbind,
1054 
1055 	.setup		= composite_setup,
1056 	.reset          = composite_disconnect,
1057 	.disconnect	= composite_disconnect,
1058 
1059 	.suspend        = composite_suspend,
1060 	.resume         = composite_resume,
1061 };
1062 
1063 /**
1064  * usb_composite_register() - register a composite driver
1065  * @driver: the driver to register
1066  * Context: single threaded during gadget setup
1067  *
1068  * This function is used to register drivers using the composite driver
1069  * framework.  The return value is zero, or a negative errno value.
1070  * Those values normally come from the driver's @bind method, which does
1071  * all the work of setting up the driver to match the hardware.
1072  *
1073  * On successful return, the gadget is ready to respond to requests from
1074  * the host, unless one of its components invokes usb_gadget_disconnect()
1075  * while it was binding.  That would usually be done in order to wait for
1076  * some userspace participation.
1077  */
1078 int usb_composite_register(struct usb_composite_driver *driver)
1079 {
1080 	int res;
1081 
1082 	if (!driver || !driver->dev || !driver->bind || composite)
1083 		return -EINVAL;
1084 
1085 	if (!driver->name)
1086 		driver->name = "composite";
1087 	composite = driver;
1088 
1089 	res = usb_gadget_register_driver(&composite_driver);
1090 	if (res != 0)
1091 		composite = NULL;
1092 
1093 	return res;
1094 }
1095 
1096 /**
1097  * usb_composite_unregister() - unregister a composite driver
1098  * @driver: the driver to unregister
1099  *
1100  * This function is used to unregister drivers using the composite
1101  * driver framework.
1102  */
1103 void usb_composite_unregister(struct usb_composite_driver *driver)
1104 {
1105 	if (composite != driver)
1106 		return;
1107 	usb_gadget_unregister_driver(&composite_driver);
1108 	composite = NULL;
1109 }
1110