xref: /openbmc/linux/drivers/usb/gadget/composite.c (revision 9cfc5c90)
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 ep->claimed as needed */
843 	usb_ep_autoconfig_reset(cdev->gadget);
844 
845 done:
846 	if (status)
847 		DBG(cdev, "added config '%s'/%u --> %d\n", config->label,
848 				config->bConfigurationValue, status);
849 	return status;
850 }
851 EXPORT_SYMBOL_GPL(usb_add_config);
852 
853 static void remove_config(struct usb_composite_dev *cdev,
854 			      struct usb_configuration *config)
855 {
856 	while (!list_empty(&config->functions)) {
857 		struct usb_function		*f;
858 
859 		f = list_first_entry(&config->functions,
860 				struct usb_function, list);
861 		list_del(&f->list);
862 		if (f->unbind) {
863 			DBG(cdev, "unbind function '%s'/%p\n", f->name, f);
864 			f->unbind(config, f);
865 			/* may free memory for "f" */
866 		}
867 	}
868 	list_del(&config->list);
869 	if (config->unbind) {
870 		DBG(cdev, "unbind config '%s'/%p\n", config->label, config);
871 		config->unbind(config);
872 			/* may free memory for "c" */
873 	}
874 }
875 
876 /**
877  * usb_remove_config() - remove a configuration from a device.
878  * @cdev: wraps the USB gadget
879  * @config: the configuration
880  *
881  * Drivers must call usb_gadget_disconnect before calling this function
882  * to disconnect the device from the host and make sure the host will not
883  * try to enumerate the device while we are changing the config list.
884  */
885 void usb_remove_config(struct usb_composite_dev *cdev,
886 		      struct usb_configuration *config)
887 {
888 	unsigned long flags;
889 
890 	spin_lock_irqsave(&cdev->lock, flags);
891 
892 	if (cdev->config == config)
893 		reset_config(cdev);
894 
895 	spin_unlock_irqrestore(&cdev->lock, flags);
896 
897 	remove_config(cdev, config);
898 }
899 
900 /*-------------------------------------------------------------------------*/
901 
902 /* We support strings in multiple languages ... string descriptor zero
903  * says which languages are supported.  The typical case will be that
904  * only one language (probably English) is used, with i18n handled on
905  * the host side.
906  */
907 
908 static void collect_langs(struct usb_gadget_strings **sp, __le16 *buf)
909 {
910 	const struct usb_gadget_strings	*s;
911 	__le16				language;
912 	__le16				*tmp;
913 
914 	while (*sp) {
915 		s = *sp;
916 		language = cpu_to_le16(s->language);
917 		for (tmp = buf; *tmp && tmp < &buf[126]; tmp++) {
918 			if (*tmp == language)
919 				goto repeat;
920 		}
921 		*tmp++ = language;
922 repeat:
923 		sp++;
924 	}
925 }
926 
927 static int lookup_string(
928 	struct usb_gadget_strings	**sp,
929 	void				*buf,
930 	u16				language,
931 	int				id
932 )
933 {
934 	struct usb_gadget_strings	*s;
935 	int				value;
936 
937 	while (*sp) {
938 		s = *sp++;
939 		if (s->language != language)
940 			continue;
941 		value = usb_gadget_get_string(s, id, buf);
942 		if (value > 0)
943 			return value;
944 	}
945 	return -EINVAL;
946 }
947 
948 static int get_string(struct usb_composite_dev *cdev,
949 		void *buf, u16 language, int id)
950 {
951 	struct usb_composite_driver	*composite = cdev->driver;
952 	struct usb_gadget_string_container *uc;
953 	struct usb_configuration	*c;
954 	struct usb_function		*f;
955 	int				len;
956 
957 	/* Yes, not only is USB's i18n support probably more than most
958 	 * folk will ever care about ... also, it's all supported here.
959 	 * (Except for UTF8 support for Unicode's "Astral Planes".)
960 	 */
961 
962 	/* 0 == report all available language codes */
963 	if (id == 0) {
964 		struct usb_string_descriptor	*s = buf;
965 		struct usb_gadget_strings	**sp;
966 
967 		memset(s, 0, 256);
968 		s->bDescriptorType = USB_DT_STRING;
969 
970 		sp = composite->strings;
971 		if (sp)
972 			collect_langs(sp, s->wData);
973 
974 		list_for_each_entry(c, &cdev->configs, list) {
975 			sp = c->strings;
976 			if (sp)
977 				collect_langs(sp, s->wData);
978 
979 			list_for_each_entry(f, &c->functions, list) {
980 				sp = f->strings;
981 				if (sp)
982 					collect_langs(sp, s->wData);
983 			}
984 		}
985 		list_for_each_entry(uc, &cdev->gstrings, list) {
986 			struct usb_gadget_strings **sp;
987 
988 			sp = get_containers_gs(uc);
989 			collect_langs(sp, s->wData);
990 		}
991 
992 		for (len = 0; len <= 126 && s->wData[len]; len++)
993 			continue;
994 		if (!len)
995 			return -EINVAL;
996 
997 		s->bLength = 2 * (len + 1);
998 		return s->bLength;
999 	}
1000 
1001 	if (cdev->use_os_string && language == 0 && id == OS_STRING_IDX) {
1002 		struct usb_os_string *b = buf;
1003 		b->bLength = sizeof(*b);
1004 		b->bDescriptorType = USB_DT_STRING;
1005 		compiletime_assert(
1006 			sizeof(b->qwSignature) == sizeof(cdev->qw_sign),
1007 			"qwSignature size must be equal to qw_sign");
1008 		memcpy(&b->qwSignature, cdev->qw_sign, sizeof(b->qwSignature));
1009 		b->bMS_VendorCode = cdev->b_vendor_code;
1010 		b->bPad = 0;
1011 		return sizeof(*b);
1012 	}
1013 
1014 	list_for_each_entry(uc, &cdev->gstrings, list) {
1015 		struct usb_gadget_strings **sp;
1016 
1017 		sp = get_containers_gs(uc);
1018 		len = lookup_string(sp, buf, language, id);
1019 		if (len > 0)
1020 			return len;
1021 	}
1022 
1023 	/* String IDs are device-scoped, so we look up each string
1024 	 * table we're told about.  These lookups are infrequent;
1025 	 * simpler-is-better here.
1026 	 */
1027 	if (composite->strings) {
1028 		len = lookup_string(composite->strings, buf, language, id);
1029 		if (len > 0)
1030 			return len;
1031 	}
1032 	list_for_each_entry(c, &cdev->configs, list) {
1033 		if (c->strings) {
1034 			len = lookup_string(c->strings, buf, language, id);
1035 			if (len > 0)
1036 				return len;
1037 		}
1038 		list_for_each_entry(f, &c->functions, list) {
1039 			if (!f->strings)
1040 				continue;
1041 			len = lookup_string(f->strings, buf, language, id);
1042 			if (len > 0)
1043 				return len;
1044 		}
1045 	}
1046 	return -EINVAL;
1047 }
1048 
1049 /**
1050  * usb_string_id() - allocate an unused string ID
1051  * @cdev: the device whose string descriptor IDs are being allocated
1052  * Context: single threaded during gadget setup
1053  *
1054  * @usb_string_id() is called from bind() callbacks to allocate
1055  * string IDs.  Drivers for functions, configurations, or gadgets will
1056  * then store that ID in the appropriate descriptors and string table.
1057  *
1058  * All string identifier should be allocated using this,
1059  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
1060  * that for example different functions don't wrongly assign different
1061  * meanings to the same identifier.
1062  */
1063 int usb_string_id(struct usb_composite_dev *cdev)
1064 {
1065 	if (cdev->next_string_id < 254) {
1066 		/* string id 0 is reserved by USB spec for list of
1067 		 * supported languages */
1068 		/* 255 reserved as well? -- mina86 */
1069 		cdev->next_string_id++;
1070 		return cdev->next_string_id;
1071 	}
1072 	return -ENODEV;
1073 }
1074 EXPORT_SYMBOL_GPL(usb_string_id);
1075 
1076 /**
1077  * usb_string_ids() - allocate unused string IDs in batch
1078  * @cdev: the device whose string descriptor IDs are being allocated
1079  * @str: an array of usb_string objects to assign numbers to
1080  * Context: single threaded during gadget setup
1081  *
1082  * @usb_string_ids() is called from bind() callbacks to allocate
1083  * string IDs.  Drivers for functions, configurations, or gadgets will
1084  * then copy IDs from the string table to the appropriate descriptors
1085  * and string table for other languages.
1086  *
1087  * All string identifier should be allocated using this,
1088  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1089  * example different functions don't wrongly assign different meanings
1090  * to the same identifier.
1091  */
1092 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
1093 {
1094 	int next = cdev->next_string_id;
1095 
1096 	for (; str->s; ++str) {
1097 		if (unlikely(next >= 254))
1098 			return -ENODEV;
1099 		str->id = ++next;
1100 	}
1101 
1102 	cdev->next_string_id = next;
1103 
1104 	return 0;
1105 }
1106 EXPORT_SYMBOL_GPL(usb_string_ids_tab);
1107 
1108 static struct usb_gadget_string_container *copy_gadget_strings(
1109 		struct usb_gadget_strings **sp, unsigned n_gstrings,
1110 		unsigned n_strings)
1111 {
1112 	struct usb_gadget_string_container *uc;
1113 	struct usb_gadget_strings **gs_array;
1114 	struct usb_gadget_strings *gs;
1115 	struct usb_string *s;
1116 	unsigned mem;
1117 	unsigned n_gs;
1118 	unsigned n_s;
1119 	void *stash;
1120 
1121 	mem = sizeof(*uc);
1122 	mem += sizeof(void *) * (n_gstrings + 1);
1123 	mem += sizeof(struct usb_gadget_strings) * n_gstrings;
1124 	mem += sizeof(struct usb_string) * (n_strings + 1) * (n_gstrings);
1125 	uc = kmalloc(mem, GFP_KERNEL);
1126 	if (!uc)
1127 		return ERR_PTR(-ENOMEM);
1128 	gs_array = get_containers_gs(uc);
1129 	stash = uc->stash;
1130 	stash += sizeof(void *) * (n_gstrings + 1);
1131 	for (n_gs = 0; n_gs < n_gstrings; n_gs++) {
1132 		struct usb_string *org_s;
1133 
1134 		gs_array[n_gs] = stash;
1135 		gs = gs_array[n_gs];
1136 		stash += sizeof(struct usb_gadget_strings);
1137 		gs->language = sp[n_gs]->language;
1138 		gs->strings = stash;
1139 		org_s = sp[n_gs]->strings;
1140 
1141 		for (n_s = 0; n_s < n_strings; n_s++) {
1142 			s = stash;
1143 			stash += sizeof(struct usb_string);
1144 			if (org_s->s)
1145 				s->s = org_s->s;
1146 			else
1147 				s->s = "";
1148 			org_s++;
1149 		}
1150 		s = stash;
1151 		s->s = NULL;
1152 		stash += sizeof(struct usb_string);
1153 
1154 	}
1155 	gs_array[n_gs] = NULL;
1156 	return uc;
1157 }
1158 
1159 /**
1160  * usb_gstrings_attach() - attach gadget strings to a cdev and assign ids
1161  * @cdev: the device whose string descriptor IDs are being allocated
1162  * and attached.
1163  * @sp: an array of usb_gadget_strings to attach.
1164  * @n_strings: number of entries in each usb_strings array (sp[]->strings)
1165  *
1166  * This function will create a deep copy of usb_gadget_strings and usb_string
1167  * and attach it to the cdev. The actual string (usb_string.s) will not be
1168  * copied but only a referenced will be made. The struct usb_gadget_strings
1169  * array may contain multiple languages and should be NULL terminated.
1170  * The ->language pointer of each struct usb_gadget_strings has to contain the
1171  * same amount of entries.
1172  * For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first
1173  * usb_string entry of es-ES contains the translation of the first usb_string
1174  * entry of en-US. Therefore both entries become the same id assign.
1175  */
1176 struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev,
1177 		struct usb_gadget_strings **sp, unsigned n_strings)
1178 {
1179 	struct usb_gadget_string_container *uc;
1180 	struct usb_gadget_strings **n_gs;
1181 	unsigned n_gstrings = 0;
1182 	unsigned i;
1183 	int ret;
1184 
1185 	for (i = 0; sp[i]; i++)
1186 		n_gstrings++;
1187 
1188 	if (!n_gstrings)
1189 		return ERR_PTR(-EINVAL);
1190 
1191 	uc = copy_gadget_strings(sp, n_gstrings, n_strings);
1192 	if (IS_ERR(uc))
1193 		return ERR_CAST(uc);
1194 
1195 	n_gs = get_containers_gs(uc);
1196 	ret = usb_string_ids_tab(cdev, n_gs[0]->strings);
1197 	if (ret)
1198 		goto err;
1199 
1200 	for (i = 1; i < n_gstrings; i++) {
1201 		struct usb_string *m_s;
1202 		struct usb_string *s;
1203 		unsigned n;
1204 
1205 		m_s = n_gs[0]->strings;
1206 		s = n_gs[i]->strings;
1207 		for (n = 0; n < n_strings; n++) {
1208 			s->id = m_s->id;
1209 			s++;
1210 			m_s++;
1211 		}
1212 	}
1213 	list_add_tail(&uc->list, &cdev->gstrings);
1214 	return n_gs[0]->strings;
1215 err:
1216 	kfree(uc);
1217 	return ERR_PTR(ret);
1218 }
1219 EXPORT_SYMBOL_GPL(usb_gstrings_attach);
1220 
1221 /**
1222  * usb_string_ids_n() - allocate unused string IDs in batch
1223  * @c: the device whose string descriptor IDs are being allocated
1224  * @n: number of string IDs to allocate
1225  * Context: single threaded during gadget setup
1226  *
1227  * Returns the first requested ID.  This ID and next @n-1 IDs are now
1228  * valid IDs.  At least provided that @n is non-zero because if it
1229  * is, returns last requested ID which is now very useful information.
1230  *
1231  * @usb_string_ids_n() is called from bind() callbacks to allocate
1232  * string IDs.  Drivers for functions, configurations, or gadgets will
1233  * then store that ID in the appropriate descriptors and string table.
1234  *
1235  * All string identifier should be allocated using this,
1236  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
1237  * example different functions don't wrongly assign different meanings
1238  * to the same identifier.
1239  */
1240 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
1241 {
1242 	unsigned next = c->next_string_id;
1243 	if (unlikely(n > 254 || (unsigned)next + n > 254))
1244 		return -ENODEV;
1245 	c->next_string_id += n;
1246 	return next + 1;
1247 }
1248 EXPORT_SYMBOL_GPL(usb_string_ids_n);
1249 
1250 /*-------------------------------------------------------------------------*/
1251 
1252 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
1253 {
1254 	struct usb_composite_dev *cdev;
1255 
1256 	if (req->status || req->actual != req->length)
1257 		DBG((struct usb_composite_dev *) ep->driver_data,
1258 				"setup complete --> %d, %d/%d\n",
1259 				req->status, req->actual, req->length);
1260 
1261 	/*
1262 	 * REVIST The same ep0 requests are shared with function drivers
1263 	 * so they don't have to maintain the same ->complete() stubs.
1264 	 *
1265 	 * Because of that, we need to check for the validity of ->context
1266 	 * here, even though we know we've set it to something useful.
1267 	 */
1268 	if (!req->context)
1269 		return;
1270 
1271 	cdev = req->context;
1272 
1273 	if (cdev->req == req)
1274 		cdev->setup_pending = false;
1275 	else if (cdev->os_desc_req == req)
1276 		cdev->os_desc_pending = false;
1277 	else
1278 		WARN(1, "unknown request %p\n", req);
1279 }
1280 
1281 static int composite_ep0_queue(struct usb_composite_dev *cdev,
1282 		struct usb_request *req, gfp_t gfp_flags)
1283 {
1284 	int ret;
1285 
1286 	ret = usb_ep_queue(cdev->gadget->ep0, req, gfp_flags);
1287 	if (ret == 0) {
1288 		if (cdev->req == req)
1289 			cdev->setup_pending = true;
1290 		else if (cdev->os_desc_req == req)
1291 			cdev->os_desc_pending = true;
1292 		else
1293 			WARN(1, "unknown request %p\n", req);
1294 	}
1295 
1296 	return ret;
1297 }
1298 
1299 static int count_ext_compat(struct usb_configuration *c)
1300 {
1301 	int i, res;
1302 
1303 	res = 0;
1304 	for (i = 0; i < c->next_interface_id; ++i) {
1305 		struct usb_function *f;
1306 		int j;
1307 
1308 		f = c->interface[i];
1309 		for (j = 0; j < f->os_desc_n; ++j) {
1310 			struct usb_os_desc *d;
1311 
1312 			if (i != f->os_desc_table[j].if_id)
1313 				continue;
1314 			d = f->os_desc_table[j].os_desc;
1315 			if (d && d->ext_compat_id)
1316 				++res;
1317 		}
1318 	}
1319 	BUG_ON(res > 255);
1320 	return res;
1321 }
1322 
1323 static void fill_ext_compat(struct usb_configuration *c, u8 *buf)
1324 {
1325 	int i, count;
1326 
1327 	count = 16;
1328 	for (i = 0; i < c->next_interface_id; ++i) {
1329 		struct usb_function *f;
1330 		int j;
1331 
1332 		f = c->interface[i];
1333 		for (j = 0; j < f->os_desc_n; ++j) {
1334 			struct usb_os_desc *d;
1335 
1336 			if (i != f->os_desc_table[j].if_id)
1337 				continue;
1338 			d = f->os_desc_table[j].os_desc;
1339 			if (d && d->ext_compat_id) {
1340 				*buf++ = i;
1341 				*buf++ = 0x01;
1342 				memcpy(buf, d->ext_compat_id, 16);
1343 				buf += 22;
1344 			} else {
1345 				++buf;
1346 				*buf = 0x01;
1347 				buf += 23;
1348 			}
1349 			count += 24;
1350 			if (count >= 4096)
1351 				return;
1352 		}
1353 	}
1354 }
1355 
1356 static int count_ext_prop(struct usb_configuration *c, int interface)
1357 {
1358 	struct usb_function *f;
1359 	int j;
1360 
1361 	f = c->interface[interface];
1362 	for (j = 0; j < f->os_desc_n; ++j) {
1363 		struct usb_os_desc *d;
1364 
1365 		if (interface != f->os_desc_table[j].if_id)
1366 			continue;
1367 		d = f->os_desc_table[j].os_desc;
1368 		if (d && d->ext_compat_id)
1369 			return d->ext_prop_count;
1370 	}
1371 	return 0;
1372 }
1373 
1374 static int len_ext_prop(struct usb_configuration *c, int interface)
1375 {
1376 	struct usb_function *f;
1377 	struct usb_os_desc *d;
1378 	int j, res;
1379 
1380 	res = 10; /* header length */
1381 	f = c->interface[interface];
1382 	for (j = 0; j < f->os_desc_n; ++j) {
1383 		if (interface != f->os_desc_table[j].if_id)
1384 			continue;
1385 		d = f->os_desc_table[j].os_desc;
1386 		if (d)
1387 			return min(res + d->ext_prop_len, 4096);
1388 	}
1389 	return res;
1390 }
1391 
1392 static int fill_ext_prop(struct usb_configuration *c, int interface, u8 *buf)
1393 {
1394 	struct usb_function *f;
1395 	struct usb_os_desc *d;
1396 	struct usb_os_desc_ext_prop *ext_prop;
1397 	int j, count, n, ret;
1398 	u8 *start = buf;
1399 
1400 	f = c->interface[interface];
1401 	for (j = 0; j < f->os_desc_n; ++j) {
1402 		if (interface != f->os_desc_table[j].if_id)
1403 			continue;
1404 		d = f->os_desc_table[j].os_desc;
1405 		if (d)
1406 			list_for_each_entry(ext_prop, &d->ext_prop, entry) {
1407 				/* 4kB minus header length */
1408 				n = buf - start;
1409 				if (n >= 4086)
1410 					return 0;
1411 
1412 				count = ext_prop->data_len +
1413 					ext_prop->name_len + 14;
1414 				if (count > 4086 - n)
1415 					return -EINVAL;
1416 				usb_ext_prop_put_size(buf, count);
1417 				usb_ext_prop_put_type(buf, ext_prop->type);
1418 				ret = usb_ext_prop_put_name(buf, ext_prop->name,
1419 							    ext_prop->name_len);
1420 				if (ret < 0)
1421 					return ret;
1422 				switch (ext_prop->type) {
1423 				case USB_EXT_PROP_UNICODE:
1424 				case USB_EXT_PROP_UNICODE_ENV:
1425 				case USB_EXT_PROP_UNICODE_LINK:
1426 					usb_ext_prop_put_unicode(buf, ret,
1427 							 ext_prop->data,
1428 							 ext_prop->data_len);
1429 					break;
1430 				case USB_EXT_PROP_BINARY:
1431 					usb_ext_prop_put_binary(buf, ret,
1432 							ext_prop->data,
1433 							ext_prop->data_len);
1434 					break;
1435 				case USB_EXT_PROP_LE32:
1436 					/* not implemented */
1437 				case USB_EXT_PROP_BE32:
1438 					/* not implemented */
1439 				default:
1440 					return -EINVAL;
1441 				}
1442 				buf += count;
1443 			}
1444 	}
1445 
1446 	return 0;
1447 }
1448 
1449 /*
1450  * The setup() callback implements all the ep0 functionality that's
1451  * not handled lower down, in hardware or the hardware driver(like
1452  * device and endpoint feature flags, and their status).  It's all
1453  * housekeeping for the gadget function we're implementing.  Most of
1454  * the work is in config and function specific setup.
1455  */
1456 int
1457 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1458 {
1459 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1460 	struct usb_request		*req = cdev->req;
1461 	int				value = -EOPNOTSUPP;
1462 	int				status = 0;
1463 	u16				w_index = le16_to_cpu(ctrl->wIndex);
1464 	u8				intf = w_index & 0xFF;
1465 	u16				w_value = le16_to_cpu(ctrl->wValue);
1466 	u16				w_length = le16_to_cpu(ctrl->wLength);
1467 	struct usb_function		*f = NULL;
1468 	u8				endp;
1469 
1470 	/* partial re-init of the response message; the function or the
1471 	 * gadget might need to intercept e.g. a control-OUT completion
1472 	 * when we delegate to it.
1473 	 */
1474 	req->zero = 0;
1475 	req->context = cdev;
1476 	req->complete = composite_setup_complete;
1477 	req->length = 0;
1478 	gadget->ep0->driver_data = cdev;
1479 
1480 	/*
1481 	 * Don't let non-standard requests match any of the cases below
1482 	 * by accident.
1483 	 */
1484 	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
1485 		goto unknown;
1486 
1487 	switch (ctrl->bRequest) {
1488 
1489 	/* we handle all standard USB descriptors */
1490 	case USB_REQ_GET_DESCRIPTOR:
1491 		if (ctrl->bRequestType != USB_DIR_IN)
1492 			goto unknown;
1493 		switch (w_value >> 8) {
1494 
1495 		case USB_DT_DEVICE:
1496 			cdev->desc.bNumConfigurations =
1497 				count_configs(cdev, USB_DT_DEVICE);
1498 			cdev->desc.bMaxPacketSize0 =
1499 				cdev->gadget->ep0->maxpacket;
1500 			if (gadget_is_superspeed(gadget)) {
1501 				if (gadget->speed >= USB_SPEED_SUPER) {
1502 					cdev->desc.bcdUSB = cpu_to_le16(0x0300);
1503 					cdev->desc.bMaxPacketSize0 = 9;
1504 				} else {
1505 					cdev->desc.bcdUSB = cpu_to_le16(0x0210);
1506 				}
1507 			} else {
1508 				cdev->desc.bcdUSB = cpu_to_le16(0x0200);
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