xref: /openbmc/linux/drivers/usb/gadget/composite.c (revision 5fd54ace)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * composite.c - infrastructure for Composite USB Gadgets
4  *
5  * Copyright (C) 2006-2008 David Brownell
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12 
13 /* #define VERBOSE_DEBUG */
14 
15 #include <linux/kallsyms.h>
16 #include <linux/kernel.h>
17 #include <linux/slab.h>
18 #include <linux/module.h>
19 #include <linux/device.h>
20 #include <linux/utsname.h>
21 
22 #include <linux/usb/composite.h>
23 #include <linux/usb/otg.h>
24 #include <asm/unaligned.h>
25 
26 #include "u_os_desc.h"
27 
28 /**
29  * struct usb_os_string - represents OS String to be reported by a gadget
30  * @bLength: total length of the entire descritor, always 0x12
31  * @bDescriptorType: USB_DT_STRING
32  * @qwSignature: the OS String proper
33  * @bMS_VendorCode: code used by the host for subsequent requests
34  * @bPad: not used, must be zero
35  */
36 struct usb_os_string {
37 	__u8	bLength;
38 	__u8	bDescriptorType;
39 	__u8	qwSignature[OS_STRING_QW_SIGN_LEN];
40 	__u8	bMS_VendorCode;
41 	__u8	bPad;
42 } __packed;
43 
44 /*
45  * The code in this file is utility code, used to build a gadget driver
46  * from one or more "function" drivers, one or more "configuration"
47  * objects, and a "usb_composite_driver" by gluing them together along
48  * with the relevant device-wide data.
49  */
50 
51 static struct usb_gadget_strings **get_containers_gs(
52 		struct usb_gadget_string_container *uc)
53 {
54 	return (struct usb_gadget_strings **)uc->stash;
55 }
56 
57 /**
58  * function_descriptors() - get function descriptors for speed
59  * @f: the function
60  * @speed: the speed
61  *
62  * Returns the descriptors or NULL if not set.
63  */
64 static struct usb_descriptor_header **
65 function_descriptors(struct usb_function *f,
66 		     enum usb_device_speed speed)
67 {
68 	struct usb_descriptor_header **descriptors;
69 
70 	/*
71 	 * NOTE: we try to help gadget drivers which might not be setting
72 	 * max_speed appropriately.
73 	 */
74 
75 	switch (speed) {
76 	case USB_SPEED_SUPER_PLUS:
77 		descriptors = f->ssp_descriptors;
78 		if (descriptors)
79 			break;
80 		/* FALLTHROUGH */
81 	case USB_SPEED_SUPER:
82 		descriptors = f->ss_descriptors;
83 		if (descriptors)
84 			break;
85 		/* FALLTHROUGH */
86 	case USB_SPEED_HIGH:
87 		descriptors = f->hs_descriptors;
88 		if (descriptors)
89 			break;
90 		/* FALLTHROUGH */
91 	default:
92 		descriptors = f->fs_descriptors;
93 	}
94 
95 	/*
96 	 * if we can't find any descriptors at all, then this gadget deserves to
97 	 * Oops with a NULL pointer dereference
98 	 */
99 
100 	return descriptors;
101 }
102 
103 /**
104  * next_ep_desc() - advance to the next EP descriptor
105  * @t: currect pointer within descriptor array
106  *
107  * Return: next EP descriptor or NULL
108  *
109  * Iterate over @t until either EP descriptor found or
110  * NULL (that indicates end of list) encountered
111  */
112 static struct usb_descriptor_header**
113 next_ep_desc(struct usb_descriptor_header **t)
114 {
115 	for (; *t; t++) {
116 		if ((*t)->bDescriptorType == USB_DT_ENDPOINT)
117 			return t;
118 	}
119 	return NULL;
120 }
121 
122 /*
123  * for_each_ep_desc()- iterate over endpoint descriptors in the
124  *		descriptors list
125  * @start:	pointer within descriptor array.
126  * @ep_desc:	endpoint descriptor to use as the loop cursor
127  */
128 #define for_each_ep_desc(start, ep_desc) \
129 	for (ep_desc = next_ep_desc(start); \
130 	      ep_desc; ep_desc = next_ep_desc(ep_desc+1))
131 
132 /**
133  * config_ep_by_speed() - configures the given endpoint
134  * according to gadget speed.
135  * @g: pointer to the gadget
136  * @f: usb function
137  * @_ep: the endpoint to configure
138  *
139  * Return: error code, 0 on success
140  *
141  * This function chooses the right descriptors for a given
142  * endpoint according to gadget speed and saves it in the
143  * endpoint desc field. If the endpoint already has a descriptor
144  * assigned to it - overwrites it with currently corresponding
145  * descriptor. The endpoint maxpacket field is updated according
146  * to the chosen descriptor.
147  * Note: the supplied function should hold all the descriptors
148  * for supported speeds
149  */
150 int config_ep_by_speed(struct usb_gadget *g,
151 			struct usb_function *f,
152 			struct usb_ep *_ep)
153 {
154 	struct usb_composite_dev	*cdev = get_gadget_data(g);
155 	struct usb_endpoint_descriptor *chosen_desc = NULL;
156 	struct usb_descriptor_header **speed_desc = NULL;
157 
158 	struct usb_ss_ep_comp_descriptor *comp_desc = NULL;
159 	int want_comp_desc = 0;
160 
161 	struct usb_descriptor_header **d_spd; /* cursor for speed desc */
162 
163 	if (!g || !f || !_ep)
164 		return -EIO;
165 
166 	/* select desired speed */
167 	switch (g->speed) {
168 	case USB_SPEED_SUPER_PLUS:
169 		if (gadget_is_superspeed_plus(g)) {
170 			speed_desc = f->ssp_descriptors;
171 			want_comp_desc = 1;
172 			break;
173 		}
174 		/* fall through */
175 	case USB_SPEED_SUPER:
176 		if (gadget_is_superspeed(g)) {
177 			speed_desc = f->ss_descriptors;
178 			want_comp_desc = 1;
179 			break;
180 		}
181 		/* fall through */
182 	case USB_SPEED_HIGH:
183 		if (gadget_is_dualspeed(g)) {
184 			speed_desc = f->hs_descriptors;
185 			break;
186 		}
187 		/* fall through */
188 	default:
189 		speed_desc = f->fs_descriptors;
190 	}
191 	/* find descriptors */
192 	for_each_ep_desc(speed_desc, d_spd) {
193 		chosen_desc = (struct usb_endpoint_descriptor *)*d_spd;
194 		if (chosen_desc->bEndpointAddress == _ep->address)
195 			goto ep_found;
196 	}
197 	return -EIO;
198 
199 ep_found:
200 	/* commit results */
201 	_ep->maxpacket = usb_endpoint_maxp(chosen_desc);
202 	_ep->desc = chosen_desc;
203 	_ep->comp_desc = NULL;
204 	_ep->maxburst = 0;
205 	_ep->mult = 1;
206 
207 	if (g->speed == USB_SPEED_HIGH && (usb_endpoint_xfer_isoc(_ep->desc) ||
208 				usb_endpoint_xfer_int(_ep->desc)))
209 		_ep->mult = usb_endpoint_maxp_mult(_ep->desc);
210 
211 	if (!want_comp_desc)
212 		return 0;
213 
214 	/*
215 	 * Companion descriptor should follow EP descriptor
216 	 * USB 3.0 spec, #9.6.7
217 	 */
218 	comp_desc = (struct usb_ss_ep_comp_descriptor *)*(++d_spd);
219 	if (!comp_desc ||
220 	    (comp_desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP))
221 		return -EIO;
222 	_ep->comp_desc = comp_desc;
223 	if (g->speed >= USB_SPEED_SUPER) {
224 		switch (usb_endpoint_type(_ep->desc)) {
225 		case USB_ENDPOINT_XFER_ISOC:
226 			/* mult: bits 1:0 of bmAttributes */
227 			_ep->mult = (comp_desc->bmAttributes & 0x3) + 1;
228 			/* fall through */
229 		case USB_ENDPOINT_XFER_BULK:
230 		case USB_ENDPOINT_XFER_INT:
231 			_ep->maxburst = comp_desc->bMaxBurst + 1;
232 			break;
233 		default:
234 			if (comp_desc->bMaxBurst != 0)
235 				ERROR(cdev, "ep0 bMaxBurst must be 0\n");
236 			_ep->maxburst = 1;
237 			break;
238 		}
239 	}
240 	return 0;
241 }
242 EXPORT_SYMBOL_GPL(config_ep_by_speed);
243 
244 /**
245  * usb_add_function() - add a function to a configuration
246  * @config: the configuration
247  * @function: the function being added
248  * Context: single threaded during gadget setup
249  *
250  * After initialization, each configuration must have one or more
251  * functions added to it.  Adding a function involves calling its @bind()
252  * method to allocate resources such as interface and string identifiers
253  * and endpoints.
254  *
255  * This function returns the value of the function's bind(), which is
256  * zero for success else a negative errno value.
257  */
258 int usb_add_function(struct usb_configuration *config,
259 		struct usb_function *function)
260 {
261 	int	value = -EINVAL;
262 
263 	DBG(config->cdev, "adding '%s'/%p to config '%s'/%p\n",
264 			function->name, function,
265 			config->label, config);
266 
267 	if (!function->set_alt || !function->disable)
268 		goto done;
269 
270 	function->config = config;
271 	list_add_tail(&function->list, &config->functions);
272 
273 	if (function->bind_deactivated) {
274 		value = usb_function_deactivate(function);
275 		if (value)
276 			goto done;
277 	}
278 
279 	/* REVISIT *require* function->bind? */
280 	if (function->bind) {
281 		value = function->bind(config, function);
282 		if (value < 0) {
283 			list_del(&function->list);
284 			function->config = NULL;
285 		}
286 	} else
287 		value = 0;
288 
289 	/* We allow configurations that don't work at both speeds.
290 	 * If we run into a lowspeed Linux system, treat it the same
291 	 * as full speed ... it's the function drivers that will need
292 	 * to avoid bulk and ISO transfers.
293 	 */
294 	if (!config->fullspeed && function->fs_descriptors)
295 		config->fullspeed = true;
296 	if (!config->highspeed && function->hs_descriptors)
297 		config->highspeed = true;
298 	if (!config->superspeed && function->ss_descriptors)
299 		config->superspeed = true;
300 	if (!config->superspeed_plus && function->ssp_descriptors)
301 		config->superspeed_plus = true;
302 
303 done:
304 	if (value)
305 		DBG(config->cdev, "adding '%s'/%p --> %d\n",
306 				function->name, function, value);
307 	return value;
308 }
309 EXPORT_SYMBOL_GPL(usb_add_function);
310 
311 void usb_remove_function(struct usb_configuration *c, struct usb_function *f)
312 {
313 	if (f->disable)
314 		f->disable(f);
315 
316 	bitmap_zero(f->endpoints, 32);
317 	list_del(&f->list);
318 	if (f->unbind)
319 		f->unbind(c, f);
320 
321 	if (f->bind_deactivated)
322 		usb_function_activate(f);
323 }
324 EXPORT_SYMBOL_GPL(usb_remove_function);
325 
326 /**
327  * usb_function_deactivate - prevent function and gadget enumeration
328  * @function: the function that isn't yet ready to respond
329  *
330  * Blocks response of the gadget driver to host enumeration by
331  * preventing the data line pullup from being activated.  This is
332  * normally called during @bind() processing to change from the
333  * initial "ready to respond" state, or when a required resource
334  * becomes available.
335  *
336  * For example, drivers that serve as a passthrough to a userspace
337  * daemon can block enumeration unless that daemon (such as an OBEX,
338  * MTP, or print server) is ready to handle host requests.
339  *
340  * Not all systems support software control of their USB peripheral
341  * data pullups.
342  *
343  * Returns zero on success, else negative errno.
344  */
345 int usb_function_deactivate(struct usb_function *function)
346 {
347 	struct usb_composite_dev	*cdev = function->config->cdev;
348 	unsigned long			flags;
349 	int				status = 0;
350 
351 	spin_lock_irqsave(&cdev->lock, flags);
352 
353 	if (cdev->deactivations == 0)
354 		status = usb_gadget_deactivate(cdev->gadget);
355 	if (status == 0)
356 		cdev->deactivations++;
357 
358 	spin_unlock_irqrestore(&cdev->lock, flags);
359 	return status;
360 }
361 EXPORT_SYMBOL_GPL(usb_function_deactivate);
362 
363 /**
364  * usb_function_activate - allow function and gadget enumeration
365  * @function: function on which usb_function_activate() was called
366  *
367  * Reverses effect of usb_function_deactivate().  If no more functions
368  * are delaying their activation, the gadget driver will respond to
369  * host enumeration procedures.
370  *
371  * Returns zero on success, else negative errno.
372  */
373 int usb_function_activate(struct usb_function *function)
374 {
375 	struct usb_composite_dev	*cdev = function->config->cdev;
376 	unsigned long			flags;
377 	int				status = 0;
378 
379 	spin_lock_irqsave(&cdev->lock, flags);
380 
381 	if (WARN_ON(cdev->deactivations == 0))
382 		status = -EINVAL;
383 	else {
384 		cdev->deactivations--;
385 		if (cdev->deactivations == 0)
386 			status = usb_gadget_activate(cdev->gadget);
387 	}
388 
389 	spin_unlock_irqrestore(&cdev->lock, flags);
390 	return status;
391 }
392 EXPORT_SYMBOL_GPL(usb_function_activate);
393 
394 /**
395  * usb_interface_id() - allocate an unused interface ID
396  * @config: configuration associated with the interface
397  * @function: function handling the interface
398  * Context: single threaded during gadget setup
399  *
400  * usb_interface_id() is called from usb_function.bind() callbacks to
401  * allocate new interface IDs.  The function driver will then store that
402  * ID in interface, association, CDC union, and other descriptors.  It
403  * will also handle any control requests targeted at that interface,
404  * particularly changing its altsetting via set_alt().  There may
405  * also be class-specific or vendor-specific requests to handle.
406  *
407  * All interface identifier should be allocated using this routine, to
408  * ensure that for example different functions don't wrongly assign
409  * different meanings to the same identifier.  Note that since interface
410  * identifiers are configuration-specific, functions used in more than
411  * one configuration (or more than once in a given configuration) need
412  * multiple versions of the relevant descriptors.
413  *
414  * Returns the interface ID which was allocated; or -ENODEV if no
415  * more interface IDs can be allocated.
416  */
417 int usb_interface_id(struct usb_configuration *config,
418 		struct usb_function *function)
419 {
420 	unsigned id = config->next_interface_id;
421 
422 	if (id < MAX_CONFIG_INTERFACES) {
423 		config->interface[id] = function;
424 		config->next_interface_id = id + 1;
425 		return id;
426 	}
427 	return -ENODEV;
428 }
429 EXPORT_SYMBOL_GPL(usb_interface_id);
430 
431 static u8 encode_bMaxPower(enum usb_device_speed speed,
432 		struct usb_configuration *c)
433 {
434 	unsigned val;
435 
436 	if (c->MaxPower)
437 		val = c->MaxPower;
438 	else
439 		val = CONFIG_USB_GADGET_VBUS_DRAW;
440 	if (!val)
441 		return 0;
442 	switch (speed) {
443 	case USB_SPEED_SUPER:
444 		return DIV_ROUND_UP(val, 8);
445 	default:
446 		return DIV_ROUND_UP(val, 2);
447 	}
448 }
449 
450 static int config_buf(struct usb_configuration *config,
451 		enum usb_device_speed speed, void *buf, u8 type)
452 {
453 	struct usb_config_descriptor	*c = buf;
454 	void				*next = buf + USB_DT_CONFIG_SIZE;
455 	int				len;
456 	struct usb_function		*f;
457 	int				status;
458 
459 	len = USB_COMP_EP0_BUFSIZ - USB_DT_CONFIG_SIZE;
460 	/* write the config descriptor */
461 	c = buf;
462 	c->bLength = USB_DT_CONFIG_SIZE;
463 	c->bDescriptorType = type;
464 	/* wTotalLength is written later */
465 	c->bNumInterfaces = config->next_interface_id;
466 	c->bConfigurationValue = config->bConfigurationValue;
467 	c->iConfiguration = config->iConfiguration;
468 	c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
469 	c->bMaxPower = encode_bMaxPower(speed, config);
470 
471 	/* There may be e.g. OTG descriptors */
472 	if (config->descriptors) {
473 		status = usb_descriptor_fillbuf(next, len,
474 				config->descriptors);
475 		if (status < 0)
476 			return status;
477 		len -= status;
478 		next += status;
479 	}
480 
481 	/* add each function's descriptors */
482 	list_for_each_entry(f, &config->functions, list) {
483 		struct usb_descriptor_header **descriptors;
484 
485 		descriptors = function_descriptors(f, speed);
486 		if (!descriptors)
487 			continue;
488 		status = usb_descriptor_fillbuf(next, len,
489 			(const struct usb_descriptor_header **) descriptors);
490 		if (status < 0)
491 			return status;
492 		len -= status;
493 		next += status;
494 	}
495 
496 	len = next - buf;
497 	c->wTotalLength = cpu_to_le16(len);
498 	return len;
499 }
500 
501 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
502 {
503 	struct usb_gadget		*gadget = cdev->gadget;
504 	struct usb_configuration	*c;
505 	struct list_head		*pos;
506 	u8				type = w_value >> 8;
507 	enum usb_device_speed		speed = USB_SPEED_UNKNOWN;
508 
509 	if (gadget->speed >= USB_SPEED_SUPER)
510 		speed = gadget->speed;
511 	else if (gadget_is_dualspeed(gadget)) {
512 		int	hs = 0;
513 		if (gadget->speed == USB_SPEED_HIGH)
514 			hs = 1;
515 		if (type == USB_DT_OTHER_SPEED_CONFIG)
516 			hs = !hs;
517 		if (hs)
518 			speed = USB_SPEED_HIGH;
519 
520 	}
521 
522 	/* This is a lookup by config *INDEX* */
523 	w_value &= 0xff;
524 
525 	pos = &cdev->configs;
526 	c = cdev->os_desc_config;
527 	if (c)
528 		goto check_config;
529 
530 	while ((pos = pos->next) !=  &cdev->configs) {
531 		c = list_entry(pos, typeof(*c), list);
532 
533 		/* skip OS Descriptors config which is handled separately */
534 		if (c == cdev->os_desc_config)
535 			continue;
536 
537 check_config:
538 		/* ignore configs that won't work at this speed */
539 		switch (speed) {
540 		case USB_SPEED_SUPER_PLUS:
541 			if (!c->superspeed_plus)
542 				continue;
543 			break;
544 		case USB_SPEED_SUPER:
545 			if (!c->superspeed)
546 				continue;
547 			break;
548 		case USB_SPEED_HIGH:
549 			if (!c->highspeed)
550 				continue;
551 			break;
552 		default:
553 			if (!c->fullspeed)
554 				continue;
555 		}
556 
557 		if (w_value == 0)
558 			return config_buf(c, speed, cdev->req->buf, type);
559 		w_value--;
560 	}
561 	return -EINVAL;
562 }
563 
564 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
565 {
566 	struct usb_gadget		*gadget = cdev->gadget;
567 	struct usb_configuration	*c;
568 	unsigned			count = 0;
569 	int				hs = 0;
570 	int				ss = 0;
571 	int				ssp = 0;
572 
573 	if (gadget_is_dualspeed(gadget)) {
574 		if (gadget->speed == USB_SPEED_HIGH)
575 			hs = 1;
576 		if (gadget->speed == USB_SPEED_SUPER)
577 			ss = 1;
578 		if (gadget->speed == USB_SPEED_SUPER_PLUS)
579 			ssp = 1;
580 		if (type == USB_DT_DEVICE_QUALIFIER)
581 			hs = !hs;
582 	}
583 	list_for_each_entry(c, &cdev->configs, list) {
584 		/* ignore configs that won't work at this speed */
585 		if (ssp) {
586 			if (!c->superspeed_plus)
587 				continue;
588 		} else if (ss) {
589 			if (!c->superspeed)
590 				continue;
591 		} else if (hs) {
592 			if (!c->highspeed)
593 				continue;
594 		} else {
595 			if (!c->fullspeed)
596 				continue;
597 		}
598 		count++;
599 	}
600 	return count;
601 }
602 
603 /**
604  * bos_desc() - prepares the BOS descriptor.
605  * @cdev: pointer to usb_composite device to generate the bos
606  *	descriptor for
607  *
608  * This function generates the BOS (Binary Device Object)
609  * descriptor and its device capabilities descriptors. The BOS
610  * descriptor should be supported by a SuperSpeed device.
611  */
612 static int bos_desc(struct usb_composite_dev *cdev)
613 {
614 	struct usb_ext_cap_descriptor	*usb_ext;
615 	struct usb_dcd_config_params	dcd_config_params;
616 	struct usb_bos_descriptor	*bos = cdev->req->buf;
617 
618 	bos->bLength = USB_DT_BOS_SIZE;
619 	bos->bDescriptorType = USB_DT_BOS;
620 
621 	bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
622 	bos->bNumDeviceCaps = 0;
623 
624 	/*
625 	 * A SuperSpeed device shall include the USB2.0 extension descriptor
626 	 * and shall support LPM when operating in USB2.0 HS mode.
627 	 */
628 	usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
629 	bos->bNumDeviceCaps++;
630 	le16_add_cpu(&bos->wTotalLength, USB_DT_USB_EXT_CAP_SIZE);
631 	usb_ext->bLength = USB_DT_USB_EXT_CAP_SIZE;
632 	usb_ext->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
633 	usb_ext->bDevCapabilityType = USB_CAP_TYPE_EXT;
634 	usb_ext->bmAttributes = cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
635 
636 	/*
637 	 * The Superspeed USB Capability descriptor shall be implemented by all
638 	 * SuperSpeed devices.
639 	 */
640 	if (gadget_is_superspeed(cdev->gadget)) {
641 		struct usb_ss_cap_descriptor *ss_cap;
642 
643 		ss_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
644 		bos->bNumDeviceCaps++;
645 		le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SS_CAP_SIZE);
646 		ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
647 		ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
648 		ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
649 		ss_cap->bmAttributes = 0; /* LTM is not supported yet */
650 		ss_cap->wSpeedSupported = cpu_to_le16(USB_LOW_SPEED_OPERATION |
651 						      USB_FULL_SPEED_OPERATION |
652 						      USB_HIGH_SPEED_OPERATION |
653 						      USB_5GBPS_OPERATION);
654 		ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
655 
656 		/* Get Controller configuration */
657 		if (cdev->gadget->ops->get_config_params) {
658 			cdev->gadget->ops->get_config_params(
659 				&dcd_config_params);
660 		} else {
661 			dcd_config_params.bU1devExitLat =
662 				USB_DEFAULT_U1_DEV_EXIT_LAT;
663 			dcd_config_params.bU2DevExitLat =
664 				cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
665 		}
666 		ss_cap->bU1devExitLat = dcd_config_params.bU1devExitLat;
667 		ss_cap->bU2DevExitLat = dcd_config_params.bU2DevExitLat;
668 	}
669 
670 	/* The SuperSpeedPlus USB Device Capability descriptor */
671 	if (gadget_is_superspeed_plus(cdev->gadget)) {
672 		struct usb_ssp_cap_descriptor *ssp_cap;
673 
674 		ssp_cap = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
675 		bos->bNumDeviceCaps++;
676 
677 		/*
678 		 * Report typical values.
679 		 */
680 
681 		le16_add_cpu(&bos->wTotalLength, USB_DT_USB_SSP_CAP_SIZE(1));
682 		ssp_cap->bLength = USB_DT_USB_SSP_CAP_SIZE(1);
683 		ssp_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
684 		ssp_cap->bDevCapabilityType = USB_SSP_CAP_TYPE;
685 		ssp_cap->bReserved = 0;
686 		ssp_cap->wReserved = 0;
687 
688 		/* SSAC = 1 (2 attributes) */
689 		ssp_cap->bmAttributes = cpu_to_le32(1);
690 
691 		/* Min RX/TX Lane Count = 1 */
692 		ssp_cap->wFunctionalitySupport =
693 			cpu_to_le16((1 << 8) | (1 << 12));
694 
695 		/*
696 		 * bmSublinkSpeedAttr[0]:
697 		 *   ST  = Symmetric, RX
698 		 *   LSE =  3 (Gbps)
699 		 *   LP  =  1 (SuperSpeedPlus)
700 		 *   LSM = 10 (10 Gbps)
701 		 */
702 		ssp_cap->bmSublinkSpeedAttr[0] =
703 			cpu_to_le32((3 << 4) | (1 << 14) | (0xa << 16));
704 		/*
705 		 * bmSublinkSpeedAttr[1] =
706 		 *   ST  = Symmetric, TX
707 		 *   LSE =  3 (Gbps)
708 		 *   LP  =  1 (SuperSpeedPlus)
709 		 *   LSM = 10 (10 Gbps)
710 		 */
711 		ssp_cap->bmSublinkSpeedAttr[1] =
712 			cpu_to_le32((3 << 4) | (1 << 14) |
713 				    (0xa << 16) | (1 << 7));
714 	}
715 
716 	return le16_to_cpu(bos->wTotalLength);
717 }
718 
719 static void device_qual(struct usb_composite_dev *cdev)
720 {
721 	struct usb_qualifier_descriptor	*qual = cdev->req->buf;
722 
723 	qual->bLength = sizeof(*qual);
724 	qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
725 	/* POLICY: same bcdUSB and device type info at both speeds */
726 	qual->bcdUSB = cdev->desc.bcdUSB;
727 	qual->bDeviceClass = cdev->desc.bDeviceClass;
728 	qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
729 	qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
730 	/* ASSUME same EP0 fifo size at both speeds */
731 	qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
732 	qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
733 	qual->bRESERVED = 0;
734 }
735 
736 /*-------------------------------------------------------------------------*/
737 
738 static void reset_config(struct usb_composite_dev *cdev)
739 {
740 	struct usb_function		*f;
741 
742 	DBG(cdev, "reset config\n");
743 
744 	list_for_each_entry(f, &cdev->config->functions, list) {
745 		if (f->disable)
746 			f->disable(f);
747 
748 		bitmap_zero(f->endpoints, 32);
749 	}
750 	cdev->config = NULL;
751 	cdev->delayed_status = 0;
752 }
753 
754 static int set_config(struct usb_composite_dev *cdev,
755 		const struct usb_ctrlrequest *ctrl, unsigned number)
756 {
757 	struct usb_gadget	*gadget = cdev->gadget;
758 	struct usb_configuration *c = NULL;
759 	int			result = -EINVAL;
760 	unsigned		power = gadget_is_otg(gadget) ? 8 : 100;
761 	int			tmp;
762 
763 	if (number) {
764 		list_for_each_entry(c, &cdev->configs, list) {
765 			if (c->bConfigurationValue == number) {
766 				/*
767 				 * We disable the FDs of the previous
768 				 * configuration only if the new configuration
769 				 * is a valid one
770 				 */
771 				if (cdev->config)
772 					reset_config(cdev);
773 				result = 0;
774 				break;
775 			}
776 		}
777 		if (result < 0)
778 			goto done;
779 	} else { /* Zero configuration value - need to reset the config */
780 		if (cdev->config)
781 			reset_config(cdev);
782 		result = 0;
783 	}
784 
785 	INFO(cdev, "%s config #%d: %s\n",
786 	     usb_speed_string(gadget->speed),
787 	     number, c ? c->label : "unconfigured");
788 
789 	if (!c)
790 		goto done;
791 
792 	usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
793 	cdev->config = c;
794 
795 	/* Initialize all interfaces by setting them to altsetting zero. */
796 	for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
797 		struct usb_function	*f = c->interface[tmp];
798 		struct usb_descriptor_header **descriptors;
799 
800 		if (!f)
801 			break;
802 
803 		/*
804 		 * Record which endpoints are used by the function. This is used
805 		 * to dispatch control requests targeted at that endpoint to the
806 		 * function's setup callback instead of the current
807 		 * configuration's setup callback.
808 		 */
809 		descriptors = function_descriptors(f, gadget->speed);
810 
811 		for (; *descriptors; ++descriptors) {
812 			struct usb_endpoint_descriptor *ep;
813 			int addr;
814 
815 			if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
816 				continue;
817 
818 			ep = (struct usb_endpoint_descriptor *)*descriptors;
819 			addr = ((ep->bEndpointAddress & 0x80) >> 3)
820 			     |  (ep->bEndpointAddress & 0x0f);
821 			set_bit(addr, f->endpoints);
822 		}
823 
824 		result = f->set_alt(f, tmp, 0);
825 		if (result < 0) {
826 			DBG(cdev, "interface %d (%s/%p) alt 0 --> %d\n",
827 					tmp, f->name, f, result);
828 
829 			reset_config(cdev);
830 			goto done;
831 		}
832 
833 		if (result == USB_GADGET_DELAYED_STATUS) {
834 			DBG(cdev,
835 			 "%s: interface %d (%s) requested delayed status\n",
836 					__func__, tmp, f->name);
837 			cdev->delayed_status++;
838 			DBG(cdev, "delayed_status count %d\n",
839 					cdev->delayed_status);
840 		}
841 	}
842 
843 	/* when we return, be sure our power usage is valid */
844 	power = c->MaxPower ? c->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
845 done:
846 	usb_gadget_vbus_draw(gadget, power);
847 	if (result >= 0 && cdev->delayed_status)
848 		result = USB_GADGET_DELAYED_STATUS;
849 	return result;
850 }
851 
852 int usb_add_config_only(struct usb_composite_dev *cdev,
853 		struct usb_configuration *config)
854 {
855 	struct usb_configuration *c;
856 
857 	if (!config->bConfigurationValue)
858 		return -EINVAL;
859 
860 	/* Prevent duplicate configuration identifiers */
861 	list_for_each_entry(c, &cdev->configs, list) {
862 		if (c->bConfigurationValue == config->bConfigurationValue)
863 			return -EBUSY;
864 	}
865 
866 	config->cdev = cdev;
867 	list_add_tail(&config->list, &cdev->configs);
868 
869 	INIT_LIST_HEAD(&config->functions);
870 	config->next_interface_id = 0;
871 	memset(config->interface, 0, sizeof(config->interface));
872 
873 	return 0;
874 }
875 EXPORT_SYMBOL_GPL(usb_add_config_only);
876 
877 /**
878  * usb_add_config() - add a configuration to a device.
879  * @cdev: wraps the USB gadget
880  * @config: the configuration, with bConfigurationValue assigned
881  * @bind: the configuration's bind function
882  * Context: single threaded during gadget setup
883  *
884  * One of the main tasks of a composite @bind() routine is to
885  * add each of the configurations it supports, using this routine.
886  *
887  * This function returns the value of the configuration's @bind(), which
888  * is zero for success else a negative errno value.  Binding configurations
889  * assigns global resources including string IDs, and per-configuration
890  * resources such as interface IDs and endpoints.
891  */
892 int usb_add_config(struct usb_composite_dev *cdev,
893 		struct usb_configuration *config,
894 		int (*bind)(struct usb_configuration *))
895 {
896 	int				status = -EINVAL;
897 
898 	if (!bind)
899 		goto done;
900 
901 	DBG(cdev, "adding config #%u '%s'/%p\n",
902 			config->bConfigurationValue,
903 			config->label, config);
904 
905 	status = usb_add_config_only(cdev, config);
906 	if (status)
907 		goto done;
908 
909 	status = bind(config);
910 	if (status < 0) {
911 		while (!list_empty(&config->functions)) {
912 			struct usb_function		*f;
913 
914 			f = list_first_entry(&config->functions,
915 					struct usb_function, list);
916 			list_del(&f->list);
917 			if (f->unbind) {
918 				DBG(cdev, "unbind function '%s'/%p\n",
919 					f->name, f);
920 				f->unbind(config, f);
921 				/* may free memory for "f" */
922 			}
923 		}
924 		list_del(&config->list);
925 		config->cdev = NULL;
926 	} else {
927 		unsigned	i;
928 
929 		DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
930 			config->bConfigurationValue, config,
931 			config->superspeed_plus ? " superplus" : "",
932 			config->superspeed ? " super" : "",
933 			config->highspeed ? " high" : "",
934 			config->fullspeed
935 				? (gadget_is_dualspeed(cdev->gadget)
936 					? " full"
937 					: " full/low")
938 				: "");
939 
940 		for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
941 			struct usb_function	*f = config->interface[i];
942 
943 			if (!f)
944 				continue;
945 			DBG(cdev, "  interface %d = %s/%p\n",
946 				i, f->name, f);
947 		}
948 	}
949 
950 	/* set_alt(), or next bind(), sets up ep->claimed as needed */
951 	usb_ep_autoconfig_reset(cdev->gadget);
952 
953 done:
954 	if (status)
955 		DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
956 				config->bConfigurationValue, status);
957 	return status;
958 }
959 EXPORT_SYMBOL_GPL(usb_add_config);
960 
961 static void remove_config(struct usb_composite_dev *cdev,
962 			      struct usb_configuration *config)
963 {
964 	while (!list_empty(&config->functions)) {
965 		struct usb_function		*f;
966 
967 		f = list_first_entry(&config->functions,
968 				struct usb_function, list);
969 
970 		usb_remove_function(config, f);
971 	}
972 	list_del(&config->list);
973 	if (config->unbind) {
974 		DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
975 		config->unbind(config);
976 			/* may free memory for "c" */
977 	}
978 }
979 
980 /**
981  * usb_remove_config() - remove a configuration from a device.
982  * @cdev: wraps the USB gadget
983  * @config: the configuration
984  *
985  * Drivers must call usb_gadget_disconnect before calling this function
986  * to disconnect the device from the host and make sure the host will not
987  * try to enumerate the device while we are changing the config list.
988  */
989 void usb_remove_config(struct usb_composite_dev *cdev,
990 		      struct usb_configuration *config)
991 {
992 	unsigned long flags;
993 
994 	spin_lock_irqsave(&cdev->lock, flags);
995 
996 	if (cdev->config == config)
997 		reset_config(cdev);
998 
999 	spin_unlock_irqrestore(&cdev->lock, flags);
1000 
1001 	remove_config(cdev, config);
1002 }
1003 
1004 /*-------------------------------------------------------------------------*/
1005 
1006 /* We support strings in multiple languages ... string descriptor zero
1007  * says which languages are supported.  The typical case will be that
1008  * only one language (probably English) is used, with i18n handled on
1009  * the host side.
1010  */
1011 
1012 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1013 {
1014 	const struct usb_gadget_strings	*s;
1015 	__le16				language;
1016 	__le16				*tmp;
1017 
1018 	while (*sp) {
1019 		s = *sp;
1020 		language = cpu_to_le16(s->language);
1021 		for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
1022 			if (*tmp == language)
1023 				goto repeat;
1024 		}
1025 		*tmp++ = language;
1026 repeat:
1027 		sp++;
1028 	}
1029 }
1030 
1031 static int lookup_string(
1032 	struct usb_gadget_strings	**sp,
1033 	void				*buf,
1034 	u16				language,
1035 	int				id
1036 )
1037 {
1038 	struct usb_gadget_strings	*s;
1039 	int				value;
1040 
1041 	while (*sp) {
1042 		s = *sp++;
1043 		if (s->language != language)
1044 			continue;
1045 		value = usb_gadget_get_string(s, id, buf);
1046 		if (value > 0)
1047 			return value;
1048 	}
1049 	return -EINVAL;
1050 }
1051 
1052 static int get_string(struct usb_composite_dev *cdev,
1053 		void *buf, u16 language, int id)
1054 {
1055 	struct usb_composite_driver	*composite = cdev->driver;
1056 	struct usb_gadget_string_container *uc;
1057 	struct usb_configuration	*c;
1058 	struct usb_function		*f;
1059 	int				len;
1060 
1061 	/* Yes, not only is USB's i18n support probably more than most
1062 	 * folk will ever care about ... also, it's all supported here.
1063 	 * (Except for UTF8 support for Unicode's "Astral Planes".)
1064 	 */
1065 
1066 	/* 0 == report all available language codes */
1067 	if (id == 0) {
1068 		struct usb_string_descriptor	*s = buf;
1069 		struct usb_gadget_strings	**sp;
1070 
1071 		memset(s, 0, 256);
1072 		s->bDescriptorType = USB_DT_STRING;
1073 
1074 		sp = composite->strings;
1075 		if (sp)
1076 			collect_langs(sp, s->wData);
1077 
1078 		list_for_each_entry(c, &cdev->configs, list) {
1079 			sp = c->strings;
1080 			if (sp)
1081 				collect_langs(sp, s->wData);
1082 
1083 			list_for_each_entry(f, &c->functions, list) {
1084 				sp = f->strings;
1085 				if (sp)
1086 					collect_langs(sp, s->wData);
1087 			}
1088 		}
1089 		list_for_each_entry(uc, &cdev->gstrings, list) {
1090 			struct usb_gadget_strings **sp;
1091 
1092 			sp = get_containers_gs(uc);
1093 			collect_langs(sp, s->wData);
1094 		}
1095 
1096 		for (len = 0; len <= 126 && s->wData[len]; len++)
1097 			continue;
1098 		if (!len)
1099 			return -EINVAL;
1100 
1101 		s->bLength = 2 * (len + 1);
1102 		return s->bLength;
1103 	}
1104 
1105 	if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1106 		struct usb_os_string *b = buf;
1107 		b->bLength = sizeof(*b);
1108 		b->bDescriptorType = USB_DT_STRING;
1109 		compiletime_assert(
1110 			sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1111 			"qwSignature size must be equal to qw_sign");
1112 		memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1113 		b->bMS_VendorCode = cdev->b_vendor_code;
1114 		b->bPad = 0;
1115 		return sizeof(*b);
1116 	}
1117 
1118 	list_for_each_entry(uc, &cdev->gstrings, list) {
1119 		struct usb_gadget_strings **sp;
1120 
1121 		sp = get_containers_gs(uc);
1122 		len = lookup_string(sp, buf, language, id);
1123 		if (len > 0)
1124 			return len;
1125 	}
1126 
1127 	/* String IDs are device-scoped, so we look up each string
1128 	 * table we're told about.  These lookups are infrequent;
1129 	 * simpler-is-better here.
1130 	 */
1131 	if (composite->strings) {
1132 		len = lookup_string(composite->strings, buf, language, id);
1133 		if (len > 0)
1134 			return len;
1135 	}
1136 	list_for_each_entry(c, &cdev->configs, list) {
1137 		if (c->strings) {
1138 			len = lookup_string(c->strings, buf, language, id);
1139 			if (len > 0)
1140 				return len;
1141 		}
1142 		list_for_each_entry(f, &c->functions, list) {
1143 			if (!f->strings)
1144 				continue;
1145 			len = lookup_string(f->strings, buf, language, id);
1146 			if (len > 0)
1147 				return len;
1148 		}
1149 	}
1150 	return -EINVAL;
1151 }
1152 
1153 /**
1154  * usb_string_id() - allocate an unused string ID
1155  * @cdev: the device whose string descriptor IDs are being allocated
1156  * Context: single threaded during gadget setup
1157  *
1158  * @usb_string_id() is called from bind() callbacks to allocate
1159  * string IDs.  Drivers for functions, configurations, or gadgets will
1160  * then store that ID in the appropriate descriptors and string table.
1161  *
1162  * All string identifier should be allocated using this,
1163  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1164  * that for example different functions don't wrongly assign different
1165  * meanings to the same identifier.
1166  */
1167 int usb_string_id(struct usb_composite_dev *cdev)
1168 {
1169 	if (cdev->next_string_id < 254) {
1170 		/* string id 0 is reserved by USB spec for list of
1171 		 * supported languages */
1172 		/* 255 reserved as well? -- mina86 */
1173 		cdev->next_string_id++;
1174 		return cdev->next_string_id;
1175 	}
1176 	return -ENODEV;
1177 }
1178 EXPORT_SYMBOL_GPL(usb_string_id);
1179 
1180 /**
1181  * usb_string_ids() - allocate unused string IDs in batch
1182  * @cdev: the device whose string descriptor IDs are being allocated
1183  * @str: an array of usb_string objects to assign numbers to
1184  * Context: single threaded during gadget setup
1185  *
1186  * @usb_string_ids() is called from bind() callbacks to allocate
1187  * string IDs.  Drivers for functions, configurations, or gadgets will
1188  * then copy IDs from the string table to the appropriate descriptors
1189  * and string table for other languages.
1190  *
1191  * All string identifier should be allocated using this,
1192  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1193  * example different functions don't wrongly assign different meanings
1194  * to the same identifier.
1195  */
1196 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1197 {
1198 	int next = cdev->next_string_id;
1199 
1200 	for (; str->s; ++str) {
1201 		if (unlikely(next >= 254))
1202 			return -ENODEV;
1203 		str->id = ++next;
1204 	}
1205 
1206 	cdev->next_string_id = next;
1207 
1208 	return 0;
1209 }
1210 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1211 
1212 static struct usb_gadget_string_container *copy_gadget_strings(
1213 		struct usb_gadget_strings **sp, unsigned n_gstrings,
1214 		unsigned n_strings)
1215 {
1216 	struct usb_gadget_string_container *uc;
1217 	struct usb_gadget_strings **gs_array;
1218 	struct usb_gadget_strings *gs;
1219 	struct usb_string *s;
1220 	unsigned mem;
1221 	unsigned n_gs;
1222 	unsigned n_s;
1223 	void *stash;
1224 
1225 	mem = sizeof(*uc);
1226 	mem += sizeof(void *) * (n_gstrings + 1);
1227 	mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1228 	mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1229 	uc = kmalloc(mem, GFP_KERNEL);
1230 	if (!uc)
1231 		return ERR_PTR(-ENOMEM);
1232 	gs_array = get_containers_gs(uc);
1233 	stash = uc->stash;
1234 	stash += sizeof(void *) * (n_gstrings + 1);
1235 	for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1236 		struct usb_string *org_s;
1237 
1238 		gs_array[n_gs] = stash;
1239 		gs = gs_array[n_gs];
1240 		stash += sizeof(struct usb_gadget_strings);
1241 		gs->language = sp[n_gs]->language;
1242 		gs->strings = stash;
1243 		org_s = sp[n_gs]->strings;
1244 
1245 		for (n_s = 0; n_s < n_strings; n_s++) {
1246 			s = stash;
1247 			stash += sizeof(struct usb_string);
1248 			if (org_s->s)
1249 				s->s = org_s->s;
1250 			else
1251 				s->s = "";
1252 			org_s++;
1253 		}
1254 		s = stash;
1255 		s->s = NULL;
1256 		stash += sizeof(struct usb_string);
1257 
1258 	}
1259 	gs_array[n_gs] = NULL;
1260 	return uc;
1261 }
1262 
1263 /**
1264  * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1265  * @cdev: the device whose string descriptor IDs are being allocated
1266  * and attached.
1267  * @sp: an array of usb_gadget_strings to attach.
1268  * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1269  *
1270  * This function will create a deep copy of usb_gadget_strings and usb_string
1271  * and attach it to the cdev. The actual string (usb_string.s) will not be
1272  * copied but only a referenced will be made. The struct usb_gadget_strings
1273  * array may contain multiple languages and should be NULL terminated.
1274  * The ->language pointer of each struct usb_gadget_strings has to contain the
1275  * same amount of entries.
1276  * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1277  * usb_string entry of es-ES contains the translation of the first usb_string
1278  * entry of en-US. Therefore both entries become the same id assign.
1279  */
1280 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1281 		struct usb_gadget_strings **sp, unsigned n_strings)
1282 {
1283 	struct usb_gadget_string_container *uc;
1284 	struct usb_gadget_strings **n_gs;
1285 	unsigned n_gstrings = 0;
1286 	unsigned i;
1287 	int ret;
1288 
1289 	for (i = 0; sp[i]; i++)
1290 		n_gstrings++;
1291 
1292 	if (!n_gstrings)
1293 		return ERR_PTR(-EINVAL);
1294 
1295 	uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1296 	if (IS_ERR(uc))
1297 		return ERR_CAST(uc);
1298 
1299 	n_gs = get_containers_gs(uc);
1300 	ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1301 	if (ret)
1302 		goto err;
1303 
1304 	for (i = 1; i < n_gstrings; i++) {
1305 		struct usb_string *m_s;
1306 		struct usb_string *s;
1307 		unsigned n;
1308 
1309 		m_s = n_gs[0]->strings;
1310 		s = n_gs[i]->strings;
1311 		for (n = 0; n < n_strings; n++) {
1312 			s->id = m_s->id;
1313 			s++;
1314 			m_s++;
1315 		}
1316 	}
1317 	list_add_tail(&uc->list, &cdev->gstrings);
1318 	return n_gs[0]->strings;
1319 err:
1320 	kfree(uc);
1321 	return ERR_PTR(ret);
1322 }
1323 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1324 
1325 /**
1326  * usb_string_ids_n() - allocate unused string IDs in batch
1327  * @c: the device whose string descriptor IDs are being allocated
1328  * @n: number of string IDs to allocate
1329  * Context: single threaded during gadget setup
1330  *
1331  * Returns the first requested ID.  This ID and next @n-1 IDs are now
1332  * valid IDs.  At least provided that @n is non-zero because if it
1333  * is, returns last requested ID which is now very useful information.
1334  *
1335  * @usb_string_ids_n() is called from bind() callbacks to allocate
1336  * string IDs.  Drivers for functions, configurations, or gadgets will
1337  * then store that ID in the appropriate descriptors and string table.
1338  *
1339  * All string identifier should be allocated using this,
1340  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1341  * example different functions don't wrongly assign different meanings
1342  * to the same identifier.
1343  */
1344 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1345 {
1346 	unsigned next = c->next_string_id;
1347 	if (unlikely(n > 254 || (unsigned)next + n > 254))
1348 		return -ENODEV;
1349 	c->next_string_id += n;
1350 	return next + 1;
1351 }
1352 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1353 
1354 /*-------------------------------------------------------------------------*/
1355 
1356 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1357 {
1358 	struct usb_composite_dev *cdev;
1359 
1360 	if (req->status || req->actual != req->length)
1361 		DBG((struct usb_composite_dev *) ep->driver_data,
1362 				"setup complete --> %d, %d/%d\n",
1363 				req->status, req->actual, req->length);
1364 
1365 	/*
1366 	 * REVIST The same ep0 requests are shared with function drivers
1367 	 * so they don't have to maintain the same ->complete() stubs.
1368 	 *
1369 	 * Because of that, we need to check for the validity of ->context
1370 	 * here, even though we know we've set it to something useful.
1371 	 */
1372 	if (!req->context)
1373 		return;
1374 
1375 	cdev = req->context;
1376 
1377 	if (cdev->req == req)
1378 		cdev->setup_pending = false;
1379 	else if (cdev->os_desc_req == req)
1380 		cdev->os_desc_pending = false;
1381 	else
1382 		WARN(1, "unknown request %p\n", req);
1383 }
1384 
1385 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1386 		struct usb_request *req, gfp_t gfp_flags)
1387 {
1388 	int ret;
1389 
1390 	ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1391 	if (ret == 0) {
1392 		if (cdev->req == req)
1393 			cdev->setup_pending = true;
1394 		else if (cdev->os_desc_req == req)
1395 			cdev->os_desc_pending = true;
1396 		else
1397 			WARN(1, "unknown request %p\n", req);
1398 	}
1399 
1400 	return ret;
1401 }
1402 
1403 static int count_ext_compat(struct usb_configuration *c)
1404 {
1405 	int i, res;
1406 
1407 	res = 0;
1408 	for (i = 0; i < c->next_interface_id; ++i) {
1409 		struct usb_function *f;
1410 		int j;
1411 
1412 		f = c->interface[i];
1413 		for (j = 0; j < f->os_desc_n; ++j) {
1414 			struct usb_os_desc *d;
1415 
1416 			if (i != f->os_desc_table[j].if_id)
1417 				continue;
1418 			d = f->os_desc_table[j].os_desc;
1419 			if (d && d->ext_compat_id)
1420 				++res;
1421 		}
1422 	}
1423 	BUG_ON(res > 255);
1424 	return res;
1425 }
1426 
1427 static void fill_ext_compat(struct usb_configuration *c, u8 *buf)
1428 {
1429 	int i, count;
1430 
1431 	count = 16;
1432 	for (i = 0; i < c->next_interface_id; ++i) {
1433 		struct usb_function *f;
1434 		int j;
1435 
1436 		f = c->interface[i];
1437 		for (j = 0; j < f->os_desc_n; ++j) {
1438 			struct usb_os_desc *d;
1439 
1440 			if (i != f->os_desc_table[j].if_id)
1441 				continue;
1442 			d = f->os_desc_table[j].os_desc;
1443 			if (d && d->ext_compat_id) {
1444 				*buf++ = i;
1445 				*buf++ = 0x01;
1446 				memcpy(buf, d->ext_compat_id, 16);
1447 				buf += 22;
1448 			} else {
1449 				++buf;
1450 				*buf = 0x01;
1451 				buf += 23;
1452 			}
1453 			count += 24;
1454 			if (count >= 4096)
1455 				return;
1456 		}
1457 	}
1458 }
1459 
1460 static int count_ext_prop(struct usb_configuration *c, int interface)
1461 {
1462 	struct usb_function *f;
1463 	int j;
1464 
1465 	f = c->interface[interface];
1466 	for (j = 0; j < f->os_desc_n; ++j) {
1467 		struct usb_os_desc *d;
1468 
1469 		if (interface != f->os_desc_table[j].if_id)
1470 			continue;
1471 		d = f->os_desc_table[j].os_desc;
1472 		if (d && d->ext_compat_id)
1473 			return d->ext_prop_count;
1474 	}
1475 	return 0;
1476 }
1477 
1478 static int len_ext_prop(struct usb_configuration *c, int interface)
1479 {
1480 	struct usb_function *f;
1481 	struct usb_os_desc *d;
1482 	int j, res;
1483 
1484 	res = 10; /* header length */
1485 	f = c->interface[interface];
1486 	for (j = 0; j < f->os_desc_n; ++j) {
1487 		if (interface != f->os_desc_table[j].if_id)
1488 			continue;
1489 		d = f->os_desc_table[j].os_desc;
1490 		if (d)
1491 			return min(res + d->ext_prop_len, 4096);
1492 	}
1493 	return res;
1494 }
1495 
1496 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1497 {
1498 	struct usb_function *f;
1499 	struct usb_os_desc *d;
1500 	struct usb_os_desc_ext_prop *ext_prop;
1501 	int j, count, n, ret;
1502 	u8 *start = buf;
1503 
1504 	f = c->interface[interface];
1505 	for (j = 0; j < f->os_desc_n; ++j) {
1506 		if (interface != f->os_desc_table[j].if_id)
1507 			continue;
1508 		d = f->os_desc_table[j].os_desc;
1509 		if (d)
1510 			list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1511 				/* 4kB minus header length */
1512 				n = buf - start;
1513 				if (n >= 4086)
1514 					return 0;
1515 
1516 				count = ext_prop->data_len +
1517 					ext_prop->name_len + 14;
1518 				if (count > 4086 - n)
1519 					return -EINVAL;
1520 				usb_ext_prop_put_size(buf, count);
1521 				usb_ext_prop_put_type(buf, ext_prop->type);
1522 				ret = usb_ext_prop_put_name(buf, ext_prop->name,
1523 							    ext_prop->name_len);
1524 				if (ret < 0)
1525 					return ret;
1526 				switch (ext_prop->type) {
1527 				case USB_EXT_PROP_UNICODE:
1528 				case USB_EXT_PROP_UNICODE_ENV:
1529 				case USB_EXT_PROP_UNICODE_LINK:
1530 					usb_ext_prop_put_unicode(buf, ret,
1531 							 ext_prop->data,
1532 							 ext_prop->data_len);
1533 					break;
1534 				case USB_EXT_PROP_BINARY:
1535 					usb_ext_prop_put_binary(buf, ret,
1536 							ext_prop->data,
1537 							ext_prop->data_len);
1538 					break;
1539 				case USB_EXT_PROP_LE32:
1540 					/* not implemented */
1541 				case USB_EXT_PROP_BE32:
1542 					/* not implemented */
1543 				default:
1544 					return -EINVAL;
1545 				}
1546 				buf += count;
1547 			}
1548 	}
1549 
1550 	return 0;
1551 }
1552 
1553 /*
1554  * The setup() callback implements all the ep0 functionality that's
1555  * not handled lower down, in hardware or the hardware driver(like
1556  * device and endpoint feature flags, and their status).  It's all
1557  * housekeeping for the gadget function we're implementing.  Most of
1558  * the work is in config and function specific setup.
1559  */
1560 int
1561 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1562 {
1563 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1564 	struct usb_request		*req = cdev->req;
1565 	int				value = -EOPNOTSUPP;
1566 	int				status = 0;
1567 	u16				w_index = le16_to_cpu(ctrl->wIndex);
1568 	u8				intf = w_index & 0xFF;
1569 	u16				w_value = le16_to_cpu(ctrl->wValue);
1570 	u16				w_length = le16_to_cpu(ctrl->wLength);
1571 	struct usb_function		*f = NULL;
1572 	u8				endp;
1573 
1574 	/* partial re-init of the response message; the function or the
1575 	 * gadget might need to intercept e.g. a control-OUT completion
1576 	 * when we delegate to it.
1577 	 */
1578 	req->zero = 0;
1579 	req->context = cdev;
1580 	req->complete = composite_setup_complete;
1581 	req->length = 0;
1582 	gadget->ep0->driver_data = cdev;
1583 
1584 	/*
1585 	 * Don't let non-standard requests match any of the cases below
1586 	 * by accident.
1587 	 */
1588 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1589 		goto unknown;
1590 
1591 	switch (ctrl->bRequest) {
1592 
1593 	/* we handle all standard USB descriptors */
1594 	case USB_REQ_GET_DESCRIPTOR:
1595 		if (ctrl->bRequestType != USB_DIR_IN)
1596 			goto unknown;
1597 		switch (w_value >> 8) {
1598 
1599 		case USB_DT_DEVICE:
1600 			cdev->desc.bNumConfigurations =
1601 				count_configs(cdev, USB_DT_DEVICE);
1602 			cdev->desc.bMaxPacketSize0 =
1603 				cdev->gadget->ep0->maxpacket;
1604 			if (gadget_is_superspeed(gadget)) {
1605 				if (gadget->speed >= USB_SPEED_SUPER) {
1606 					cdev->desc.bcdUSB = cpu_to_le16(0x0310);
1607 					cdev->desc.bMaxPacketSize0 = 9;
1608 				} else {
1609 					cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1610 				}
1611 			} else {
1612 				if (gadget->lpm_capable)
1613 					cdev->desc.bcdUSB = cpu_to_le16(0x0201);
1614 				else
1615 					cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1616 			}
1617 
1618 			value = min(w_length, (u16) sizeof cdev->desc);
1619 			memcpy(req->buf, &cdev->desc, value);
1620 			break;
1621 		case USB_DT_DEVICE_QUALIFIER:
1622 			if (!gadget_is_dualspeed(gadget) ||
1623 			    gadget->speed >= USB_SPEED_SUPER)
1624 				break;
1625 			device_qual(cdev);
1626 			value = min_t(int, w_length,
1627 				sizeof(struct usb_qualifier_descriptor));
1628 			break;
1629 		case USB_DT_OTHER_SPEED_CONFIG:
1630 			if (!gadget_is_dualspeed(gadget) ||
1631 			    gadget->speed >= USB_SPEED_SUPER)
1632 				break;
1633 			/* FALLTHROUGH */
1634 		case USB_DT_CONFIG:
1635 			value = config_desc(cdev, w_value);
1636 			if (value >= 0)
1637 				value = min(w_length, (u16) value);
1638 			break;
1639 		case USB_DT_STRING:
1640 			value = get_string(cdev, req->buf,
1641 					w_index, w_value & 0xff);
1642 			if (value >= 0)
1643 				value = min(w_length, (u16) value);
1644 			break;
1645 		case USB_DT_BOS:
1646 			if (gadget_is_superspeed(gadget) ||
1647 			    gadget->lpm_capable) {
1648 				value = bos_desc(cdev);
1649 				value = min(w_length, (u16) value);
1650 			}
1651 			break;
1652 		case USB_DT_OTG:
1653 			if (gadget_is_otg(gadget)) {
1654 				struct usb_configuration *config;
1655 				int otg_desc_len = 0;
1656 
1657 				if (cdev->config)
1658 					config = cdev->config;
1659 				else
1660 					config = list_first_entry(
1661 							&cdev->configs,
1662 						struct usb_configuration, list);
1663 				if (!config)
1664 					goto done;
1665 
1666 				if (gadget->otg_caps &&
1667 					(gadget->otg_caps->otg_rev >= 0x0200))
1668 					otg_desc_len += sizeof(
1669 						struct usb_otg20_descriptor);
1670 				else
1671 					otg_desc_len += sizeof(
1672 						struct usb_otg_descriptor);
1673 
1674 				value = min_t(int, w_length, otg_desc_len);
1675 				memcpy(req->buf, config->descriptors[0], value);
1676 			}
1677 			break;
1678 		}
1679 		break;
1680 
1681 	/* any number of configs can work */
1682 	case USB_REQ_SET_CONFIGURATION:
1683 		if (ctrl->bRequestType != 0)
1684 			goto unknown;
1685 		if (gadget_is_otg(gadget)) {
1686 			if (gadget->a_hnp_support)
1687 				DBG(cdev, "HNP available\n");
1688 			else if (gadget->a_alt_hnp_support)
1689 				DBG(cdev, "HNP on another port\n");
1690 			else
1691 				VDBG(cdev, "HNP inactive\n");
1692 		}
1693 		spin_lock(&cdev->lock);
1694 		value = set_config(cdev, ctrl, w_value);
1695 		spin_unlock(&cdev->lock);
1696 		break;
1697 	case USB_REQ_GET_CONFIGURATION:
1698 		if (ctrl->bRequestType != USB_DIR_IN)
1699 			goto unknown;
1700 		if (cdev->config)
1701 			*(u8 *)req->buf = cdev->config->bConfigurationValue;
1702 		else
1703 			*(u8 *)req->buf = 0;
1704 		value = min(w_length, (u16) 1);
1705 		break;
1706 
1707 	/* function drivers must handle get/set altsetting */
1708 	case USB_REQ_SET_INTERFACE:
1709 		if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1710 			goto unknown;
1711 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1712 			break;
1713 		f = cdev->config->interface[intf];
1714 		if (!f)
1715 			break;
1716 
1717 		/*
1718 		 * If there's no get_alt() method, we know only altsetting zero
1719 		 * works. There is no need to check if set_alt() is not NULL
1720 		 * as we check this in usb_add_function().
1721 		 */
1722 		if (w_value && !f->get_alt)
1723 			break;
1724 		value = f->set_alt(f, w_index, w_value);
1725 		if (value == USB_GADGET_DELAYED_STATUS) {
1726 			DBG(cdev,
1727 			 "%s: interface %d (%s) requested delayed status\n",
1728 					__func__, intf, f->name);
1729 			cdev->delayed_status++;
1730 			DBG(cdev, "delayed_status count %d\n",
1731 					cdev->delayed_status);
1732 		}
1733 		break;
1734 	case USB_REQ_GET_INTERFACE:
1735 		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1736 			goto unknown;
1737 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1738 			break;
1739 		f = cdev->config->interface[intf];
1740 		if (!f)
1741 			break;
1742 		/* lots of interfaces only need altsetting zero... */
1743 		value = f->get_alt ? f->get_alt(f, w_index) : 0;
1744 		if (value < 0)
1745 			break;
1746 		*((u8 *)req->buf) = value;
1747 		value = min(w_length, (u16) 1);
1748 		break;
1749 	case USB_REQ_GET_STATUS:
1750 		if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1751 						(w_index == OTG_STS_SELECTOR)) {
1752 			if (ctrl->bRequestType != (USB_DIR_IN |
1753 							USB_RECIP_DEVICE))
1754 				goto unknown;
1755 			*((u8 *)req->buf) = gadget->host_request_flag;
1756 			value = 1;
1757 			break;
1758 		}
1759 
1760 		/*
1761 		 * USB 3.0 additions:
1762 		 * Function driver should handle get_status request. If such cb
1763 		 * wasn't supplied we respond with default value = 0
1764 		 * Note: function driver should supply such cb only for the
1765 		 * first interface of the function
1766 		 */
1767 		if (!gadget_is_superspeed(gadget))
1768 			goto unknown;
1769 		if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
1770 			goto unknown;
1771 		value = 2;	/* This is the length of the get_status reply */
1772 		put_unaligned_le16(0, req->buf);
1773 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1774 			break;
1775 		f = cdev->config->interface[intf];
1776 		if (!f)
1777 			break;
1778 		status = f->get_status ? f->get_status(f) : 0;
1779 		if (status < 0)
1780 			break;
1781 		put_unaligned_le16(status & 0x0000ffff, req->buf);
1782 		break;
1783 	/*
1784 	 * Function drivers should handle SetFeature/ClearFeature
1785 	 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
1786 	 * only for the first interface of the function
1787 	 */
1788 	case USB_REQ_CLEAR_FEATURE:
1789 	case USB_REQ_SET_FEATURE:
1790 		if (!gadget_is_superspeed(gadget))
1791 			goto unknown;
1792 		if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
1793 			goto unknown;
1794 		switch (w_value) {
1795 		case USB_INTRF_FUNC_SUSPEND:
1796 			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1797 				break;
1798 			f = cdev->config->interface[intf];
1799 			if (!f)
1800 				break;
1801 			value = 0;
1802 			if (f->func_suspend)
1803 				value = f->func_suspend(f, w_index >> 8);
1804 			if (value < 0) {
1805 				ERROR(cdev,
1806 				      "func_suspend() returned error %d\n",
1807 				      value);
1808 				value = 0;
1809 			}
1810 			break;
1811 		}
1812 		break;
1813 	default:
1814 unknown:
1815 		/*
1816 		 * OS descriptors handling
1817 		 */
1818 		if (cdev->use_os_string && cdev->os_desc_config &&
1819 		    (ctrl->bRequestType & USB_TYPE_VENDOR) &&
1820 		    ctrl->bRequest == cdev->b_vendor_code) {
1821 			struct usb_request		*req;
1822 			struct usb_configuration	*os_desc_cfg;
1823 			u8				*buf;
1824 			int				interface;
1825 			int				count = 0;
1826 
1827 			req = cdev->os_desc_req;
1828 			req->context = cdev;
1829 			req->complete = composite_setup_complete;
1830 			buf = req->buf;
1831 			os_desc_cfg = cdev->os_desc_config;
1832 			memset(buf, 0, w_length);
1833 			buf[5] = 0x01;
1834 			switch (ctrl->bRequestType & USB_RECIP_MASK) {
1835 			case USB_RECIP_DEVICE:
1836 				if (w_index != 0x4 || (w_value >> 8))
1837 					break;
1838 				buf[6] = w_index;
1839 				if (w_length == 0x10) {
1840 					/* Number of ext compat interfaces */
1841 					count = count_ext_compat(os_desc_cfg);
1842 					buf[8] = count;
1843 					count *= 24; /* 24 B/ext compat desc */
1844 					count += 16; /* header */
1845 					put_unaligned_le32(count, buf);
1846 					value = w_length;
1847 				} else {
1848 					/* "extended compatibility ID"s */
1849 					count = count_ext_compat(os_desc_cfg);
1850 					buf[8] = count;
1851 					count *= 24; /* 24 B/ext compat desc */
1852 					count += 16; /* header */
1853 					put_unaligned_le32(count, buf);
1854 					buf += 16;
1855 					fill_ext_compat(os_desc_cfg, buf);
1856 					value = w_length;
1857 				}
1858 				break;
1859 			case USB_RECIP_INTERFACE:
1860 				if (w_index != 0x5 || (w_value >> 8))
1861 					break;
1862 				interface = w_value & 0xFF;
1863 				buf[6] = w_index;
1864 				if (w_length == 0x0A) {
1865 					count = count_ext_prop(os_desc_cfg,
1866 						interface);
1867 					put_unaligned_le16(count, buf + 8);
1868 					count = len_ext_prop(os_desc_cfg,
1869 						interface);
1870 					put_unaligned_le32(count, buf);
1871 
1872 					value = w_length;
1873 				} else {
1874 					count = count_ext_prop(os_desc_cfg,
1875 						interface);
1876 					put_unaligned_le16(count, buf + 8);
1877 					count = len_ext_prop(os_desc_cfg,
1878 						interface);
1879 					put_unaligned_le32(count, buf);
1880 					buf += 10;
1881 					value = fill_ext_prop(os_desc_cfg,
1882 							      interface, buf);
1883 					if (value < 0)
1884 						return value;
1885 
1886 					value = w_length;
1887 				}
1888 				break;
1889 			}
1890 
1891 			if (value >= 0) {
1892 				req->length = value;
1893 				req->context = cdev;
1894 				req->zero = value < w_length;
1895 				value = composite_ep0_queue(cdev, req,
1896 							    GFP_ATOMIC);
1897 				if (value < 0) {
1898 					DBG(cdev, "ep_queue --> %d\n", value);
1899 					req->status = 0;
1900 					composite_setup_complete(gadget->ep0,
1901 								 req);
1902 				}
1903 			}
1904 			return value;
1905 		}
1906 
1907 		VDBG(cdev,
1908 			"non-core control req%02x.%02x v%04x i%04x l%d\n",
1909 			ctrl->bRequestType, ctrl->bRequest,
1910 			w_value, w_index, w_length);
1911 
1912 		/* functions always handle their interfaces and endpoints...
1913 		 * punt other recipients (other, WUSB, ...) to the current
1914 		 * configuration code.
1915 		 */
1916 		if (cdev->config) {
1917 			list_for_each_entry(f, &cdev->config->functions, list)
1918 				if (f->req_match &&
1919 				    f->req_match(f, ctrl, false))
1920 					goto try_fun_setup;
1921 		} else {
1922 			struct usb_configuration *c;
1923 			list_for_each_entry(c, &cdev->configs, list)
1924 				list_for_each_entry(f, &c->functions, list)
1925 					if (f->req_match &&
1926 					    f->req_match(f, ctrl, true))
1927 						goto try_fun_setup;
1928 		}
1929 		f = NULL;
1930 
1931 		switch (ctrl->bRequestType & USB_RECIP_MASK) {
1932 		case USB_RECIP_INTERFACE:
1933 			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1934 				break;
1935 			f = cdev->config->interface[intf];
1936 			break;
1937 
1938 		case USB_RECIP_ENDPOINT:
1939 			if (!cdev->config)
1940 				break;
1941 			endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
1942 			list_for_each_entry(f, &cdev->config->functions, list) {
1943 				if (test_bit(endp, f->endpoints))
1944 					break;
1945 			}
1946 			if (&f->list == &cdev->config->functions)
1947 				f = NULL;
1948 			break;
1949 		}
1950 try_fun_setup:
1951 		if (f && f->setup)
1952 			value = f->setup(f, ctrl);
1953 		else {
1954 			struct usb_configuration	*c;
1955 
1956 			c = cdev->config;
1957 			if (!c)
1958 				goto done;
1959 
1960 			/* try current config's setup */
1961 			if (c->setup) {
1962 				value = c->setup(c, ctrl);
1963 				goto done;
1964 			}
1965 
1966 			/* try the only function in the current config */
1967 			if (!list_is_singular(&c->functions))
1968 				goto done;
1969 			f = list_first_entry(&c->functions, struct usb_function,
1970 					     list);
1971 			if (f->setup)
1972 				value = f->setup(f, ctrl);
1973 		}
1974 
1975 		goto done;
1976 	}
1977 
1978 	/* respond with data transfer before status phase? */
1979 	if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
1980 		req->length = value;
1981 		req->context = cdev;
1982 		req->zero = value < w_length;
1983 		value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
1984 		if (value < 0) {
1985 			DBG(cdev, "ep_queue --> %d\n", value);
1986 			req->status = 0;
1987 			composite_setup_complete(gadget->ep0, req);
1988 		}
1989 	} else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
1990 		WARN(cdev,
1991 			"%s: Delayed status not supported for w_length != 0",
1992 			__func__);
1993 	}
1994 
1995 done:
1996 	/* device either stalls (value < 0) or reports success */
1997 	return value;
1998 }
1999 
2000 void composite_disconnect(struct usb_gadget *gadget)
2001 {
2002 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2003 	unsigned long			flags;
2004 
2005 	/* REVISIT:  should we have config and device level
2006 	 * disconnect callbacks?
2007 	 */
2008 	spin_lock_irqsave(&cdev->lock, flags);
2009 	if (cdev->config)
2010 		reset_config(cdev);
2011 	if (cdev->driver->disconnect)
2012 		cdev->driver->disconnect(cdev);
2013 	spin_unlock_irqrestore(&cdev->lock, flags);
2014 }
2015 
2016 /*-------------------------------------------------------------------------*/
2017 
2018 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2019 			      char *buf)
2020 {
2021 	struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2022 	struct usb_composite_dev *cdev = get_gadget_data(gadget);
2023 
2024 	return sprintf(buf, "%d\n", cdev->suspended);
2025 }
2026 static DEVICE_ATTR_RO(suspended);
2027 
2028 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2029 {
2030 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2031 	struct usb_gadget_strings	*gstr = cdev->driver->strings[0];
2032 	struct usb_string		*dev_str = gstr->strings;
2033 
2034 	/* composite_disconnect() must already have been called
2035 	 * by the underlying peripheral controller driver!
2036 	 * so there's no i/o concurrency that could affect the
2037 	 * state protected by cdev->lock.
2038 	 */
2039 	WARN_ON(cdev->config);
2040 
2041 	while (!list_empty(&cdev->configs)) {
2042 		struct usb_configuration	*c;
2043 		c = list_first_entry(&cdev->configs,
2044 				struct usb_configuration, list);
2045 		remove_config(cdev, c);
2046 	}
2047 	if (cdev->driver->unbind && unbind_driver)
2048 		cdev->driver->unbind(cdev);
2049 
2050 	composite_dev_cleanup(cdev);
2051 
2052 	if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2053 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2054 
2055 	kfree(cdev->def_manufacturer);
2056 	kfree(cdev);
2057 	set_gadget_data(gadget, NULL);
2058 }
2059 
2060 static void composite_unbind(struct usb_gadget *gadget)
2061 {
2062 	__composite_unbind(gadget, true);
2063 }
2064 
2065 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2066 		const struct usb_device_descriptor *old)
2067 {
2068 	__le16 idVendor;
2069 	__le16 idProduct;
2070 	__le16 bcdDevice;
2071 	u8 iSerialNumber;
2072 	u8 iManufacturer;
2073 	u8 iProduct;
2074 
2075 	/*
2076 	 * these variables may have been set in
2077 	 * usb_composite_overwrite_options()
2078 	 */
2079 	idVendor = new->idVendor;
2080 	idProduct = new->idProduct;
2081 	bcdDevice = new->bcdDevice;
2082 	iSerialNumber = new->iSerialNumber;
2083 	iManufacturer = new->iManufacturer;
2084 	iProduct = new->iProduct;
2085 
2086 	*new = *old;
2087 	if (idVendor)
2088 		new->idVendor = idVendor;
2089 	if (idProduct)
2090 		new->idProduct = idProduct;
2091 	if (bcdDevice)
2092 		new->bcdDevice = bcdDevice;
2093 	else
2094 		new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2095 	if (iSerialNumber)
2096 		new->iSerialNumber = iSerialNumber;
2097 	if (iManufacturer)
2098 		new->iManufacturer = iManufacturer;
2099 	if (iProduct)
2100 		new->iProduct = iProduct;
2101 }
2102 
2103 int composite_dev_prepare(struct usb_composite_driver *composite,
2104 		struct usb_composite_dev *cdev)
2105 {
2106 	struct usb_gadget *gadget = cdev->gadget;
2107 	int ret = -ENOMEM;
2108 
2109 	/* preallocate control response and buffer */
2110 	cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2111 	if (!cdev->req)
2112 		return -ENOMEM;
2113 
2114 	cdev->req->buf = kmalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2115 	if (!cdev->req->buf)
2116 		goto fail;
2117 
2118 	ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2119 	if (ret)
2120 		goto fail_dev;
2121 
2122 	cdev->req->complete = composite_setup_complete;
2123 	cdev->req->context = cdev;
2124 	gadget->ep0->driver_data = cdev;
2125 
2126 	cdev->driver = composite;
2127 
2128 	/*
2129 	 * As per USB compliance update, a device that is actively drawing
2130 	 * more than 100mA from USB must report itself as bus-powered in
2131 	 * the GetStatus(DEVICE) call.
2132 	 */
2133 	if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2134 		usb_gadget_set_selfpowered(gadget);
2135 
2136 	/* interface and string IDs start at zero via kzalloc.
2137 	 * we force endpoints to start unassigned; few controller
2138 	 * drivers will zero ep->driver_data.
2139 	 */
2140 	usb_ep_autoconfig_reset(gadget);
2141 	return 0;
2142 fail_dev:
2143 	kfree(cdev->req->buf);
2144 fail:
2145 	usb_ep_free_request(gadget->ep0, cdev->req);
2146 	cdev->req = NULL;
2147 	return ret;
2148 }
2149 
2150 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2151 				  struct usb_ep *ep0)
2152 {
2153 	int ret = 0;
2154 
2155 	cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2156 	if (!cdev->os_desc_req) {
2157 		ret = -ENOMEM;
2158 		goto end;
2159 	}
2160 
2161 	/* OS feature descriptor length <= 4kB */
2162 	cdev->os_desc_req->buf = kmalloc(4096, GFP_KERNEL);
2163 	if (!cdev->os_desc_req->buf) {
2164 		ret = -ENOMEM;
2165 		usb_ep_free_request(ep0, cdev->os_desc_req);
2166 		goto end;
2167 	}
2168 	cdev->os_desc_req->context = cdev;
2169 	cdev->os_desc_req->complete = composite_setup_complete;
2170 end:
2171 	return ret;
2172 }
2173 
2174 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2175 {
2176 	struct usb_gadget_string_container *uc, *tmp;
2177 
2178 	list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2179 		list_del(&uc->list);
2180 		kfree(uc);
2181 	}
2182 	if (cdev->os_desc_req) {
2183 		if (cdev->os_desc_pending)
2184 			usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2185 
2186 		kfree(cdev->os_desc_req->buf);
2187 		usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2188 	}
2189 	if (cdev->req) {
2190 		if (cdev->setup_pending)
2191 			usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2192 
2193 		kfree(cdev->req->buf);
2194 		usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2195 	}
2196 	cdev->next_string_id = 0;
2197 	device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2198 }
2199 
2200 static int composite_bind(struct usb_gadget *gadget,
2201 		struct usb_gadget_driver *gdriver)
2202 {
2203 	struct usb_composite_dev	*cdev;
2204 	struct usb_composite_driver	*composite = to_cdriver(gdriver);
2205 	int				status = -ENOMEM;
2206 
2207 	cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2208 	if (!cdev)
2209 		return status;
2210 
2211 	spin_lock_init(&cdev->lock);
2212 	cdev->gadget = gadget;
2213 	set_gadget_data(gadget, cdev);
2214 	INIT_LIST_HEAD(&cdev->configs);
2215 	INIT_LIST_HEAD(&cdev->gstrings);
2216 
2217 	status = composite_dev_prepare(composite, cdev);
2218 	if (status)
2219 		goto fail;
2220 
2221 	/* composite gadget needs to assign strings for whole device (like
2222 	 * serial number), register function drivers, potentially update
2223 	 * power state and consumption, etc
2224 	 */
2225 	status = composite->bind(cdev);
2226 	if (status < 0)
2227 		goto fail;
2228 
2229 	if (cdev->use_os_string) {
2230 		status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2231 		if (status)
2232 			goto fail;
2233 	}
2234 
2235 	update_unchanged_dev_desc(&cdev->desc, composite->dev);
2236 
2237 	/* has userspace failed to provide a serial number? */
2238 	if (composite->needs_serial && !cdev->desc.iSerialNumber)
2239 		WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2240 
2241 	INFO(cdev, "%s ready\n", composite->name);
2242 	return 0;
2243 
2244 fail:
2245 	__composite_unbind(gadget, false);
2246 	return status;
2247 }
2248 
2249 /*-------------------------------------------------------------------------*/
2250 
2251 void composite_suspend(struct usb_gadget *gadget)
2252 {
2253 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2254 	struct usb_function		*f;
2255 
2256 	/* REVISIT:  should we have config level
2257 	 * suspend/resume callbacks?
2258 	 */
2259 	DBG(cdev, "suspend\n");
2260 	if (cdev->config) {
2261 		list_for_each_entry(f, &cdev->config->functions, list) {
2262 			if (f->suspend)
2263 				f->suspend(f);
2264 		}
2265 	}
2266 	if (cdev->driver->suspend)
2267 		cdev->driver->suspend(cdev);
2268 
2269 	cdev->suspended = 1;
2270 
2271 	usb_gadget_vbus_draw(gadget, 2);
2272 }
2273 
2274 void composite_resume(struct usb_gadget *gadget)
2275 {
2276 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2277 	struct usb_function		*f;
2278 	u16				maxpower;
2279 
2280 	/* REVISIT:  should we have config level
2281 	 * suspend/resume callbacks?
2282 	 */
2283 	DBG(cdev, "resume\n");
2284 	if (cdev->driver->resume)
2285 		cdev->driver->resume(cdev);
2286 	if (cdev->config) {
2287 		list_for_each_entry(f, &cdev->config->functions, list) {
2288 			if (f->resume)
2289 				f->resume(f);
2290 		}
2291 
2292 		maxpower = cdev->config->MaxPower;
2293 
2294 		usb_gadget_vbus_draw(gadget, maxpower ?
2295 			maxpower : CONFIG_USB_GADGET_VBUS_DRAW);
2296 	}
2297 
2298 	cdev->suspended = 0;
2299 }
2300 
2301 /*-------------------------------------------------------------------------*/
2302 
2303 static const struct usb_gadget_driver composite_driver_template = {
2304 	.bind		= composite_bind,
2305 	.unbind		= composite_unbind,
2306 
2307 	.setup		= composite_setup,
2308 	.reset		= composite_disconnect,
2309 	.disconnect	= composite_disconnect,
2310 
2311 	.suspend	= composite_suspend,
2312 	.resume		= composite_resume,
2313 
2314 	.driver	= {
2315 		.owner		= THIS_MODULE,
2316 	},
2317 };
2318 
2319 /**
2320  * usb_composite_probe() - register a composite driver
2321  * @driver: the driver to register
2322  *
2323  * Context: single threaded during gadget setup
2324  *
2325  * This function is used to register drivers using the composite driver
2326  * framework.  The return value is zero, or a negative errno value.
2327  * Those values normally come from the driver's @bind method, which does
2328  * all the work of setting up the driver to match the hardware.
2329  *
2330  * On successful return, the gadget is ready to respond to requests from
2331  * the host, unless one of its components invokes usb_gadget_disconnect()
2332  * while it was binding.  That would usually be done in order to wait for
2333  * some userspace participation.
2334  */
2335 int usb_composite_probe(struct usb_composite_driver *driver)
2336 {
2337 	struct usb_gadget_driver *gadget_driver;
2338 
2339 	if (!driver || !driver->dev || !driver->bind)
2340 		return -EINVAL;
2341 
2342 	if (!driver->name)
2343 		driver->name = "composite";
2344 
2345 	driver->gadget_driver = composite_driver_template;
2346 	gadget_driver = &driver->gadget_driver;
2347 
2348 	gadget_driver->function =  (char *) driver->name;
2349 	gadget_driver->driver.name = driver->name;
2350 	gadget_driver->max_speed = driver->max_speed;
2351 
2352 	return usb_gadget_probe_driver(gadget_driver);
2353 }
2354 EXPORT_SYMBOL_GPL(usb_composite_probe);
2355 
2356 /**
2357  * usb_composite_unregister() - unregister a composite driver
2358  * @driver: the driver to unregister
2359  *
2360  * This function is used to unregister drivers using the composite
2361  * driver framework.
2362  */
2363 void usb_composite_unregister(struct usb_composite_driver *driver)
2364 {
2365 	usb_gadget_unregister_driver(&driver->gadget_driver);
2366 }
2367 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2368 
2369 /**
2370  * usb_composite_setup_continue() - Continue with the control transfer
2371  * @cdev: the composite device who's control transfer was kept waiting
2372  *
2373  * This function must be called by the USB function driver to continue
2374  * with the control transfer's data/status stage in case it had requested to
2375  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2376  * can request the composite framework to delay the setup request's data/status
2377  * stages by returning USB_GADGET_DELAYED_STATUS.
2378  */
2379 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2380 {
2381 	int			value;
2382 	struct usb_request	*req = cdev->req;
2383 	unsigned long		flags;
2384 
2385 	DBG(cdev, "%s\n", __func__);
2386 	spin_lock_irqsave(&cdev->lock, flags);
2387 
2388 	if (cdev->delayed_status == 0) {
2389 		WARN(cdev, "%s: Unexpected call\n", __func__);
2390 
2391 	} else if (--cdev->delayed_status == 0) {
2392 		DBG(cdev, "%s: Completing delayed status\n", __func__);
2393 		req->length = 0;
2394 		req->context = cdev;
2395 		value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2396 		if (value < 0) {
2397 			DBG(cdev, "ep_queue --> %d\n", value);
2398 			req->status = 0;
2399 			composite_setup_complete(cdev->gadget->ep0, req);
2400 		}
2401 	}
2402 
2403 	spin_unlock_irqrestore(&cdev->lock, flags);
2404 }
2405 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2406 
2407 static char *composite_default_mfr(struct usb_gadget *gadget)
2408 {
2409 	return kasprintf(GFP_KERNEL, "%s %s with %s", init_utsname()->sysname,
2410 			 init_utsname()->release, gadget->name);
2411 }
2412 
2413 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2414 		struct usb_composite_overwrite *covr)
2415 {
2416 	struct usb_device_descriptor	*desc = &cdev->desc;
2417 	struct usb_gadget_strings	*gstr = cdev->driver->strings[0];
2418 	struct usb_string		*dev_str = gstr->strings;
2419 
2420 	if (covr->idVendor)
2421 		desc->idVendor = cpu_to_le16(covr->idVendor);
2422 
2423 	if (covr->idProduct)
2424 		desc->idProduct = cpu_to_le16(covr->idProduct);
2425 
2426 	if (covr->bcdDevice)
2427 		desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2428 
2429 	if (covr->serial_number) {
2430 		desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2431 		dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2432 	}
2433 	if (covr->manufacturer) {
2434 		desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2435 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2436 
2437 	} else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2438 		desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2439 		cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2440 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2441 	}
2442 
2443 	if (covr->product) {
2444 		desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2445 		dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2446 	}
2447 }
2448 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2449 
2450 MODULE_LICENSE("GPL");
2451 MODULE_AUTHOR("David Brownell");
2452