xref: /linux/drivers/usb/gadget/composite.c (revision e724e7aaf9ca794670a4d4931af7a7e24e37fec3)
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 
1129 	if (status == 0)
1130 		status = usb_gadget_check_config(cdev->gadget);
1131 
1132 	if (status < 0) {
1133 		while (!list_empty(&config->functions)) {
1134 			struct usb_function		*f;
1135 
1136 			f = list_first_entry(&config->functions,
1137 					struct usb_function, list);
1138 			list_del(&f->list);
1139 			if (f->unbind) {
1140 				DBG(cdev, "unbind function '%s'/%p\n",
1141 					f->name, f);
1142 				f->unbind(config, f);
1143 				/* may free memory for "f" */
1144 			}
1145 		}
1146 		list_del(&config->list);
1147 		config->cdev = NULL;
1148 	} else {
1149 		unsigned	i;
1150 
1151 		DBG(cdev, "cfg %d/%p speeds:%s%s%s%s\n",
1152 			config->bConfigurationValue, config,
1153 			config->superspeed_plus ? " superplus" : "",
1154 			config->superspeed ? " super" : "",
1155 			config->highspeed ? " high" : "",
1156 			config->fullspeed
1157 				? (gadget_is_dualspeed(cdev->gadget)
1158 					? " full"
1159 					: " full/low")
1160 				: "");
1161 
1162 		for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
1163 			struct usb_function	*f = config->interface[i];
1164 
1165 			if (!f)
1166 				continue;
1167 			DBG(cdev, "  interface %d = %s/%p\n",
1168 				i, f->name, f);
1169 		}
1170 	}
1171 
1172 	/* set_alt(), or next bind(), sets up ep->claimed as needed */
1173 	usb_ep_autoconfig_reset(cdev->gadget);
1174 
1175 done:
1176 	if (status)
1177 		DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
1178 				config->bConfigurationValue, status);
1179 	return status;
1180 }
1181 EXPORT_SYMBOL_GPL(usb_add_config);
1182 
1183 static void remove_config(struct usb_composite_dev *cdev,
1184 			      struct usb_configuration *config)
1185 {
1186 	while (!list_empty(&config->functions)) {
1187 		struct usb_function		*f;
1188 
1189 		f = list_first_entry(&config->functions,
1190 				struct usb_function, list);
1191 
1192 		usb_remove_function(config, f);
1193 	}
1194 	list_del(&config->list);
1195 	if (config->unbind) {
1196 		DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
1197 		config->unbind(config);
1198 			/* may free memory for "c" */
1199 	}
1200 }
1201 
1202 /**
1203  * usb_remove_config() - remove a configuration from a device.
1204  * @cdev: wraps the USB gadget
1205  * @config: the configuration
1206  *
1207  * Drivers must call usb_gadget_disconnect before calling this function
1208  * to disconnect the device from the host and make sure the host will not
1209  * try to enumerate the device while we are changing the config list.
1210  */
1211 void usb_remove_config(struct usb_composite_dev *cdev,
1212 		      struct usb_configuration *config)
1213 {
1214 	unsigned long flags;
1215 
1216 	spin_lock_irqsave(&cdev->lock, flags);
1217 
1218 	if (cdev->config == config)
1219 		reset_config(cdev);
1220 
1221 	spin_unlock_irqrestore(&cdev->lock, flags);
1222 
1223 	remove_config(cdev, config);
1224 }
1225 
1226 /*-------------------------------------------------------------------------*/
1227 
1228 /* We support strings in multiple languages ... string descriptor zero
1229  * says which languages are supported.  The typical case will be that
1230  * only one language (probably English) is used, with i18n handled on
1231  * the host side.
1232  */
1233 
1234 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
1235 {
1236 	const struct usb_gadget_strings	*s;
1237 	__le16				language;
1238 	__le16				*tmp;
1239 
1240 	while (*sp) {
1241 		s = *sp;
1242 		language = cpu_to_le16(s->language);
1243 		for (tmp = buf; *tmp && tmp < &buf[USB_MAX_STRING_LEN]; tmp++) {
1244 			if (*tmp == language)
1245 				goto repeat;
1246 		}
1247 		*tmp++ = language;
1248 repeat:
1249 		sp++;
1250 	}
1251 }
1252 
1253 static int lookup_string(
1254 	struct usb_gadget_strings	**sp,
1255 	void				*buf,
1256 	u16				language,
1257 	int				id
1258 )
1259 {
1260 	struct usb_gadget_strings	*s;
1261 	int				value;
1262 
1263 	while (*sp) {
1264 		s = *sp++;
1265 		if (s->language != language)
1266 			continue;
1267 		value = usb_gadget_get_string(s, id, buf);
1268 		if (value > 0)
1269 			return value;
1270 	}
1271 	return -EINVAL;
1272 }
1273 
1274 static int get_string(struct usb_composite_dev *cdev,
1275 		void *buf, u16 language, int id)
1276 {
1277 	struct usb_composite_driver	*composite = cdev->driver;
1278 	struct usb_gadget_string_container *uc;
1279 	struct usb_configuration	*c;
1280 	struct usb_function		*f;
1281 	int				len;
1282 
1283 	/* Yes, not only is USB's i18n support probably more than most
1284 	 * folk will ever care about ... also, it's all supported here.
1285 	 * (Except for UTF8 support for Unicode's "Astral Planes".)
1286 	 */
1287 
1288 	/* 0 == report all available language codes */
1289 	if (id == 0) {
1290 		struct usb_string_descriptor	*s = buf;
1291 		struct usb_gadget_strings	**sp;
1292 
1293 		memset(s, 0, 256);
1294 		s->bDescriptorType = USB_DT_STRING;
1295 
1296 		sp = composite->strings;
1297 		if (sp)
1298 			collect_langs(sp, s->wData);
1299 
1300 		list_for_each_entry(c, &cdev->configs, list) {
1301 			sp = c->strings;
1302 			if (sp)
1303 				collect_langs(sp, s->wData);
1304 
1305 			list_for_each_entry(f, &c->functions, list) {
1306 				sp = f->strings;
1307 				if (sp)
1308 					collect_langs(sp, s->wData);
1309 			}
1310 		}
1311 		list_for_each_entry(uc, &cdev->gstrings, list) {
1312 			struct usb_gadget_strings **sp;
1313 
1314 			sp = get_containers_gs(uc);
1315 			collect_langs(sp, s->wData);
1316 		}
1317 
1318 		for (len = 0; len <= USB_MAX_STRING_LEN && s->wData[len]; len++)
1319 			continue;
1320 		if (!len)
1321 			return -EINVAL;
1322 
1323 		s->bLength = 2 * (len + 1);
1324 		return s->bLength;
1325 	}
1326 
1327 	if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1328 		struct usb_os_string *b = buf;
1329 		b->bLength = sizeof(*b);
1330 		b->bDescriptorType = USB_DT_STRING;
1331 		compiletime_assert(
1332 			sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1333 			"qwSignature size must be equal to qw_sign");
1334 		memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1335 		b->bMS_VendorCode = cdev->b_vendor_code;
1336 		b->bPad = 0;
1337 		return sizeof(*b);
1338 	}
1339 
1340 	list_for_each_entry(uc, &cdev->gstrings, list) {
1341 		struct usb_gadget_strings **sp;
1342 
1343 		sp = get_containers_gs(uc);
1344 		len = lookup_string(sp, buf, language, id);
1345 		if (len > 0)
1346 			return len;
1347 	}
1348 
1349 	/* String IDs are device-scoped, so we look up each string
1350 	 * table we're told about.  These lookups are infrequent;
1351 	 * simpler-is-better here.
1352 	 */
1353 	if (composite->strings) {
1354 		len = lookup_string(composite->strings, buf, language, id);
1355 		if (len > 0)
1356 			return len;
1357 	}
1358 	list_for_each_entry(c, &cdev->configs, list) {
1359 		if (c->strings) {
1360 			len = lookup_string(c->strings, buf, language, id);
1361 			if (len > 0)
1362 				return len;
1363 		}
1364 		list_for_each_entry(f, &c->functions, list) {
1365 			if (!f->strings)
1366 				continue;
1367 			len = lookup_string(f->strings, buf, language, id);
1368 			if (len > 0)
1369 				return len;
1370 		}
1371 	}
1372 	return -EINVAL;
1373 }
1374 
1375 /**
1376  * usb_string_id() - allocate an unused string ID
1377  * @cdev: the device whose string descriptor IDs are being allocated
1378  * Context: single threaded during gadget setup
1379  *
1380  * @usb_string_id() is called from bind() callbacks to allocate
1381  * string IDs.  Drivers for functions, configurations, or gadgets will
1382  * then store that ID in the appropriate descriptors and string table.
1383  *
1384  * All string identifier should be allocated using this,
1385  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1386  * that for example different functions don't wrongly assign different
1387  * meanings to the same identifier.
1388  */
1389 int usb_string_id(struct usb_composite_dev *cdev)
1390 {
1391 	if (cdev->next_string_id < 254) {
1392 		/* string id 0 is reserved by USB spec for list of
1393 		 * supported languages */
1394 		/* 255 reserved as well? -- mina86 */
1395 		cdev->next_string_id++;
1396 		return cdev->next_string_id;
1397 	}
1398 	return -ENODEV;
1399 }
1400 EXPORT_SYMBOL_GPL(usb_string_id);
1401 
1402 /**
1403  * usb_string_ids_tab() - allocate unused string IDs in batch
1404  * @cdev: the device whose string descriptor IDs are being allocated
1405  * @str: an array of usb_string objects to assign numbers to
1406  * Context: single threaded during gadget setup
1407  *
1408  * @usb_string_ids() is called from bind() callbacks to allocate
1409  * string IDs.  Drivers for functions, configurations, or gadgets will
1410  * then copy IDs from the string table to the appropriate descriptors
1411  * and string table for other languages.
1412  *
1413  * All string identifier should be allocated using this,
1414  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1415  * example different functions don't wrongly assign different meanings
1416  * to the same identifier.
1417  */
1418 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1419 {
1420 	int next = cdev->next_string_id;
1421 
1422 	for (; str->s; ++str) {
1423 		if (unlikely(next >= 254))
1424 			return -ENODEV;
1425 		str->id = ++next;
1426 	}
1427 
1428 	cdev->next_string_id = next;
1429 
1430 	return 0;
1431 }
1432 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1433 
1434 static struct usb_gadget_string_container *copy_gadget_strings(
1435 		struct usb_gadget_strings **sp, unsigned n_gstrings,
1436 		unsigned n_strings)
1437 {
1438 	struct usb_gadget_string_container *uc;
1439 	struct usb_gadget_strings **gs_array;
1440 	struct usb_gadget_strings *gs;
1441 	struct usb_string *s;
1442 	unsigned mem;
1443 	unsigned n_gs;
1444 	unsigned n_s;
1445 	void *stash;
1446 
1447 	mem = sizeof(*uc);
1448 	mem += sizeof(void *) * (n_gstrings + 1);
1449 	mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1450 	mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1451 	uc = kmalloc(mem, GFP_KERNEL);
1452 	if (!uc)
1453 		return ERR_PTR(-ENOMEM);
1454 	gs_array = get_containers_gs(uc);
1455 	stash = uc->stash;
1456 	stash += sizeof(void *) * (n_gstrings + 1);
1457 	for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1458 		struct usb_string *org_s;
1459 
1460 		gs_array[n_gs] = stash;
1461 		gs = gs_array[n_gs];
1462 		stash += sizeof(struct usb_gadget_strings);
1463 		gs->language = sp[n_gs]->language;
1464 		gs->strings = stash;
1465 		org_s = sp[n_gs]->strings;
1466 
1467 		for (n_s = 0; n_s < n_strings; n_s++) {
1468 			s = stash;
1469 			stash += sizeof(struct usb_string);
1470 			if (org_s->s)
1471 				s->s = org_s->s;
1472 			else
1473 				s->s = "";
1474 			org_s++;
1475 		}
1476 		s = stash;
1477 		s->s = NULL;
1478 		stash += sizeof(struct usb_string);
1479 
1480 	}
1481 	gs_array[n_gs] = NULL;
1482 	return uc;
1483 }
1484 
1485 /**
1486  * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1487  * @cdev: the device whose string descriptor IDs are being allocated
1488  * and attached.
1489  * @sp: an array of usb_gadget_strings to attach.
1490  * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1491  *
1492  * This function will create a deep copy of usb_gadget_strings and usb_string
1493  * and attach it to the cdev. The actual string (usb_string.s) will not be
1494  * copied but only a referenced will be made. The struct usb_gadget_strings
1495  * array may contain multiple languages and should be NULL terminated.
1496  * The ->language pointer of each struct usb_gadget_strings has to contain the
1497  * same amount of entries.
1498  * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1499  * usb_string entry of es-ES contains the translation of the first usb_string
1500  * entry of en-US. Therefore both entries become the same id assign.
1501  */
1502 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1503 		struct usb_gadget_strings **sp, unsigned n_strings)
1504 {
1505 	struct usb_gadget_string_container *uc;
1506 	struct usb_gadget_strings **n_gs;
1507 	unsigned n_gstrings = 0;
1508 	unsigned i;
1509 	int ret;
1510 
1511 	for (i = 0; sp[i]; i++)
1512 		n_gstrings++;
1513 
1514 	if (!n_gstrings)
1515 		return ERR_PTR(-EINVAL);
1516 
1517 	uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1518 	if (IS_ERR(uc))
1519 		return ERR_CAST(uc);
1520 
1521 	n_gs = get_containers_gs(uc);
1522 	ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1523 	if (ret)
1524 		goto err;
1525 
1526 	for (i = 1; i < n_gstrings; i++) {
1527 		struct usb_string *m_s;
1528 		struct usb_string *s;
1529 		unsigned n;
1530 
1531 		m_s = n_gs[0]->strings;
1532 		s = n_gs[i]->strings;
1533 		for (n = 0; n < n_strings; n++) {
1534 			s->id = m_s->id;
1535 			s++;
1536 			m_s++;
1537 		}
1538 	}
1539 	list_add_tail(&uc->list, &cdev->gstrings);
1540 	return n_gs[0]->strings;
1541 err:
1542 	kfree(uc);
1543 	return ERR_PTR(ret);
1544 }
1545 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1546 
1547 /**
1548  * usb_string_ids_n() - allocate unused string IDs in batch
1549  * @c: the device whose string descriptor IDs are being allocated
1550  * @n: number of string IDs to allocate
1551  * Context: single threaded during gadget setup
1552  *
1553  * Returns the first requested ID.  This ID and next @n-1 IDs are now
1554  * valid IDs.  At least provided that @n is non-zero because if it
1555  * is, returns last requested ID which is now very useful information.
1556  *
1557  * @usb_string_ids_n() is called from bind() callbacks to allocate
1558  * string IDs.  Drivers for functions, configurations, or gadgets will
1559  * then store that ID in the appropriate descriptors and string table.
1560  *
1561  * All string identifier should be allocated using this,
1562  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1563  * example different functions don't wrongly assign different meanings
1564  * to the same identifier.
1565  */
1566 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1567 {
1568 	unsigned next = c->next_string_id;
1569 	if (unlikely(n > 254 || (unsigned)next + n > 254))
1570 		return -ENODEV;
1571 	c->next_string_id += n;
1572 	return next + 1;
1573 }
1574 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1575 
1576 /*-------------------------------------------------------------------------*/
1577 
1578 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1579 {
1580 	struct usb_composite_dev *cdev;
1581 
1582 	if (req->status || req->actual != req->length)
1583 		DBG((struct usb_composite_dev *) ep->driver_data,
1584 				"setup complete --> %d, %d/%d\n",
1585 				req->status, req->actual, req->length);
1586 
1587 	/*
1588 	 * REVIST The same ep0 requests are shared with function drivers
1589 	 * so they don't have to maintain the same ->complete() stubs.
1590 	 *
1591 	 * Because of that, we need to check for the validity of ->context
1592 	 * here, even though we know we've set it to something useful.
1593 	 */
1594 	if (!req->context)
1595 		return;
1596 
1597 	cdev = req->context;
1598 
1599 	if (cdev->req == req)
1600 		cdev->setup_pending = false;
1601 	else if (cdev->os_desc_req == req)
1602 		cdev->os_desc_pending = false;
1603 	else
1604 		WARN(1, "unknown request %p\n", req);
1605 }
1606 
1607 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1608 		struct usb_request *req, gfp_t gfp_flags)
1609 {
1610 	int ret;
1611 
1612 	ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1613 	if (ret == 0) {
1614 		if (cdev->req == req)
1615 			cdev->setup_pending = true;
1616 		else if (cdev->os_desc_req == req)
1617 			cdev->os_desc_pending = true;
1618 		else
1619 			WARN(1, "unknown request %p\n", req);
1620 	}
1621 
1622 	return ret;
1623 }
1624 
1625 static int count_ext_compat(struct usb_configuration *c)
1626 {
1627 	int i, res;
1628 
1629 	res = 0;
1630 	for (i = 0; i < c->next_interface_id; ++i) {
1631 		struct usb_function *f;
1632 		int j;
1633 
1634 		f = c->interface[i];
1635 		for (j = 0; j < f->os_desc_n; ++j) {
1636 			struct usb_os_desc *d;
1637 
1638 			if (i != f->os_desc_table[j].if_id)
1639 				continue;
1640 			d = f->os_desc_table[j].os_desc;
1641 			if (d && d->ext_compat_id)
1642 				++res;
1643 		}
1644 	}
1645 	BUG_ON(res > 255);
1646 	return res;
1647 }
1648 
1649 static int fill_ext_compat(struct usb_configuration *c, u8 *buf)
1650 {
1651 	int i, count;
1652 
1653 	count = 16;
1654 	buf += 16;
1655 	for (i = 0; i < c->next_interface_id; ++i) {
1656 		struct usb_function *f;
1657 		int j;
1658 
1659 		f = c->interface[i];
1660 		for (j = 0; j < f->os_desc_n; ++j) {
1661 			struct usb_os_desc *d;
1662 
1663 			if (i != f->os_desc_table[j].if_id)
1664 				continue;
1665 			d = f->os_desc_table[j].os_desc;
1666 			if (d && d->ext_compat_id) {
1667 				*buf++ = i;
1668 				*buf++ = 0x01;
1669 				memcpy(buf, d->ext_compat_id, 16);
1670 				buf += 22;
1671 			} else {
1672 				++buf;
1673 				*buf = 0x01;
1674 				buf += 23;
1675 			}
1676 			count += 24;
1677 			if (count + 24 >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1678 				return count;
1679 		}
1680 	}
1681 
1682 	return count;
1683 }
1684 
1685 static int count_ext_prop(struct usb_configuration *c, int interface)
1686 {
1687 	struct usb_function *f;
1688 	int j;
1689 
1690 	f = c->interface[interface];
1691 	for (j = 0; j < f->os_desc_n; ++j) {
1692 		struct usb_os_desc *d;
1693 
1694 		if (interface != f->os_desc_table[j].if_id)
1695 			continue;
1696 		d = f->os_desc_table[j].os_desc;
1697 		if (d && d->ext_compat_id)
1698 			return d->ext_prop_count;
1699 	}
1700 	return 0;
1701 }
1702 
1703 static int len_ext_prop(struct usb_configuration *c, int interface)
1704 {
1705 	struct usb_function *f;
1706 	struct usb_os_desc *d;
1707 	int j, res;
1708 
1709 	res = 10; /* header length */
1710 	f = c->interface[interface];
1711 	for (j = 0; j < f->os_desc_n; ++j) {
1712 		if (interface != f->os_desc_table[j].if_id)
1713 			continue;
1714 		d = f->os_desc_table[j].os_desc;
1715 		if (d)
1716 			return min(res + d->ext_prop_len, 4096);
1717 	}
1718 	return res;
1719 }
1720 
1721 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1722 {
1723 	struct usb_function *f;
1724 	struct usb_os_desc *d;
1725 	struct usb_os_desc_ext_prop *ext_prop;
1726 	int j, count, n, ret;
1727 
1728 	f = c->interface[interface];
1729 	count = 10; /* header length */
1730 	buf += 10;
1731 	for (j = 0; j < f->os_desc_n; ++j) {
1732 		if (interface != f->os_desc_table[j].if_id)
1733 			continue;
1734 		d = f->os_desc_table[j].os_desc;
1735 		if (d)
1736 			list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1737 				n = ext_prop->data_len +
1738 					ext_prop->name_len + 14;
1739 				if (count + n >= USB_COMP_EP0_OS_DESC_BUFSIZ)
1740 					return count;
1741 				usb_ext_prop_put_size(buf, n);
1742 				usb_ext_prop_put_type(buf, ext_prop->type);
1743 				ret = usb_ext_prop_put_name(buf, ext_prop->name,
1744 							    ext_prop->name_len);
1745 				if (ret < 0)
1746 					return ret;
1747 				switch (ext_prop->type) {
1748 				case USB_EXT_PROP_UNICODE:
1749 				case USB_EXT_PROP_UNICODE_ENV:
1750 				case USB_EXT_PROP_UNICODE_LINK:
1751 					usb_ext_prop_put_unicode(buf, ret,
1752 							 ext_prop->data,
1753 							 ext_prop->data_len);
1754 					break;
1755 				case USB_EXT_PROP_BINARY:
1756 					usb_ext_prop_put_binary(buf, ret,
1757 							ext_prop->data,
1758 							ext_prop->data_len);
1759 					break;
1760 				case USB_EXT_PROP_LE32:
1761 					/* not implemented */
1762 				case USB_EXT_PROP_BE32:
1763 					/* not implemented */
1764 				default:
1765 					return -EINVAL;
1766 				}
1767 				buf += n;
1768 				count += n;
1769 			}
1770 	}
1771 
1772 	return count;
1773 }
1774 
1775 /*
1776  * The setup() callback implements all the ep0 functionality that's
1777  * not handled lower down, in hardware or the hardware driver(like
1778  * device and endpoint feature flags, and their status).  It's all
1779  * housekeeping for the gadget function we're implementing.  Most of
1780  * the work is in config and function specific setup.
1781  */
1782 int
1783 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1784 {
1785 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1786 	struct usb_request		*req = cdev->req;
1787 	int				value = -EOPNOTSUPP;
1788 	int				status = 0;
1789 	u16				w_index = le16_to_cpu(ctrl->wIndex);
1790 	u8				intf = w_index & 0xFF;
1791 	u16				w_value = le16_to_cpu(ctrl->wValue);
1792 	u16				w_length = le16_to_cpu(ctrl->wLength);
1793 	struct usb_function		*f = NULL;
1794 	struct usb_function		*iter;
1795 	u8				endp;
1796 
1797 	if (w_length > USB_COMP_EP0_BUFSIZ) {
1798 		if (ctrl->bRequestType & USB_DIR_IN) {
1799 			/* Cast away the const, we are going to overwrite on purpose. */
1800 			__le16 *temp = (__le16 *)&ctrl->wLength;
1801 
1802 			*temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
1803 			w_length = USB_COMP_EP0_BUFSIZ;
1804 		} else {
1805 			goto done;
1806 		}
1807 	}
1808 
1809 	/* partial re-init of the response message; the function or the
1810 	 * gadget might need to intercept e.g. a control-OUT completion
1811 	 * when we delegate to it.
1812 	 */
1813 	req->zero = 0;
1814 	req->context = cdev;
1815 	req->complete = composite_setup_complete;
1816 	req->length = 0;
1817 	gadget->ep0->driver_data = cdev;
1818 
1819 	/*
1820 	 * Don't let non-standard requests match any of the cases below
1821 	 * by accident.
1822 	 */
1823 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1824 		goto unknown;
1825 
1826 	switch (ctrl->bRequest) {
1827 
1828 	/* we handle all standard USB descriptors */
1829 	case USB_REQ_GET_DESCRIPTOR:
1830 		if (ctrl->bRequestType != USB_DIR_IN)
1831 			goto unknown;
1832 		switch (w_value >> 8) {
1833 
1834 		case USB_DT_DEVICE:
1835 			cdev->desc.bNumConfigurations =
1836 				count_configs(cdev, USB_DT_DEVICE);
1837 			cdev->desc.bMaxPacketSize0 =
1838 				cdev->gadget->ep0->maxpacket;
1839 			if (gadget_is_superspeed(gadget)) {
1840 				if (gadget->speed >= USB_SPEED_SUPER) {
1841 					cdev->desc.bcdUSB = cpu_to_le16(0x0320);
1842 					cdev->desc.bMaxPacketSize0 = 9;
1843 				} else {
1844 					cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1845 				}
1846 			} else {
1847 				if (gadget->lpm_capable || cdev->use_webusb)
1848 					cdev->desc.bcdUSB = cpu_to_le16(0x0201);
1849 				else
1850 					cdev->desc.bcdUSB = cpu_to_le16(0x0200);
1851 			}
1852 
1853 			value = min(w_length, (u16) sizeof cdev->desc);
1854 			memcpy(req->buf, &cdev->desc, value);
1855 			break;
1856 		case USB_DT_DEVICE_QUALIFIER:
1857 			if (!gadget_is_dualspeed(gadget) ||
1858 			    gadget->speed >= USB_SPEED_SUPER)
1859 				break;
1860 			device_qual(cdev);
1861 			value = min_t(int, w_length,
1862 				sizeof(struct usb_qualifier_descriptor));
1863 			break;
1864 		case USB_DT_OTHER_SPEED_CONFIG:
1865 			if (!gadget_is_dualspeed(gadget) ||
1866 			    gadget->speed >= USB_SPEED_SUPER)
1867 				break;
1868 			fallthrough;
1869 		case USB_DT_CONFIG:
1870 			value = config_desc(cdev, w_value);
1871 			if (value >= 0)
1872 				value = min(w_length, (u16) value);
1873 			break;
1874 		case USB_DT_STRING:
1875 			value = get_string(cdev, req->buf,
1876 					w_index, w_value & 0xff);
1877 			if (value >= 0)
1878 				value = min(w_length, (u16) value);
1879 			break;
1880 		case USB_DT_BOS:
1881 			if (gadget_is_superspeed(gadget) ||
1882 			    gadget->lpm_capable || cdev->use_webusb) {
1883 				value = bos_desc(cdev);
1884 				value = min(w_length, (u16) value);
1885 			}
1886 			break;
1887 		case USB_DT_OTG:
1888 			if (gadget_is_otg(gadget)) {
1889 				struct usb_configuration *config;
1890 				int otg_desc_len = 0;
1891 
1892 				if (cdev->config)
1893 					config = cdev->config;
1894 				else
1895 					config = list_first_entry(
1896 							&cdev->configs,
1897 						struct usb_configuration, list);
1898 				if (!config)
1899 					goto done;
1900 
1901 				if (gadget->otg_caps &&
1902 					(gadget->otg_caps->otg_rev >= 0x0200))
1903 					otg_desc_len += sizeof(
1904 						struct usb_otg20_descriptor);
1905 				else
1906 					otg_desc_len += sizeof(
1907 						struct usb_otg_descriptor);
1908 
1909 				value = min_t(int, w_length, otg_desc_len);
1910 				memcpy(req->buf, config->descriptors[0], value);
1911 			}
1912 			break;
1913 		}
1914 		break;
1915 
1916 	/* any number of configs can work */
1917 	case USB_REQ_SET_CONFIGURATION:
1918 		if (ctrl->bRequestType != 0)
1919 			goto unknown;
1920 		if (gadget_is_otg(gadget)) {
1921 			if (gadget->a_hnp_support)
1922 				DBG(cdev, "HNP available\n");
1923 			else if (gadget->a_alt_hnp_support)
1924 				DBG(cdev, "HNP on another port\n");
1925 			else
1926 				VDBG(cdev, "HNP inactive\n");
1927 		}
1928 		spin_lock(&cdev->lock);
1929 		value = set_config(cdev, ctrl, w_value);
1930 		spin_unlock(&cdev->lock);
1931 		break;
1932 	case USB_REQ_GET_CONFIGURATION:
1933 		if (ctrl->bRequestType != USB_DIR_IN)
1934 			goto unknown;
1935 		if (cdev->config)
1936 			*(u8 *)req->buf = cdev->config->bConfigurationValue;
1937 		else
1938 			*(u8 *)req->buf = 0;
1939 		value = min(w_length, (u16) 1);
1940 		break;
1941 
1942 	/* function drivers must handle get/set altsetting */
1943 	case USB_REQ_SET_INTERFACE:
1944 		if (ctrl->bRequestType != USB_RECIP_INTERFACE)
1945 			goto unknown;
1946 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1947 			break;
1948 		f = cdev->config->interface[intf];
1949 		if (!f)
1950 			break;
1951 
1952 		/*
1953 		 * If there's no get_alt() method, we know only altsetting zero
1954 		 * works. There is no need to check if set_alt() is not NULL
1955 		 * as we check this in usb_add_function().
1956 		 */
1957 		if (w_value && !f->get_alt)
1958 			break;
1959 
1960 		spin_lock(&cdev->lock);
1961 		value = f->set_alt(f, w_index, w_value);
1962 		if (value == USB_GADGET_DELAYED_STATUS) {
1963 			DBG(cdev,
1964 			 "%s: interface %d (%s) requested delayed status\n",
1965 					__func__, intf, f->name);
1966 			cdev->delayed_status++;
1967 			DBG(cdev, "delayed_status count %d\n",
1968 					cdev->delayed_status);
1969 		}
1970 		spin_unlock(&cdev->lock);
1971 		break;
1972 	case USB_REQ_GET_INTERFACE:
1973 		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
1974 			goto unknown;
1975 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
1976 			break;
1977 		f = cdev->config->interface[intf];
1978 		if (!f)
1979 			break;
1980 		/* lots of interfaces only need altsetting zero... */
1981 		value = f->get_alt ? f->get_alt(f, w_index) : 0;
1982 		if (value < 0)
1983 			break;
1984 		*((u8 *)req->buf) = value;
1985 		value = min(w_length, (u16) 1);
1986 		break;
1987 	case USB_REQ_GET_STATUS:
1988 		if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
1989 						(w_index == OTG_STS_SELECTOR)) {
1990 			if (ctrl->bRequestType != (USB_DIR_IN |
1991 							USB_RECIP_DEVICE))
1992 				goto unknown;
1993 			*((u8 *)req->buf) = gadget->host_request_flag;
1994 			value = 1;
1995 			break;
1996 		}
1997 
1998 		/*
1999 		 * USB 3.0 additions:
2000 		 * Function driver should handle get_status request. If such cb
2001 		 * wasn't supplied we respond with default value = 0
2002 		 * Note: function driver should supply such cb only for the
2003 		 * first interface of the function
2004 		 */
2005 		if (!gadget_is_superspeed(gadget))
2006 			goto unknown;
2007 		if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
2008 			goto unknown;
2009 		value = 2;	/* This is the length of the get_status reply */
2010 		put_unaligned_le16(0, req->buf);
2011 		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2012 			break;
2013 		f = cdev->config->interface[intf];
2014 		if (!f)
2015 			break;
2016 
2017 		if (f->get_status) {
2018 			status = f->get_status(f);
2019 			if (status < 0)
2020 				break;
2021 		} else {
2022 			/* Set D0 and D1 bits based on func wakeup capability */
2023 			if (f->config->bmAttributes & USB_CONFIG_ATT_WAKEUP) {
2024 				status |= USB_INTRF_STAT_FUNC_RW_CAP;
2025 				if (f->func_wakeup_armed)
2026 					status |= USB_INTRF_STAT_FUNC_RW;
2027 			}
2028 		}
2029 
2030 		put_unaligned_le16(status & 0x0000ffff, req->buf);
2031 		break;
2032 	/*
2033 	 * Function drivers should handle SetFeature/ClearFeature
2034 	 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
2035 	 * only for the first interface of the function
2036 	 */
2037 	case USB_REQ_CLEAR_FEATURE:
2038 	case USB_REQ_SET_FEATURE:
2039 		if (!gadget_is_superspeed(gadget))
2040 			goto unknown;
2041 		if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
2042 			goto unknown;
2043 		switch (w_value) {
2044 		case USB_INTRF_FUNC_SUSPEND:
2045 			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2046 				break;
2047 			f = cdev->config->interface[intf];
2048 			if (!f)
2049 				break;
2050 			value = 0;
2051 			if (f->func_suspend) {
2052 				value = f->func_suspend(f, w_index >> 8);
2053 			/* SetFeature(FUNCTION_SUSPEND) */
2054 			} else if (ctrl->bRequest == USB_REQ_SET_FEATURE) {
2055 				if (!(f->config->bmAttributes &
2056 				      USB_CONFIG_ATT_WAKEUP) &&
2057 				     (w_index & USB_INTRF_FUNC_SUSPEND_RW))
2058 					break;
2059 
2060 				f->func_wakeup_armed = !!(w_index &
2061 							  USB_INTRF_FUNC_SUSPEND_RW);
2062 
2063 				if (w_index & USB_INTRF_FUNC_SUSPEND_LP) {
2064 					if (f->suspend && !f->func_suspended) {
2065 						f->suspend(f);
2066 						f->func_suspended = true;
2067 					}
2068 				/*
2069 				 * Handle cases where host sends function resume
2070 				 * through SetFeature(FUNCTION_SUSPEND) but low power
2071 				 * bit reset
2072 				 */
2073 				} else {
2074 					if (f->resume && f->func_suspended) {
2075 						f->resume(f);
2076 						f->func_suspended = false;
2077 					}
2078 				}
2079 			/* ClearFeature(FUNCTION_SUSPEND) */
2080 			} else if (ctrl->bRequest == USB_REQ_CLEAR_FEATURE) {
2081 				f->func_wakeup_armed = false;
2082 
2083 				if (f->resume && f->func_suspended) {
2084 					f->resume(f);
2085 					f->func_suspended = false;
2086 				}
2087 			}
2088 
2089 			if (value < 0) {
2090 				ERROR(cdev,
2091 				      "func_suspend() returned error %d\n",
2092 				      value);
2093 				value = 0;
2094 			}
2095 			break;
2096 		}
2097 		break;
2098 	default:
2099 unknown:
2100 		/*
2101 		 * OS descriptors handling
2102 		 */
2103 		if (cdev->use_os_string && cdev->os_desc_config &&
2104 		    (ctrl->bRequestType & USB_TYPE_VENDOR) &&
2105 		    ctrl->bRequest == cdev->b_vendor_code) {
2106 			struct usb_configuration	*os_desc_cfg;
2107 			u8				*buf;
2108 			int				interface;
2109 			int				count = 0;
2110 
2111 			req = cdev->os_desc_req;
2112 			req->context = cdev;
2113 			req->complete = composite_setup_complete;
2114 			buf = req->buf;
2115 			os_desc_cfg = cdev->os_desc_config;
2116 			w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
2117 			memset(buf, 0, w_length);
2118 			buf[5] = 0x01;
2119 			switch (ctrl->bRequestType & USB_RECIP_MASK) {
2120 			case USB_RECIP_DEVICE:
2121 				if (w_index != 0x4 || (w_value >> 8))
2122 					break;
2123 				buf[6] = w_index;
2124 				/* Number of ext compat interfaces */
2125 				count = count_ext_compat(os_desc_cfg);
2126 				buf[8] = count;
2127 				count *= 24; /* 24 B/ext compat desc */
2128 				count += 16; /* header */
2129 				put_unaligned_le32(count, buf);
2130 				value = w_length;
2131 				if (w_length > 0x10) {
2132 					value = fill_ext_compat(os_desc_cfg, buf);
2133 					value = min_t(u16, w_length, value);
2134 				}
2135 				break;
2136 			case USB_RECIP_INTERFACE:
2137 				if (w_index != 0x5 || (w_value >> 8))
2138 					break;
2139 				interface = w_value & 0xFF;
2140 				if (interface >= MAX_CONFIG_INTERFACES ||
2141 				    !os_desc_cfg->interface[interface])
2142 					break;
2143 				buf[6] = w_index;
2144 				count = count_ext_prop(os_desc_cfg,
2145 					interface);
2146 				put_unaligned_le16(count, buf + 8);
2147 				count = len_ext_prop(os_desc_cfg,
2148 					interface);
2149 				put_unaligned_le32(count, buf);
2150 				value = w_length;
2151 				if (w_length > 0x0A) {
2152 					value = fill_ext_prop(os_desc_cfg,
2153 							      interface, buf);
2154 					if (value >= 0)
2155 						value = min_t(u16, w_length, value);
2156 				}
2157 				break;
2158 			}
2159 
2160 			goto check_value;
2161 		}
2162 
2163 		/*
2164 		 * WebUSB URL descriptor handling, following:
2165 		 * https://wicg.github.io/webusb/#device-requests
2166 		 */
2167 		if (cdev->use_webusb &&
2168 		    ctrl->bRequestType == (USB_DIR_IN | USB_TYPE_VENDOR) &&
2169 		    w_index == WEBUSB_GET_URL &&
2170 		    w_value == WEBUSB_LANDING_PAGE_PRESENT &&
2171 		    ctrl->bRequest == cdev->b_webusb_vendor_code) {
2172 			unsigned int	landing_page_length;
2173 			unsigned int	landing_page_offset;
2174 			struct webusb_url_descriptor *url_descriptor =
2175 					(struct webusb_url_descriptor *)cdev->req->buf;
2176 
2177 			url_descriptor->bDescriptorType = WEBUSB_URL_DESCRIPTOR_TYPE;
2178 
2179 			if (strncasecmp(cdev->landing_page, "https://",  8) == 0) {
2180 				landing_page_offset = 8;
2181 				url_descriptor->bScheme = WEBUSB_URL_SCHEME_HTTPS;
2182 			} else if (strncasecmp(cdev->landing_page, "http://", 7) == 0) {
2183 				landing_page_offset = 7;
2184 				url_descriptor->bScheme = WEBUSB_URL_SCHEME_HTTP;
2185 			} else {
2186 				landing_page_offset = 0;
2187 				url_descriptor->bScheme = WEBUSB_URL_SCHEME_NONE;
2188 			}
2189 
2190 			landing_page_length = strnlen(cdev->landing_page,
2191 				sizeof(url_descriptor->URL)
2192 				- WEBUSB_URL_DESCRIPTOR_HEADER_LENGTH + landing_page_offset);
2193 
2194 			if (w_length < WEBUSB_URL_DESCRIPTOR_HEADER_LENGTH + landing_page_length)
2195 				landing_page_length = w_length
2196 				- WEBUSB_URL_DESCRIPTOR_HEADER_LENGTH + landing_page_offset;
2197 
2198 			memcpy(url_descriptor->URL,
2199 				cdev->landing_page + landing_page_offset,
2200 				landing_page_length - landing_page_offset);
2201 			url_descriptor->bLength = landing_page_length
2202 				- landing_page_offset + WEBUSB_URL_DESCRIPTOR_HEADER_LENGTH;
2203 
2204 			value = url_descriptor->bLength;
2205 
2206 			goto check_value;
2207 		}
2208 
2209 		VDBG(cdev,
2210 			"non-core control req%02x.%02x v%04x i%04x l%d\n",
2211 			ctrl->bRequestType, ctrl->bRequest,
2212 			w_value, w_index, w_length);
2213 
2214 		/* functions always handle their interfaces and endpoints...
2215 		 * punt other recipients (other, WUSB, ...) to the current
2216 		 * configuration code.
2217 		 */
2218 		if (cdev->config) {
2219 			list_for_each_entry(f, &cdev->config->functions, list)
2220 				if (f->req_match &&
2221 				    f->req_match(f, ctrl, false))
2222 					goto try_fun_setup;
2223 		} else {
2224 			struct usb_configuration *c;
2225 			list_for_each_entry(c, &cdev->configs, list)
2226 				list_for_each_entry(f, &c->functions, list)
2227 					if (f->req_match &&
2228 					    f->req_match(f, ctrl, true))
2229 						goto try_fun_setup;
2230 		}
2231 		f = NULL;
2232 
2233 		switch (ctrl->bRequestType & USB_RECIP_MASK) {
2234 		case USB_RECIP_INTERFACE:
2235 			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
2236 				break;
2237 			f = cdev->config->interface[intf];
2238 			break;
2239 
2240 		case USB_RECIP_ENDPOINT:
2241 			if (!cdev->config)
2242 				break;
2243 			endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
2244 			list_for_each_entry(iter, &cdev->config->functions, list) {
2245 				if (test_bit(endp, iter->endpoints)) {
2246 					f = iter;
2247 					break;
2248 				}
2249 			}
2250 			break;
2251 		}
2252 try_fun_setup:
2253 		if (f && f->setup)
2254 			value = f->setup(f, ctrl);
2255 		else {
2256 			struct usb_configuration	*c;
2257 
2258 			c = cdev->config;
2259 			if (!c)
2260 				goto done;
2261 
2262 			/* try current config's setup */
2263 			if (c->setup) {
2264 				value = c->setup(c, ctrl);
2265 				goto done;
2266 			}
2267 
2268 			/* try the only function in the current config */
2269 			if (!list_is_singular(&c->functions))
2270 				goto done;
2271 			f = list_first_entry(&c->functions, struct usb_function,
2272 					     list);
2273 			if (f->setup)
2274 				value = f->setup(f, ctrl);
2275 		}
2276 
2277 		goto done;
2278 	}
2279 
2280 check_value:
2281 	/* respond with data transfer before status phase? */
2282 	if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
2283 		req->length = value;
2284 		req->context = cdev;
2285 		req->zero = value < w_length;
2286 		value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2287 		if (value < 0) {
2288 			DBG(cdev, "ep_queue --> %d\n", value);
2289 			req->status = 0;
2290 			composite_setup_complete(gadget->ep0, req);
2291 		}
2292 	} else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
2293 		WARN(cdev,
2294 			"%s: Delayed status not supported for w_length != 0",
2295 			__func__);
2296 	}
2297 
2298 done:
2299 	/* device either stalls (value < 0) or reports success */
2300 	return value;
2301 }
2302 
2303 static void __composite_disconnect(struct usb_gadget *gadget)
2304 {
2305 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2306 	unsigned long			flags;
2307 
2308 	/* REVISIT:  should we have config and device level
2309 	 * disconnect callbacks?
2310 	 */
2311 	spin_lock_irqsave(&cdev->lock, flags);
2312 	cdev->suspended = 0;
2313 	if (cdev->config)
2314 		reset_config(cdev);
2315 	if (cdev->driver->disconnect)
2316 		cdev->driver->disconnect(cdev);
2317 	spin_unlock_irqrestore(&cdev->lock, flags);
2318 }
2319 
2320 void composite_disconnect(struct usb_gadget *gadget)
2321 {
2322 	usb_gadget_vbus_draw(gadget, 0);
2323 	__composite_disconnect(gadget);
2324 }
2325 
2326 void composite_reset(struct usb_gadget *gadget)
2327 {
2328 	/*
2329 	 * Section 1.4.13 Standard Downstream Port of the USB battery charging
2330 	 * specification v1.2 states that a device connected on a SDP shall only
2331 	 * draw at max 100mA while in a connected, but unconfigured state.
2332 	 */
2333 	usb_gadget_vbus_draw(gadget, 100);
2334 	__composite_disconnect(gadget);
2335 }
2336 
2337 /*-------------------------------------------------------------------------*/
2338 
2339 static ssize_t suspended_show(struct device *dev, struct device_attribute *attr,
2340 			      char *buf)
2341 {
2342 	struct usb_gadget *gadget = dev_to_usb_gadget(dev);
2343 	struct usb_composite_dev *cdev = get_gadget_data(gadget);
2344 
2345 	return sprintf(buf, "%d\n", cdev->suspended);
2346 }
2347 static DEVICE_ATTR_RO(suspended);
2348 
2349 static void __composite_unbind(struct usb_gadget *gadget, bool unbind_driver)
2350 {
2351 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2352 	struct usb_gadget_strings	*gstr = cdev->driver->strings[0];
2353 	struct usb_string		*dev_str = gstr->strings;
2354 
2355 	/* composite_disconnect() must already have been called
2356 	 * by the underlying peripheral controller driver!
2357 	 * so there's no i/o concurrency that could affect the
2358 	 * state protected by cdev->lock.
2359 	 */
2360 	WARN_ON(cdev->config);
2361 
2362 	while (!list_empty(&cdev->configs)) {
2363 		struct usb_configuration	*c;
2364 		c = list_first_entry(&cdev->configs,
2365 				struct usb_configuration, list);
2366 		remove_config(cdev, c);
2367 	}
2368 	if (cdev->driver->unbind && unbind_driver)
2369 		cdev->driver->unbind(cdev);
2370 
2371 	composite_dev_cleanup(cdev);
2372 
2373 	if (dev_str[USB_GADGET_MANUFACTURER_IDX].s == cdev->def_manufacturer)
2374 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = "";
2375 
2376 	kfree(cdev->def_manufacturer);
2377 	kfree(cdev);
2378 	set_gadget_data(gadget, NULL);
2379 }
2380 
2381 static void composite_unbind(struct usb_gadget *gadget)
2382 {
2383 	__composite_unbind(gadget, true);
2384 }
2385 
2386 static void update_unchanged_dev_desc(struct usb_device_descriptor *new,
2387 		const struct usb_device_descriptor *old)
2388 {
2389 	__le16 idVendor;
2390 	__le16 idProduct;
2391 	__le16 bcdDevice;
2392 	u8 iSerialNumber;
2393 	u8 iManufacturer;
2394 	u8 iProduct;
2395 
2396 	/*
2397 	 * these variables may have been set in
2398 	 * usb_composite_overwrite_options()
2399 	 */
2400 	idVendor = new->idVendor;
2401 	idProduct = new->idProduct;
2402 	bcdDevice = new->bcdDevice;
2403 	iSerialNumber = new->iSerialNumber;
2404 	iManufacturer = new->iManufacturer;
2405 	iProduct = new->iProduct;
2406 
2407 	*new = *old;
2408 	if (idVendor)
2409 		new->idVendor = idVendor;
2410 	if (idProduct)
2411 		new->idProduct = idProduct;
2412 	if (bcdDevice)
2413 		new->bcdDevice = bcdDevice;
2414 	else
2415 		new->bcdDevice = cpu_to_le16(get_default_bcdDevice());
2416 	if (iSerialNumber)
2417 		new->iSerialNumber = iSerialNumber;
2418 	if (iManufacturer)
2419 		new->iManufacturer = iManufacturer;
2420 	if (iProduct)
2421 		new->iProduct = iProduct;
2422 }
2423 
2424 int composite_dev_prepare(struct usb_composite_driver *composite,
2425 		struct usb_composite_dev *cdev)
2426 {
2427 	struct usb_gadget *gadget = cdev->gadget;
2428 	int ret = -ENOMEM;
2429 
2430 	/* preallocate control response and buffer */
2431 	cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2432 	if (!cdev->req)
2433 		return -ENOMEM;
2434 
2435 	cdev->req->buf = kzalloc(USB_COMP_EP0_BUFSIZ, GFP_KERNEL);
2436 	if (!cdev->req->buf)
2437 		goto fail;
2438 
2439 	ret = device_create_file(&gadget->dev, &dev_attr_suspended);
2440 	if (ret)
2441 		goto fail_dev;
2442 
2443 	cdev->req->complete = composite_setup_complete;
2444 	cdev->req->context = cdev;
2445 	gadget->ep0->driver_data = cdev;
2446 
2447 	cdev->driver = composite;
2448 
2449 	/*
2450 	 * As per USB compliance update, a device that is actively drawing
2451 	 * more than 100mA from USB must report itself as bus-powered in
2452 	 * the GetStatus(DEVICE) call.
2453 	 */
2454 	if (CONFIG_USB_GADGET_VBUS_DRAW <= USB_SELF_POWER_VBUS_MAX_DRAW)
2455 		usb_gadget_set_selfpowered(gadget);
2456 
2457 	/* interface and string IDs start at zero via kzalloc.
2458 	 * we force endpoints to start unassigned; few controller
2459 	 * drivers will zero ep->driver_data.
2460 	 */
2461 	usb_ep_autoconfig_reset(gadget);
2462 	return 0;
2463 fail_dev:
2464 	kfree(cdev->req->buf);
2465 fail:
2466 	usb_ep_free_request(gadget->ep0, cdev->req);
2467 	cdev->req = NULL;
2468 	return ret;
2469 }
2470 
2471 int composite_os_desc_req_prepare(struct usb_composite_dev *cdev,
2472 				  struct usb_ep *ep0)
2473 {
2474 	int ret = 0;
2475 
2476 	cdev->os_desc_req = usb_ep_alloc_request(ep0, GFP_KERNEL);
2477 	if (!cdev->os_desc_req) {
2478 		ret = -ENOMEM;
2479 		goto end;
2480 	}
2481 
2482 	cdev->os_desc_req->buf = kmalloc(USB_COMP_EP0_OS_DESC_BUFSIZ,
2483 					 GFP_KERNEL);
2484 	if (!cdev->os_desc_req->buf) {
2485 		ret = -ENOMEM;
2486 		usb_ep_free_request(ep0, cdev->os_desc_req);
2487 		goto end;
2488 	}
2489 	cdev->os_desc_req->context = cdev;
2490 	cdev->os_desc_req->complete = composite_setup_complete;
2491 end:
2492 	return ret;
2493 }
2494 
2495 void composite_dev_cleanup(struct usb_composite_dev *cdev)
2496 {
2497 	struct usb_gadget_string_container *uc, *tmp;
2498 	struct usb_ep			   *ep, *tmp_ep;
2499 
2500 	list_for_each_entry_safe(uc, tmp, &cdev->gstrings, list) {
2501 		list_del(&uc->list);
2502 		kfree(uc);
2503 	}
2504 	if (cdev->os_desc_req) {
2505 		if (cdev->os_desc_pending)
2506 			usb_ep_dequeue(cdev->gadget->ep0, cdev->os_desc_req);
2507 
2508 		kfree(cdev->os_desc_req->buf);
2509 		cdev->os_desc_req->buf = NULL;
2510 		usb_ep_free_request(cdev->gadget->ep0, cdev->os_desc_req);
2511 		cdev->os_desc_req = NULL;
2512 	}
2513 	if (cdev->req) {
2514 		if (cdev->setup_pending)
2515 			usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
2516 
2517 		kfree(cdev->req->buf);
2518 		cdev->req->buf = NULL;
2519 		usb_ep_free_request(cdev->gadget->ep0, cdev->req);
2520 		cdev->req = NULL;
2521 	}
2522 	cdev->next_string_id = 0;
2523 	device_remove_file(&cdev->gadget->dev, &dev_attr_suspended);
2524 
2525 	/*
2526 	 * Some UDC backends have a dynamic EP allocation scheme.
2527 	 *
2528 	 * In that case, the dispose() callback is used to notify the
2529 	 * backend that the EPs are no longer in use.
2530 	 *
2531 	 * Note: The UDC backend can remove the EP from the ep_list as
2532 	 *	 a result, so we need to use the _safe list iterator.
2533 	 */
2534 	list_for_each_entry_safe(ep, tmp_ep,
2535 				 &cdev->gadget->ep_list, ep_list) {
2536 		if (ep->ops->dispose)
2537 			ep->ops->dispose(ep);
2538 	}
2539 }
2540 
2541 static int composite_bind(struct usb_gadget *gadget,
2542 		struct usb_gadget_driver *gdriver)
2543 {
2544 	struct usb_composite_dev	*cdev;
2545 	struct usb_composite_driver	*composite = to_cdriver(gdriver);
2546 	int				status = -ENOMEM;
2547 
2548 	cdev = kzalloc(sizeof *cdev, GFP_KERNEL);
2549 	if (!cdev)
2550 		return status;
2551 
2552 	spin_lock_init(&cdev->lock);
2553 	cdev->gadget = gadget;
2554 	set_gadget_data(gadget, cdev);
2555 	INIT_LIST_HEAD(&cdev->configs);
2556 	INIT_LIST_HEAD(&cdev->gstrings);
2557 
2558 	status = composite_dev_prepare(composite, cdev);
2559 	if (status)
2560 		goto fail;
2561 
2562 	/* composite gadget needs to assign strings for whole device (like
2563 	 * serial number), register function drivers, potentially update
2564 	 * power state and consumption, etc
2565 	 */
2566 	status = composite->bind(cdev);
2567 	if (status < 0)
2568 		goto fail;
2569 
2570 	if (cdev->use_os_string) {
2571 		status = composite_os_desc_req_prepare(cdev, gadget->ep0);
2572 		if (status)
2573 			goto fail;
2574 	}
2575 
2576 	update_unchanged_dev_desc(&cdev->desc, composite->dev);
2577 
2578 	/* has userspace failed to provide a serial number? */
2579 	if (composite->needs_serial && !cdev->desc.iSerialNumber)
2580 		WARNING(cdev, "userspace failed to provide iSerialNumber\n");
2581 
2582 	INFO(cdev, "%s ready\n", composite->name);
2583 	return 0;
2584 
2585 fail:
2586 	__composite_unbind(gadget, false);
2587 	return status;
2588 }
2589 
2590 /*-------------------------------------------------------------------------*/
2591 
2592 void composite_suspend(struct usb_gadget *gadget)
2593 {
2594 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2595 	struct usb_function		*f;
2596 
2597 	/* REVISIT:  should we have config level
2598 	 * suspend/resume callbacks?
2599 	 */
2600 	DBG(cdev, "suspend\n");
2601 	if (cdev->config) {
2602 		list_for_each_entry(f, &cdev->config->functions, list) {
2603 			if (f->suspend)
2604 				f->suspend(f);
2605 		}
2606 	}
2607 	if (cdev->driver->suspend)
2608 		cdev->driver->suspend(cdev);
2609 
2610 	cdev->suspended = 1;
2611 
2612 	usb_gadget_set_selfpowered(gadget);
2613 	usb_gadget_vbus_draw(gadget, 2);
2614 }
2615 
2616 void composite_resume(struct usb_gadget *gadget)
2617 {
2618 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
2619 	struct usb_function		*f;
2620 	unsigned			maxpower;
2621 
2622 	/* REVISIT:  should we have config level
2623 	 * suspend/resume callbacks?
2624 	 */
2625 	DBG(cdev, "resume\n");
2626 	if (cdev->driver->resume)
2627 		cdev->driver->resume(cdev);
2628 	if (cdev->config) {
2629 		list_for_each_entry(f, &cdev->config->functions, list) {
2630 			/*
2631 			 * Check for func_suspended flag to see if the function is
2632 			 * in USB3 FUNCTION_SUSPEND state. In this case resume is
2633 			 * done via FUNCTION_SUSPEND feature selector.
2634 			 */
2635 			if (f->resume && !f->func_suspended)
2636 				f->resume(f);
2637 		}
2638 
2639 		maxpower = cdev->config->MaxPower ?
2640 			cdev->config->MaxPower : CONFIG_USB_GADGET_VBUS_DRAW;
2641 		if (gadget->speed < USB_SPEED_SUPER)
2642 			maxpower = min(maxpower, 500U);
2643 		else
2644 			maxpower = min(maxpower, 900U);
2645 
2646 		if (maxpower > USB_SELF_POWER_VBUS_MAX_DRAW)
2647 			usb_gadget_clear_selfpowered(gadget);
2648 
2649 		usb_gadget_vbus_draw(gadget, maxpower);
2650 	} else {
2651 		maxpower = CONFIG_USB_GADGET_VBUS_DRAW;
2652 		maxpower = min(maxpower, 100U);
2653 		usb_gadget_vbus_draw(gadget, maxpower);
2654 	}
2655 
2656 	cdev->suspended = 0;
2657 }
2658 
2659 /*-------------------------------------------------------------------------*/
2660 
2661 static const struct usb_gadget_driver composite_driver_template = {
2662 	.bind		= composite_bind,
2663 	.unbind		= composite_unbind,
2664 
2665 	.setup		= composite_setup,
2666 	.reset		= composite_reset,
2667 	.disconnect	= composite_disconnect,
2668 
2669 	.suspend	= composite_suspend,
2670 	.resume		= composite_resume,
2671 
2672 	.driver	= {
2673 		.owner		= THIS_MODULE,
2674 	},
2675 };
2676 
2677 /**
2678  * usb_composite_probe() - register a composite driver
2679  * @driver: the driver to register
2680  *
2681  * Context: single threaded during gadget setup
2682  *
2683  * This function is used to register drivers using the composite driver
2684  * framework.  The return value is zero, or a negative errno value.
2685  * Those values normally come from the driver's @bind method, which does
2686  * all the work of setting up the driver to match the hardware.
2687  *
2688  * On successful return, the gadget is ready to respond to requests from
2689  * the host, unless one of its components invokes usb_gadget_disconnect()
2690  * while it was binding.  That would usually be done in order to wait for
2691  * some userspace participation.
2692  */
2693 int usb_composite_probe(struct usb_composite_driver *driver)
2694 {
2695 	struct usb_gadget_driver *gadget_driver;
2696 
2697 	if (!driver || !driver->dev || !driver->bind)
2698 		return -EINVAL;
2699 
2700 	if (!driver->name)
2701 		driver->name = "composite";
2702 
2703 	driver->gadget_driver = composite_driver_template;
2704 	gadget_driver = &driver->gadget_driver;
2705 
2706 	gadget_driver->function =  (char *) driver->name;
2707 	gadget_driver->driver.name = driver->name;
2708 	gadget_driver->max_speed = driver->max_speed;
2709 
2710 	return usb_gadget_register_driver(gadget_driver);
2711 }
2712 EXPORT_SYMBOL_GPL(usb_composite_probe);
2713 
2714 /**
2715  * usb_composite_unregister() - unregister a composite driver
2716  * @driver: the driver to unregister
2717  *
2718  * This function is used to unregister drivers using the composite
2719  * driver framework.
2720  */
2721 void usb_composite_unregister(struct usb_composite_driver *driver)
2722 {
2723 	usb_gadget_unregister_driver(&driver->gadget_driver);
2724 }
2725 EXPORT_SYMBOL_GPL(usb_composite_unregister);
2726 
2727 /**
2728  * usb_composite_setup_continue() - Continue with the control transfer
2729  * @cdev: the composite device who's control transfer was kept waiting
2730  *
2731  * This function must be called by the USB function driver to continue
2732  * with the control transfer's data/status stage in case it had requested to
2733  * delay the data/status stages. A USB function's setup handler (e.g. set_alt())
2734  * can request the composite framework to delay the setup request's data/status
2735  * stages by returning USB_GADGET_DELAYED_STATUS.
2736  */
2737 void usb_composite_setup_continue(struct usb_composite_dev *cdev)
2738 {
2739 	int			value;
2740 	struct usb_request	*req = cdev->req;
2741 	unsigned long		flags;
2742 
2743 	DBG(cdev, "%s\n", __func__);
2744 	spin_lock_irqsave(&cdev->lock, flags);
2745 
2746 	if (cdev->delayed_status == 0) {
2747 		WARN(cdev, "%s: Unexpected call\n", __func__);
2748 
2749 	} else if (--cdev->delayed_status == 0) {
2750 		DBG(cdev, "%s: Completing delayed status\n", __func__);
2751 		req->length = 0;
2752 		req->context = cdev;
2753 		value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
2754 		if (value < 0) {
2755 			DBG(cdev, "ep_queue --> %d\n", value);
2756 			req->status = 0;
2757 			composite_setup_complete(cdev->gadget->ep0, req);
2758 		}
2759 	}
2760 
2761 	spin_unlock_irqrestore(&cdev->lock, flags);
2762 }
2763 EXPORT_SYMBOL_GPL(usb_composite_setup_continue);
2764 
2765 static char *composite_default_mfr(struct usb_gadget *gadget)
2766 {
2767 	return kasprintf(GFP_KERNEL, "%s %s with %s", init_utsname()->sysname,
2768 			 init_utsname()->release, gadget->name);
2769 }
2770 
2771 void usb_composite_overwrite_options(struct usb_composite_dev *cdev,
2772 		struct usb_composite_overwrite *covr)
2773 {
2774 	struct usb_device_descriptor	*desc = &cdev->desc;
2775 	struct usb_gadget_strings	*gstr = cdev->driver->strings[0];
2776 	struct usb_string		*dev_str = gstr->strings;
2777 
2778 	if (covr->idVendor)
2779 		desc->idVendor = cpu_to_le16(covr->idVendor);
2780 
2781 	if (covr->idProduct)
2782 		desc->idProduct = cpu_to_le16(covr->idProduct);
2783 
2784 	if (covr->bcdDevice)
2785 		desc->bcdDevice = cpu_to_le16(covr->bcdDevice);
2786 
2787 	if (covr->serial_number) {
2788 		desc->iSerialNumber = dev_str[USB_GADGET_SERIAL_IDX].id;
2789 		dev_str[USB_GADGET_SERIAL_IDX].s = covr->serial_number;
2790 	}
2791 	if (covr->manufacturer) {
2792 		desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2793 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = covr->manufacturer;
2794 
2795 	} else if (!strlen(dev_str[USB_GADGET_MANUFACTURER_IDX].s)) {
2796 		desc->iManufacturer = dev_str[USB_GADGET_MANUFACTURER_IDX].id;
2797 		cdev->def_manufacturer = composite_default_mfr(cdev->gadget);
2798 		dev_str[USB_GADGET_MANUFACTURER_IDX].s = cdev->def_manufacturer;
2799 	}
2800 
2801 	if (covr->product) {
2802 		desc->iProduct = dev_str[USB_GADGET_PRODUCT_IDX].id;
2803 		dev_str[USB_GADGET_PRODUCT_IDX].s = covr->product;
2804 	}
2805 }
2806 EXPORT_SYMBOL_GPL(usb_composite_overwrite_options);
2807 
2808 MODULE_LICENSE("GPL");
2809 MODULE_AUTHOR("David Brownell");
2810