[go: nahoru, domu]

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