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