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