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