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