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