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