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