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