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