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