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