• 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  * U-Boot porting: Lukasz Majewski <l.majewski@samsung.com>
7  */
8 #undef DEBUG
9 
10 #include <linux/bitops.h>
11 #include <linux/usb/composite.h>
12 
13 #define USB_BUFSIZ	4096
14 
15 /* Helper type for accessing packed u16 pointers */
16 typedef struct { __le16 val; } __packed __le16_packed;
17 
18 static struct usb_composite_driver *composite;
19 
le16_add_cpu_packed(__le16_packed * var,u16 val)20 static inline void le16_add_cpu_packed(__le16_packed *var, u16 val)
21 {
22 	var->val = cpu_to_le16(le16_to_cpu(var->val) + val);
23 }
24 
25 /**
26  * usb_add_function() - add a function to a configuration
27  * @config: the configuration
28  * @function: the function being added
29  * Context: single threaded during gadget setup
30  *
31  * After initialization, each configuration must have one or more
32  * functions added to it.  Adding a function involves calling its @bind()
33  * method to allocate resources such as interface and string identifiers
34  * and endpoints.
35  *
36  * This function returns the value of the function's bind(), which is
37  * zero for success else a negative errno value.
38  */
usb_add_function(struct usb_configuration * config,struct usb_function * function)39 int usb_add_function(struct usb_configuration *config,
40 		struct usb_function *function)
41 {
42 	int	value = -EINVAL;
43 
44 	debug("adding '%s'/%p to config '%s'/%p\n",
45 			function->name, function,
46 			config->label, config);
47 
48 	if (!function->set_alt || !function->disable)
49 		goto done;
50 
51 	function->config = config;
52 	list_add_tail(&function->list, &config->functions);
53 
54 	if (function->bind) {
55 		value = function->bind(config, function);
56 		if (value < 0) {
57 			list_del(&function->list);
58 			function->config = NULL;
59 		}
60 	} else
61 		value = 0;
62 
63 	if (!config->fullspeed && function->descriptors)
64 		config->fullspeed = 1;
65 	if (!config->highspeed && function->hs_descriptors)
66 		config->highspeed = 1;
67 
68 done:
69 	if (value)
70 		debug("adding '%s'/%p --> %d\n",
71 				function->name, function, value);
72 	return value;
73 }
74 
75 /**
76  * usb_function_deactivate - prevent function and gadget enumeration
77  * @function: the function that isn't yet ready to respond
78  *
79  * Blocks response of the gadget driver to host enumeration by
80  * preventing the data line pullup from being activated.  This is
81  * normally called during @bind() processing to change from the
82  * initial "ready to respond" state, or when a required resource
83  * becomes available.
84  *
85  * For example, drivers that serve as a passthrough to a userspace
86  * daemon can block enumeration unless that daemon (such as an OBEX,
87  * MTP, or print server) is ready to handle host requests.
88  *
89  * Not all systems support software control of their USB peripheral
90  * data pullups.
91  *
92  * Returns zero on success, else negative errno.
93  */
usb_function_deactivate(struct usb_function * function)94 int usb_function_deactivate(struct usb_function *function)
95 {
96 	struct usb_composite_dev	*cdev = function->config->cdev;
97 	int				status = 0;
98 
99 	if (cdev->deactivations == 0)
100 		status = usb_gadget_disconnect(cdev->gadget);
101 	if (status == 0)
102 		cdev->deactivations++;
103 
104 	return status;
105 }
106 
107 /**
108  * usb_function_activate - allow function and gadget enumeration
109  * @function: function on which usb_function_activate() was called
110  *
111  * Reverses effect of usb_function_deactivate().  If no more functions
112  * are delaying their activation, the gadget driver will respond to
113  * host enumeration procedures.
114  *
115  * Returns zero on success, else negative errno.
116  */
usb_function_activate(struct usb_function * function)117 int usb_function_activate(struct usb_function *function)
118 {
119 	struct usb_composite_dev	*cdev = function->config->cdev;
120 	int				status = 0;
121 
122 	if (cdev->deactivations == 0)
123 		status = -EINVAL;
124 	else {
125 		cdev->deactivations--;
126 		if (cdev->deactivations == 0)
127 			status = usb_gadget_connect(cdev->gadget);
128 	}
129 
130 	return status;
131 }
132 
133 /**
134  * usb_interface_id() - allocate an unused interface ID
135  * @config: configuration associated with the interface
136  * @function: function handling the interface
137  * Context: single threaded during gadget setup
138  *
139  * usb_interface_id() is called from usb_function.bind() callbacks to
140  * allocate new interface IDs.  The function driver will then store that
141  * ID in interface, association, CDC union, and other descriptors.  It
142  * will also handle any control requests targetted at that interface,
143  * particularly changing its altsetting via set_alt().  There may
144  * also be class-specific or vendor-specific requests to handle.
145  *
146  * All interface identifier should be allocated using this routine, to
147  * ensure that for example different functions don't wrongly assign
148  * different meanings to the same identifier.  Note that since interface
149  * identifers are configuration-specific, functions used in more than
150  * one configuration (or more than once in a given configuration) need
151  * multiple versions of the relevant descriptors.
152  *
153  * Returns the interface ID which was allocated; or -ENODEV if no
154  * more interface IDs can be allocated.
155  */
usb_interface_id(struct usb_configuration * config,struct usb_function * function)156 int usb_interface_id(struct usb_configuration *config,
157 		struct usb_function *function)
158 {
159 	unsigned char id = config->next_interface_id;
160 
161 	if (id < MAX_CONFIG_INTERFACES) {
162 		config->interface[id] = function;
163 		config->next_interface_id = id + 1;
164 		return id;
165 	}
166 	return -ENODEV;
167 }
168 
config_buf(struct usb_configuration * config,enum usb_device_speed speed,void * buf,u8 type)169 static int config_buf(struct usb_configuration *config,
170 		enum usb_device_speed speed, void *buf, u8 type)
171 {
172 	int				len = USB_BUFSIZ - USB_DT_CONFIG_SIZE;
173 	void				*next = buf + USB_DT_CONFIG_SIZE;
174 	struct usb_descriptor_header    **descriptors;
175 	struct usb_config_descriptor	*c;
176 	int				status;
177 	struct usb_function		*f;
178 
179 	/* write the config descriptor */
180 	c = buf;
181 	c->bLength = USB_DT_CONFIG_SIZE;
182 	c->bDescriptorType = type;
183 
184 	c->bNumInterfaces = config->next_interface_id;
185 	c->bConfigurationValue = config->bConfigurationValue;
186 	c->iConfiguration = config->iConfiguration;
187 	c->bmAttributes = USB_CONFIG_ATT_ONE | config->bmAttributes;
188 	c->bMaxPower = config->bMaxPower ? : (CONFIG_USB_GADGET_VBUS_DRAW / 2);
189 
190 	/* There may be e.g. OTG descriptors */
191 	if (config->descriptors) {
192 		status = usb_descriptor_fillbuf(next, len,
193 				config->descriptors);
194 		if (status < 0)
195 			return status;
196 		len -= status;
197 		next += status;
198 	}
199 
200 	/* add each function's descriptors */
201 	list_for_each_entry(f, &config->functions, list) {
202 		if (speed == USB_SPEED_HIGH)
203 			descriptors = f->hs_descriptors;
204 		else
205 			descriptors = f->descriptors;
206 		if (!descriptors)
207 			continue;
208 		status = usb_descriptor_fillbuf(next, len,
209 			(const struct usb_descriptor_header **) descriptors);
210 		if (status < 0)
211 			return status;
212 		len -= status;
213 		next += status;
214 	}
215 
216 	len = next - buf;
217 	c->wTotalLength = cpu_to_le16(len);
218 	return len;
219 }
220 
config_desc(struct usb_composite_dev * cdev,unsigned w_value)221 static int config_desc(struct usb_composite_dev *cdev, unsigned w_value)
222 {
223 	enum usb_device_speed		speed = USB_SPEED_UNKNOWN;
224 	struct usb_gadget		*gadget = cdev->gadget;
225 	u8				type = w_value >> 8;
226 	int                             hs = 0;
227 	struct usb_configuration	*c;
228 
229 	if (gadget_is_dualspeed(gadget)) {
230 		if (gadget->speed == USB_SPEED_HIGH)
231 			hs = 1;
232 		if (type == USB_DT_OTHER_SPEED_CONFIG)
233 			hs = !hs;
234 		if (hs)
235 			speed = USB_SPEED_HIGH;
236 	}
237 
238 	w_value &= 0xff;
239 	list_for_each_entry(c, &cdev->configs, list) {
240 		if (speed == USB_SPEED_HIGH) {
241 			if (!c->highspeed)
242 				continue;
243 		} else {
244 			if (!c->fullspeed)
245 				continue;
246 		}
247 		if (w_value == 0)
248 			return config_buf(c, speed, cdev->req->buf, type);
249 		w_value--;
250 	}
251 	return -EINVAL;
252 }
253 
count_configs(struct usb_composite_dev * cdev,unsigned type)254 static int count_configs(struct usb_composite_dev *cdev, unsigned type)
255 {
256 	struct usb_gadget		*gadget = cdev->gadget;
257 	unsigned			count = 0;
258 	int				hs = 0;
259 	struct usb_configuration	*c;
260 
261 	if (gadget_is_dualspeed(gadget)) {
262 		if (gadget->speed == USB_SPEED_HIGH)
263 			hs = 1;
264 		if (type == USB_DT_DEVICE_QUALIFIER)
265 			hs = !hs;
266 	}
267 	list_for_each_entry(c, &cdev->configs, list) {
268 		/* ignore configs that won't work at this speed */
269 		if (hs) {
270 			if (!c->highspeed)
271 				continue;
272 		} else {
273 			if (!c->fullspeed)
274 				continue;
275 		}
276 		count++;
277 	}
278 	return count;
279 }
280 
device_qual(struct usb_composite_dev * cdev)281 static void device_qual(struct usb_composite_dev *cdev)
282 {
283 	struct usb_qualifier_descriptor	*qual = cdev->req->buf;
284 
285 	qual->bLength = sizeof(*qual);
286 	qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER;
287 	/* POLICY: same bcdUSB and device type info at both speeds */
288 	qual->bcdUSB = cdev->desc.bcdUSB;
289 	qual->bDeviceClass = cdev->desc.bDeviceClass;
290 	qual->bDeviceSubClass = cdev->desc.bDeviceSubClass;
291 	qual->bDeviceProtocol = cdev->desc.bDeviceProtocol;
292 	/* ASSUME same EP0 fifo size at both speeds */
293 	qual->bMaxPacketSize0 = cdev->gadget->ep0->maxpacket;
294 	qual->bNumConfigurations = count_configs(cdev, USB_DT_DEVICE_QUALIFIER);
295 	qual->bRESERVED = 0;
296 }
297 
reset_config(struct usb_composite_dev * cdev)298 static void reset_config(struct usb_composite_dev *cdev)
299 {
300 	struct usb_function		*f;
301 
302 	debug("%s:\n", __func__);
303 
304 	list_for_each_entry(f, &cdev->config->functions, list) {
305 		if (f->disable)
306 			f->disable(f);
307 
308 		bitmap_zero(f->endpoints, 32);
309 	}
310 	cdev->config = NULL;
311 }
312 
set_config(struct usb_composite_dev * cdev,const struct usb_ctrlrequest * ctrl,unsigned number)313 static int set_config(struct usb_composite_dev *cdev,
314 		const struct usb_ctrlrequest *ctrl, unsigned number)
315 {
316 	struct usb_gadget	*gadget = cdev->gadget;
317 	unsigned		power = gadget_is_otg(gadget) ? 8 : 100;
318 	struct usb_descriptor_header **descriptors;
319 	int			result = -EINVAL;
320 	struct usb_endpoint_descriptor *ep;
321 	struct usb_configuration *c = NULL;
322 	int                     addr;
323 	int			tmp;
324 	struct usb_function	*f;
325 
326 	if (cdev->config)
327 		reset_config(cdev);
328 
329 	if (number) {
330 		list_for_each_entry(c, &cdev->configs, list) {
331 			if (c->bConfigurationValue == number) {
332 				result = 0;
333 				break;
334 			}
335 		}
336 		if (result < 0)
337 			goto done;
338 	} else
339 		result = 0;
340 
341 	debug("%s: %s speed config #%d: %s\n", __func__,
342 	     ({ char *speed;
343 		     switch (gadget->speed) {
344 		     case USB_SPEED_LOW:
345 			     speed = "low";
346 			     break;
347 		     case USB_SPEED_FULL:
348 			     speed = "full";
349 			     break;
350 		     case USB_SPEED_HIGH:
351 			     speed = "high";
352 			     break;
353 		     default:
354 			     speed = "?";
355 			     break;
356 		     };
357 		     speed;
358 	     }), number, c ? c->label : "unconfigured");
359 
360 	if (!c)
361 		goto done;
362 
363 	cdev->config = c;
364 
365 	/* Initialize all interfaces by setting them to altsetting zero. */
366 	for (tmp = 0; tmp < MAX_CONFIG_INTERFACES; tmp++) {
367 		f = c->interface[tmp];
368 		if (!f)
369 			break;
370 
371 		/*
372 		 * Record which endpoints are used by the function. This is used
373 		 * to dispatch control requests targeted at that endpoint to the
374 		 * function's setup callback instead of the current
375 		 * configuration's setup callback.
376 		 */
377 		if (gadget->speed == USB_SPEED_HIGH)
378 			descriptors = f->hs_descriptors;
379 		else
380 			descriptors = f->descriptors;
381 
382 		for (; *descriptors; ++descriptors) {
383 			if ((*descriptors)->bDescriptorType != USB_DT_ENDPOINT)
384 				continue;
385 
386 			ep = (struct usb_endpoint_descriptor *)*descriptors;
387 			addr = ((ep->bEndpointAddress & 0x80) >> 3)
388 			     |	(ep->bEndpointAddress & 0x0f);
389 			generic_set_bit(addr, f->endpoints);
390 		}
391 
392 		result = f->set_alt(f, tmp, 0);
393 		if (result < 0) {
394 			debug("interface %d (%s/%p) alt 0 --> %d\n",
395 					tmp, f->name, f, result);
396 
397 			reset_config(cdev);
398 			goto done;
399 		}
400 	}
401 
402 	/* when we return, be sure our power usage is valid */
403 	power = c->bMaxPower ? (2 * c->bMaxPower) : CONFIG_USB_GADGET_VBUS_DRAW;
404 done:
405 	usb_gadget_vbus_draw(gadget, power);
406 	return result;
407 }
408 
409 /**
410  * usb_add_config() - add a configuration to a device.
411  * @cdev: wraps the USB gadget
412  * @config: the configuration, with bConfigurationValue assigned
413  * Context: single threaded during gadget setup
414  *
415  * One of the main tasks of a composite driver's bind() routine is to
416  * add each of the configurations it supports, using this routine.
417  *
418  * This function returns the value of the configuration's bind(), which
419  * is zero for success else a negative errno value.  Binding configurations
420  * assigns global resources including string IDs, and per-configuration
421  * resources such as interface IDs and endpoints.
422  */
usb_add_config(struct usb_composite_dev * cdev,struct usb_configuration * config)423 int usb_add_config(struct usb_composite_dev *cdev,
424 		struct usb_configuration *config)
425 {
426 	int				status = -EINVAL;
427 	struct usb_configuration	*c;
428 	struct usb_function		*f;
429 	unsigned int			i;
430 
431 	debug("%s: adding config #%u '%s'/%p\n", __func__,
432 			config->bConfigurationValue,
433 			config->label, config);
434 
435 	if (!config->bConfigurationValue || !config->bind)
436 		goto done;
437 
438 	/* Prevent duplicate configuration identifiers */
439 	list_for_each_entry(c, &cdev->configs, list) {
440 		if (c->bConfigurationValue == config->bConfigurationValue) {
441 			status = -EBUSY;
442 			goto done;
443 		}
444 	}
445 
446 	config->cdev = cdev;
447 	list_add_tail(&config->list, &cdev->configs);
448 
449 	INIT_LIST_HEAD(&config->functions);
450 	config->next_interface_id = 0;
451 
452 	status = config->bind(config);
453 	if (status < 0) {
454 		list_del(&config->list);
455 		config->cdev = NULL;
456 	} else {
457 		debug("cfg %d/%p speeds:%s%s\n",
458 			config->bConfigurationValue, config,
459 			config->highspeed ? " high" : "",
460 			config->fullspeed
461 				? (gadget_is_dualspeed(cdev->gadget)
462 					? " full"
463 					: " full/low")
464 				: "");
465 
466 		for (i = 0; i < MAX_CONFIG_INTERFACES; i++) {
467 			f = config->interface[i];
468 			if (!f)
469 				continue;
470 			debug("%s: interface %d = %s/%p\n",
471 			      __func__, i, f->name, f);
472 		}
473 	}
474 
475 	usb_ep_autoconfig_reset(cdev->gadget);
476 
477 done:
478 	if (status)
479 		debug("added config '%s'/%u --> %d\n", config->label,
480 				config->bConfigurationValue, status);
481 	return status;
482 }
483 
484 /*
485  * We support strings in multiple languages ... string descriptor zero
486  * says which languages are supported.	The typical case will be that
487  * only one language (probably English) is used, with I18N handled on
488  * the host side.
489  */
490 
collect_langs(struct usb_gadget_strings ** sp,void * buf)491 static void collect_langs(struct usb_gadget_strings **sp, void *buf)
492 {
493 	const struct usb_gadget_strings	*s;
494 	u16				language;
495 	__le16_packed			*tmp;
496 	__le16_packed			*end = (buf + 252);
497 
498 	while (*sp) {
499 		s = *sp;
500 		language = cpu_to_le16(s->language);
501 		for (tmp = buf; tmp->val && tmp < end; tmp++) {
502 			if (tmp->val == language)
503 				goto repeat;
504 		}
505 		tmp->val = language;
506 repeat:
507 		sp++;
508 	}
509 }
510 
lookup_string(struct usb_gadget_strings ** sp,void * buf,u16 language,int id)511 static int lookup_string(
512 	struct usb_gadget_strings	**sp,
513 	void				*buf,
514 	u16				language,
515 	int				id
516 )
517 {
518 	int				value;
519 	struct usb_gadget_strings	*s;
520 
521 	while (*sp) {
522 		s = *sp++;
523 		if (s->language != language)
524 			continue;
525 		value = usb_gadget_get_string(s, id, buf);
526 		if (value > 0)
527 			return value;
528 	}
529 	return -EINVAL;
530 }
531 
get_string(struct usb_composite_dev * cdev,void * buf,u16 language,int id)532 static int get_string(struct usb_composite_dev *cdev,
533 		void *buf, u16 language, int id)
534 {
535 	struct usb_string_descriptor	*s = buf;
536 	struct usb_gadget_strings	**sp;
537 	int				len;
538 	struct usb_configuration	*c;
539 	struct usb_function		*f;
540 
541 	/*
542 	 * Yes, not only is USB's I18N support probably more than most
543 	 * folk will ever care about ... also, it's all supported here.
544 	 * (Except for UTF8 support for Unicode's "Astral Planes".)
545 	 */
546 
547 	/* 0 == report all available language codes */
548 	if (id == 0) {
549 		memset(s, 0, 256);
550 		s->bDescriptorType = USB_DT_STRING;
551 
552 		sp = composite->strings;
553 		if (sp)
554 			collect_langs(sp, s->wData);
555 
556 		list_for_each_entry(c, &cdev->configs, list) {
557 			sp = c->strings;
558 			if (sp)
559 				collect_langs(sp, s->wData);
560 
561 			list_for_each_entry(f, &c->functions, list) {
562 				sp = f->strings;
563 				if (sp)
564 					collect_langs(sp, s->wData);
565 			}
566 		}
567 
568 		for (len = 0; len <= 126 && s->wData[len]; len++)
569 			continue;
570 		if (!len)
571 			return -EINVAL;
572 
573 		s->bLength = 2 * (len + 1);
574 		return s->bLength;
575 	}
576 
577 	/*
578 	 * Otherwise, look up and return a specified string.  String IDs
579 	 * are device-scoped, so we look up each string table we're told
580 	 * about.  These lookups are infrequent; simpler-is-better here.
581 	 */
582 	if (composite->strings) {
583 		len = lookup_string(composite->strings, buf, language, id);
584 		if (len > 0)
585 			return len;
586 	}
587 	list_for_each_entry(c, &cdev->configs, list) {
588 		if (c->strings) {
589 			len = lookup_string(c->strings, buf, language, id);
590 			if (len > 0)
591 				return len;
592 		}
593 		list_for_each_entry(f, &c->functions, list) {
594 			if (!f->strings)
595 				continue;
596 			len = lookup_string(f->strings, buf, language, id);
597 			if (len > 0)
598 				return len;
599 		}
600 	}
601 	return -EINVAL;
602 }
603 
604 /**
605  * usb_string_id() - allocate an unused string ID
606  * @cdev: the device whose string descriptor IDs are being allocated
607  * Context: single threaded during gadget setup
608  *
609  * @usb_string_id() is called from bind() callbacks to allocate
610  * string IDs.	Drivers for functions, configurations, or gadgets will
611  * then store that ID in the appropriate descriptors and string table.
612  *
613  * All string identifier should be allocated using this,
614  * @usb_string_ids_tab() or @usb_string_ids_n() routine, to ensure
615  * that for example different functions don't wrongly assign different
616  * meanings to the same identifier.
617  */
usb_string_id(struct usb_composite_dev * cdev)618 int usb_string_id(struct usb_composite_dev *cdev)
619 {
620 	if (cdev->next_string_id < 254) {
621 		/*
622 		 * string id 0 is reserved by USB spec for list of
623 		 * supported languages
624 		 * 255 reserved as well? -- mina86
625 		 */
626 		cdev->next_string_id++;
627 		return cdev->next_string_id;
628 	}
629 	return -ENODEV;
630 }
631 
632 /**
633  * usb_string_ids() - allocate unused string IDs in batch
634  * @cdev: the device whose string descriptor IDs are being allocated
635  * @str: an array of usb_string objects to assign numbers to
636  * Context: single threaded during gadget setup
637  *
638  * @usb_string_ids() is called from bind() callbacks to allocate
639  * string IDs.	Drivers for functions, configurations, or gadgets will
640  * then copy IDs from the string table to the appropriate descriptors
641  * and string table for other languages.
642  *
643  * All string identifier should be allocated using this,
644  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
645  * example different functions don't wrongly assign different meanings
646  * to the same identifier.
647  */
usb_string_ids_tab(struct usb_composite_dev * cdev,struct usb_string * str)648 int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)
649 {
650 	u8 next = cdev->next_string_id;
651 
652 	for (; str->s; ++str) {
653 		if (next >= 254)
654 			return -ENODEV;
655 		str->id = ++next;
656 	}
657 
658 	cdev->next_string_id = next;
659 
660 	return 0;
661 }
662 
663 /**
664  * usb_string_ids_n() - allocate unused string IDs in batch
665  * @c: the device whose string descriptor IDs are being allocated
666  * @n: number of string IDs to allocate
667  * Context: single threaded during gadget setup
668  *
669  * Returns the first requested ID.  This ID and next @n-1 IDs are now
670  * valid IDs.  At least provided that @n is non-zero because if it
671  * is, returns last requested ID which is now very useful information.
672  *
673  * @usb_string_ids_n() is called from bind() callbacks to allocate
674  * string IDs.	Drivers for functions, configurations, or gadgets will
675  * then store that ID in the appropriate descriptors and string table.
676  *
677  * All string identifier should be allocated using this,
678  * @usb_string_id() or @usb_string_ids_n() routine, to ensure that for
679  * example different functions don't wrongly assign different meanings
680  * to the same identifier.
681  */
usb_string_ids_n(struct usb_composite_dev * c,unsigned n)682 int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)
683 {
684 	u8 next = c->next_string_id;
685 
686 	if (n > 254 || next + n > 254)
687 		return -ENODEV;
688 
689 	c->next_string_id += n;
690 	return next + 1;
691 }
692 
composite_setup_complete(struct usb_ep * ep,struct usb_request * req)693 static void composite_setup_complete(struct usb_ep *ep, struct usb_request *req)
694 {
695 	if (req->status || req->actual != req->length)
696 		debug("%s: setup complete --> %d, %d/%d\n", __func__,
697 				req->status, req->actual, req->length);
698 }
699 
bos_desc(struct usb_composite_dev * cdev)700 static int bos_desc(struct usb_composite_dev *cdev)
701 {
702 	struct usb_ext_cap_descriptor   *usb_ext;
703 	struct usb_bos_descriptor       *bos = cdev->req->buf;
704 
705 	bos->bLength = USB_DT_BOS_SIZE;
706 	bos->bDescriptorType = USB_DT_BOS;
707 
708 	bos->wTotalLength = cpu_to_le16(USB_DT_BOS_SIZE);
709 	bos->bNumDeviceCaps = 0;
710 
711 	/*
712 	 * A SuperSpeed device shall include the USB2.0 extension descriptor
713 	 * and shall support LPM when operating in USB2.0 HS mode.
714 	 */
715 	usb_ext = cdev->req->buf + le16_to_cpu(bos->wTotalLength);
716 	bos->bNumDeviceCaps++;
717 	le16_add_cpu_packed((__le16_packed *)&bos->wTotalLength,
718 			    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 =
723 		cpu_to_le32(USB_LPM_SUPPORT | USB_BESL_SUPPORT);
724 
725 	/*
726 	 * The Superspeed USB Capability descriptor shall be implemented
727 	 * by all 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_packed((__le16_packed *)&bos->wTotalLength,
735 				    USB_DT_USB_SS_CAP_SIZE);
736 		ss_cap->bLength = USB_DT_USB_SS_CAP_SIZE;
737 		ss_cap->bDescriptorType = USB_DT_DEVICE_CAPABILITY;
738 		ss_cap->bDevCapabilityType = USB_SS_CAP_TYPE;
739 		ss_cap->bmAttributes = 0; /* LTM is not supported yet */
740 		ss_cap->wSpeedSupported =
741 			cpu_to_le16(USB_LOW_SPEED_OPERATION |
742 				    USB_FULL_SPEED_OPERATION |
743 				    USB_HIGH_SPEED_OPERATION |
744 				    USB_5GBPS_OPERATION);
745 		ss_cap->bFunctionalitySupport = USB_LOW_SPEED_OPERATION;
746 		ss_cap->bU1devExitLat = USB_DEFAULT_U1_DEV_EXIT_LAT;
747 		ss_cap->bU2DevExitLat =
748 			cpu_to_le16(USB_DEFAULT_U2_DEV_EXIT_LAT);
749 	}
750 	return le16_to_cpu(bos->wTotalLength);
751 }
752 
753 /*
754  * The setup() callback implements all the ep0 functionality that's
755  * not handled lower down, in hardware or the hardware driver(like
756  * device and endpoint feature flags, and their status).  It's all
757  * housekeeping for the gadget function we're implementing.  Most of
758  * the work is in config and function specific setup.
759  */
760 static int
composite_setup(struct usb_gadget * gadget,const struct usb_ctrlrequest * ctrl)761 composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
762 {
763 	u16				w_length = le16_to_cpu(ctrl->wLength);
764 	u16				w_index = le16_to_cpu(ctrl->wIndex);
765 	u16				w_value = le16_to_cpu(ctrl->wValue);
766 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
767 	u8				intf = w_index & 0xFF;
768 	int				value = -EOPNOTSUPP;
769 	struct usb_request		*req = cdev->req;
770 	struct usb_function		*f = NULL;
771 	int				standard;
772 	u8				endp;
773 	struct usb_configuration	*c;
774 
775 	/*
776 	 * partial re-init of the response message; the function or the
777 	 * gadget might need to intercept e.g. a control-OUT completion
778 	 * when we delegate to it.
779 	 */
780 	req->zero = 0;
781 	req->complete = composite_setup_complete;
782 	req->length = USB_BUFSIZ;
783 	gadget->ep0->driver_data = cdev;
784 	standard = (ctrl->bRequestType & USB_TYPE_MASK)
785 						== USB_TYPE_STANDARD;
786 	if (!standard)
787 		goto unknown;
788 
789 	switch (ctrl->bRequest) {
790 
791 	/* we handle all standard USB descriptors */
792 	case USB_REQ_GET_DESCRIPTOR:
793 		if (ctrl->bRequestType != USB_DIR_IN)
794 			goto unknown;
795 		switch (w_value >> 8) {
796 
797 		case USB_DT_DEVICE:
798 			cdev->desc.bNumConfigurations =
799 				count_configs(cdev, USB_DT_DEVICE);
800 
801 			/*
802 			 * If the speed is Super speed, then the supported
803 			 * max packet size is 512 and it should be sent as
804 			 * exponent of 2. So, 9(2^9=512) should be filled in
805 			 * bMaxPacketSize0. Also fill USB version as 3.0
806 			 * if speed is Super speed.
807 			 */
808 			if (cdev->gadget->speed == USB_SPEED_SUPER) {
809 				cdev->desc.bMaxPacketSize0 = 9;
810 				cdev->desc.bcdUSB = cpu_to_le16(0x0300);
811 			} else {
812 				cdev->desc.bMaxPacketSize0 =
813 					cdev->gadget->ep0->maxpacket;
814 			}
815 			value = min(w_length, (u16) sizeof cdev->desc);
816 			memcpy(req->buf, &cdev->desc, value);
817 			break;
818 		case USB_DT_DEVICE_QUALIFIER:
819 			if (!gadget_is_dualspeed(gadget))
820 				break;
821 			device_qual(cdev);
822 			value = min_t(int, w_length,
823 				      sizeof(struct usb_qualifier_descriptor));
824 			break;
825 		case USB_DT_OTHER_SPEED_CONFIG:
826 			if (!gadget_is_dualspeed(gadget))
827 				break;
828 
829 		case USB_DT_CONFIG:
830 			value = config_desc(cdev, w_value);
831 			if (value >= 0)
832 				value = min(w_length, (u16) value);
833 			break;
834 		case USB_DT_STRING:
835 			value = get_string(cdev, req->buf,
836 					w_index, w_value & 0xff);
837 			if (value >= 0)
838 				value = min(w_length, (u16) value);
839 			break;
840 		case USB_DT_BOS:
841 			if (gadget_is_superspeed(cdev->gadget))
842 				value = bos_desc(cdev);
843 			if (value >= 0)
844 				value = min(w_length, (u16)value);
845 			break;
846 		default:
847 			goto unknown;
848 		}
849 		break;
850 
851 	/* any number of configs can work */
852 	case USB_REQ_SET_CONFIGURATION:
853 		if (ctrl->bRequestType != 0)
854 			goto unknown;
855 		if (gadget_is_otg(gadget)) {
856 			if (gadget->a_hnp_support)
857 				debug("HNP available\n");
858 			else if (gadget->a_alt_hnp_support)
859 				debug("HNP on another port\n");
860 			else
861 				debug("HNP inactive\n");
862 		}
863 
864 		value = set_config(cdev, ctrl, w_value);
865 		break;
866 	case USB_REQ_GET_CONFIGURATION:
867 		if (ctrl->bRequestType != USB_DIR_IN)
868 			goto unknown;
869 		if (cdev->config)
870 			*(u8 *)req->buf = cdev->config->bConfigurationValue;
871 		else
872 			*(u8 *)req->buf = 0;
873 		value = min(w_length, (u16) 1);
874 		break;
875 
876 	/*
877 	 * function drivers must handle get/set altsetting; if there's
878 	 * no get() method, we know only altsetting zero works.
879 	 */
880 	case USB_REQ_SET_INTERFACE:
881 		if (ctrl->bRequestType != USB_RECIP_INTERFACE)
882 			goto unknown;
883 		if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
884 			break;
885 		f = cdev->config->interface[intf];
886 		if (!f)
887 			break;
888 		if (w_value && !f->set_alt)
889 			break;
890 		value = f->set_alt(f, w_index, w_value);
891 		break;
892 	case USB_REQ_GET_INTERFACE:
893 		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
894 			goto unknown;
895 		if (!cdev->config || w_index >= MAX_CONFIG_INTERFACES)
896 			break;
897 		f = cdev->config->interface[intf];
898 		if (!f)
899 			break;
900 		/* lots of interfaces only need altsetting zero... */
901 		value = f->get_alt ? f->get_alt(f, w_index) : 0;
902 		if (value < 0)
903 			break;
904 		*((u8 *)req->buf) = value;
905 		value = min(w_length, (u16) 1);
906 		break;
907 	default:
908 unknown:
909 		debug("non-core control req%02x.%02x v%04x i%04x l%d\n",
910 			ctrl->bRequestType, ctrl->bRequest,
911 			w_value, w_index, w_length);
912 
913 		if (!cdev->config)
914 			goto done;
915 
916 		/*
917 		 * functions always handle their interfaces and endpoints...
918 		 * punt other recipients (other, WUSB, ...) to the current
919 		 * configuration code.
920 		 */
921 		switch (ctrl->bRequestType & USB_RECIP_MASK) {
922 		case USB_RECIP_INTERFACE:
923 			f = cdev->config->interface[intf];
924 			break;
925 
926 		case USB_RECIP_ENDPOINT:
927 			endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
928 			list_for_each_entry(f, &cdev->config->functions, list) {
929 				if (test_bit(endp, f->endpoints))
930 					break;
931 			}
932 			if (&f->list == &cdev->config->functions)
933 				f = NULL;
934 			break;
935 		/*
936 		 * dfu-util (version 0.5) sets bmRequestType.Receipent = Device
937 		 * for non-standard request (w_value = 0x21,
938 		 * bRequest = GET_DESCRIPTOR in this case).
939 		 * When only one interface is registered (as it is done now),
940 		 * then this request shall be handled as it was requested for
941 		 * interface.
942 		 *
943 		 * In the below code it is checked if only one interface is
944 		 * present and proper function for it is extracted. Due to that
945 		 * function's setup (f->setup) is called to handle this
946 		 * special non-standard request.
947 		 */
948 		case USB_RECIP_DEVICE:
949 			debug("cdev->config->next_interface_id: %d intf: %d\n",
950 			       cdev->config->next_interface_id, intf);
951 			if (cdev->config->next_interface_id == 1)
952 				f = cdev->config->interface[intf];
953 			break;
954 		}
955 
956 		if (f && f->setup)
957 			value = f->setup(f, ctrl);
958 		else {
959 			c = cdev->config;
960 			if (c->setup)
961 				value = c->setup(c, ctrl);
962 		}
963 
964 		goto done;
965 	}
966 
967 	/* respond with data transfer before status phase? */
968 	if (value >= 0) {
969 		req->length = value;
970 		req->zero = value < w_length;
971 		value = usb_ep_queue(gadget->ep0, req, GFP_KERNEL);
972 		if (value < 0) {
973 			debug("ep_queue --> %d\n", value);
974 			req->status = 0;
975 			composite_setup_complete(gadget->ep0, req);
976 		}
977 	}
978 
979 done:
980 	/* device either stalls (value < 0) or reports success */
981 	return value;
982 }
983 
composite_disconnect(struct usb_gadget * gadget)984 static void composite_disconnect(struct usb_gadget *gadget)
985 {
986 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
987 
988 	if (cdev->config)
989 		reset_config(cdev);
990 	if (composite->disconnect)
991 		composite->disconnect(cdev);
992 }
993 
composite_unbind(struct usb_gadget * gadget)994 static void composite_unbind(struct usb_gadget *gadget)
995 {
996 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
997 	struct usb_configuration	*c;
998 	struct usb_function		*f;
999 
1000 	/*
1001 	 * composite_disconnect() must already have been called
1002 	 * by the underlying peripheral controller driver!
1003 	 * so there's no i/o concurrency that could affect the
1004 	 * state protected by cdev->lock.
1005 	 */
1006 	BUG_ON(cdev->config);
1007 
1008 	while (!list_empty(&cdev->configs)) {
1009 		c = list_first_entry(&cdev->configs,
1010 				struct usb_configuration, list);
1011 		while (!list_empty(&c->functions)) {
1012 			f = list_first_entry(&c->functions,
1013 					struct usb_function, list);
1014 			list_del(&f->list);
1015 			if (f->unbind) {
1016 				debug("unbind function '%s'/%p\n",
1017 						f->name, f);
1018 				f->unbind(c, f);
1019 			}
1020 		}
1021 		list_del(&c->list);
1022 		if (c->unbind) {
1023 			debug("unbind config '%s'/%p\n", c->label, c);
1024 			c->unbind(c);
1025 		}
1026 		free(c);
1027 	}
1028 	if (composite->unbind)
1029 		composite->unbind(cdev);
1030 
1031 	if (cdev->req) {
1032 		kfree(cdev->req->buf);
1033 		usb_ep_free_request(gadget->ep0, cdev->req);
1034 	}
1035 	kfree(cdev);
1036 	set_gadget_data(gadget, NULL);
1037 
1038 	composite = NULL;
1039 }
1040 
composite_bind(struct usb_gadget * gadget)1041 static int composite_bind(struct usb_gadget *gadget)
1042 {
1043 	int				status = -ENOMEM;
1044 	struct usb_composite_dev	*cdev;
1045 
1046 	cdev = calloc(sizeof *cdev, 1);
1047 	if (!cdev)
1048 		return status;
1049 
1050 	cdev->gadget = gadget;
1051 	set_gadget_data(gadget, cdev);
1052 	INIT_LIST_HEAD(&cdev->configs);
1053 
1054 	/* preallocate control response and buffer */
1055 	cdev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1056 	if (!cdev->req)
1057 		goto fail;
1058 	cdev->req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, USB_BUFSIZ);
1059 	if (!cdev->req->buf)
1060 		goto fail;
1061 	cdev->req->complete = composite_setup_complete;
1062 	gadget->ep0->driver_data = cdev;
1063 
1064 	cdev->bufsiz = USB_BUFSIZ;
1065 	cdev->driver = composite;
1066 
1067 	usb_gadget_set_selfpowered(gadget);
1068 	usb_ep_autoconfig_reset(cdev->gadget);
1069 
1070 	status = composite->bind(cdev);
1071 	if (status < 0)
1072 		goto fail;
1073 
1074 	memcpy(&cdev->desc, composite->dev,
1075 	       sizeof(struct usb_device_descriptor));
1076 	cdev->desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1077 
1078 	debug("%s: ready\n", composite->name);
1079 	return 0;
1080 
1081 fail:
1082 	composite_unbind(gadget);
1083 	return status;
1084 }
1085 
1086 static void
composite_suspend(struct usb_gadget * gadget)1087 composite_suspend(struct usb_gadget *gadget)
1088 {
1089 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1090 	struct usb_function		*f;
1091 
1092 	debug("%s: suspend\n", __func__);
1093 	if (cdev->config) {
1094 		list_for_each_entry(f, &cdev->config->functions, list) {
1095 			if (f->suspend)
1096 				f->suspend(f);
1097 		}
1098 	}
1099 	if (composite->suspend)
1100 		composite->suspend(cdev);
1101 
1102 	cdev->suspended = 1;
1103 }
1104 
1105 static void
composite_resume(struct usb_gadget * gadget)1106 composite_resume(struct usb_gadget *gadget)
1107 {
1108 	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
1109 	struct usb_function		*f;
1110 
1111 	debug("%s: resume\n", __func__);
1112 	if (composite->resume)
1113 		composite->resume(cdev);
1114 	if (cdev->config) {
1115 		list_for_each_entry(f, &cdev->config->functions, list) {
1116 			if (f->resume)
1117 				f->resume(f);
1118 		}
1119 	}
1120 
1121 	cdev->suspended = 0;
1122 }
1123 
1124 static struct usb_gadget_driver composite_driver = {
1125 	.speed		= USB_SPEED_HIGH,
1126 
1127 	.bind		= composite_bind,
1128 	.unbind         = composite_unbind,
1129 
1130 	.setup		= composite_setup,
1131 	.reset          = composite_disconnect,
1132 	.disconnect	= composite_disconnect,
1133 
1134 	.suspend        = composite_suspend,
1135 	.resume         = composite_resume,
1136 };
1137 
1138 /**
1139  * usb_composite_register() - register a composite driver
1140  * @driver: the driver to register
1141  * Context: single threaded during gadget setup
1142  *
1143  * This function is used to register drivers using the composite driver
1144  * framework.  The return value is zero, or a negative errno value.
1145  * Those values normally come from the driver's @bind method, which does
1146  * all the work of setting up the driver to match the hardware.
1147  *
1148  * On successful return, the gadget is ready to respond to requests from
1149  * the host, unless one of its components invokes usb_gadget_disconnect()
1150  * while it was binding.  That would usually be done in order to wait for
1151  * some userspace participation.
1152  */
usb_composite_register(struct usb_composite_driver * driver)1153 int usb_composite_register(struct usb_composite_driver *driver)
1154 {
1155 	int res;
1156 
1157 	if (!driver || !driver->dev || !driver->bind || composite)
1158 		return -EINVAL;
1159 
1160 	if (!driver->name)
1161 		driver->name = "composite";
1162 	composite = driver;
1163 
1164 	res = usb_gadget_register_driver(&composite_driver);
1165 	if (res != 0)
1166 		composite = NULL;
1167 
1168 	return res;
1169 }
1170 
1171 /**
1172  * usb_composite_unregister() - unregister a composite driver
1173  * @driver: the driver to unregister
1174  *
1175  * This function is used to unregister drivers using the composite
1176  * driver framework.
1177  */
usb_composite_unregister(struct usb_composite_driver * driver)1178 void usb_composite_unregister(struct usb_composite_driver *driver)
1179 {
1180 	if (composite != driver)
1181 		return;
1182 	usb_gadget_unregister_driver(&composite_driver);
1183 	composite = NULL;
1184 }
1185