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