xref: /linux/drivers/usb/core/config.c (revision f86fd32d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Released under the GPLv2 only.
4  */
5 
6 #include <linux/usb.h>
7 #include <linux/usb/ch9.h>
8 #include <linux/usb/hcd.h>
9 #include <linux/usb/quirks.h>
10 #include <linux/module.h>
11 #include <linux/slab.h>
12 #include <linux/device.h>
13 #include <asm/byteorder.h>
14 #include "usb.h"
15 
16 
17 #define USB_MAXALTSETTING		128	/* Hard limit */
18 
19 #define USB_MAXCONFIG			8	/* Arbitrary limit */
20 
21 
22 static inline const char *plural(int n)
23 {
24 	return (n == 1 ? "" : "s");
25 }
26 
27 static int find_next_descriptor(unsigned char *buffer, int size,
28     int dt1, int dt2, int *num_skipped)
29 {
30 	struct usb_descriptor_header *h;
31 	int n = 0;
32 	unsigned char *buffer0 = buffer;
33 
34 	/* Find the next descriptor of type dt1 or dt2 */
35 	while (size > 0) {
36 		h = (struct usb_descriptor_header *) buffer;
37 		if (h->bDescriptorType == dt1 || h->bDescriptorType == dt2)
38 			break;
39 		buffer += h->bLength;
40 		size -= h->bLength;
41 		++n;
42 	}
43 
44 	/* Store the number of descriptors skipped and return the
45 	 * number of bytes skipped */
46 	if (num_skipped)
47 		*num_skipped = n;
48 	return buffer - buffer0;
49 }
50 
51 static void usb_parse_ssp_isoc_endpoint_companion(struct device *ddev,
52 		int cfgno, int inum, int asnum, struct usb_host_endpoint *ep,
53 		unsigned char *buffer, int size)
54 {
55 	struct usb_ssp_isoc_ep_comp_descriptor *desc;
56 
57 	/*
58 	 * The SuperSpeedPlus Isoc endpoint companion descriptor immediately
59 	 * follows the SuperSpeed Endpoint Companion descriptor
60 	 */
61 	desc = (struct usb_ssp_isoc_ep_comp_descriptor *) buffer;
62 	if (desc->bDescriptorType != USB_DT_SSP_ISOC_ENDPOINT_COMP ||
63 	    size < USB_DT_SSP_ISOC_EP_COMP_SIZE) {
64 		dev_warn(ddev, "Invalid SuperSpeedPlus isoc endpoint companion"
65 			 "for config %d interface %d altsetting %d ep %d.\n",
66 			 cfgno, inum, asnum, ep->desc.bEndpointAddress);
67 		return;
68 	}
69 	memcpy(&ep->ssp_isoc_ep_comp, desc, USB_DT_SSP_ISOC_EP_COMP_SIZE);
70 }
71 
72 static void usb_parse_ss_endpoint_companion(struct device *ddev, int cfgno,
73 		int inum, int asnum, struct usb_host_endpoint *ep,
74 		unsigned char *buffer, int size)
75 {
76 	struct usb_ss_ep_comp_descriptor *desc;
77 	int max_tx;
78 
79 	/* The SuperSpeed endpoint companion descriptor is supposed to
80 	 * be the first thing immediately following the endpoint descriptor.
81 	 */
82 	desc = (struct usb_ss_ep_comp_descriptor *) buffer;
83 
84 	if (desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP ||
85 			size < USB_DT_SS_EP_COMP_SIZE) {
86 		dev_warn(ddev, "No SuperSpeed endpoint companion for config %d "
87 				" interface %d altsetting %d ep %d: "
88 				"using minimum values\n",
89 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
90 
91 		/* Fill in some default values.
92 		 * Leave bmAttributes as zero, which will mean no streams for
93 		 * bulk, and isoc won't support multiple bursts of packets.
94 		 * With bursts of only one packet, and a Mult of 1, the max
95 		 * amount of data moved per endpoint service interval is one
96 		 * packet.
97 		 */
98 		ep->ss_ep_comp.bLength = USB_DT_SS_EP_COMP_SIZE;
99 		ep->ss_ep_comp.bDescriptorType = USB_DT_SS_ENDPOINT_COMP;
100 		if (usb_endpoint_xfer_isoc(&ep->desc) ||
101 				usb_endpoint_xfer_int(&ep->desc))
102 			ep->ss_ep_comp.wBytesPerInterval =
103 					ep->desc.wMaxPacketSize;
104 		return;
105 	}
106 	buffer += desc->bLength;
107 	size -= desc->bLength;
108 	memcpy(&ep->ss_ep_comp, desc, USB_DT_SS_EP_COMP_SIZE);
109 
110 	/* Check the various values */
111 	if (usb_endpoint_xfer_control(&ep->desc) && desc->bMaxBurst != 0) {
112 		dev_warn(ddev, "Control endpoint with bMaxBurst = %d in "
113 				"config %d interface %d altsetting %d ep %d: "
114 				"setting to zero\n", desc->bMaxBurst,
115 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
116 		ep->ss_ep_comp.bMaxBurst = 0;
117 	} else if (desc->bMaxBurst > 15) {
118 		dev_warn(ddev, "Endpoint with bMaxBurst = %d in "
119 				"config %d interface %d altsetting %d ep %d: "
120 				"setting to 15\n", desc->bMaxBurst,
121 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
122 		ep->ss_ep_comp.bMaxBurst = 15;
123 	}
124 
125 	if ((usb_endpoint_xfer_control(&ep->desc) ||
126 			usb_endpoint_xfer_int(&ep->desc)) &&
127 				desc->bmAttributes != 0) {
128 		dev_warn(ddev, "%s endpoint with bmAttributes = %d in "
129 				"config %d interface %d altsetting %d ep %d: "
130 				"setting to zero\n",
131 				usb_endpoint_xfer_control(&ep->desc) ? "Control" : "Bulk",
132 				desc->bmAttributes,
133 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
134 		ep->ss_ep_comp.bmAttributes = 0;
135 	} else if (usb_endpoint_xfer_bulk(&ep->desc) &&
136 			desc->bmAttributes > 16) {
137 		dev_warn(ddev, "Bulk endpoint with more than 65536 streams in "
138 				"config %d interface %d altsetting %d ep %d: "
139 				"setting to max\n",
140 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
141 		ep->ss_ep_comp.bmAttributes = 16;
142 	} else if (usb_endpoint_xfer_isoc(&ep->desc) &&
143 		   !USB_SS_SSP_ISOC_COMP(desc->bmAttributes) &&
144 		   USB_SS_MULT(desc->bmAttributes) > 3) {
145 		dev_warn(ddev, "Isoc endpoint has Mult of %d in "
146 				"config %d interface %d altsetting %d ep %d: "
147 				"setting to 3\n",
148 				USB_SS_MULT(desc->bmAttributes),
149 				cfgno, inum, asnum, ep->desc.bEndpointAddress);
150 		ep->ss_ep_comp.bmAttributes = 2;
151 	}
152 
153 	if (usb_endpoint_xfer_isoc(&ep->desc))
154 		max_tx = (desc->bMaxBurst + 1) *
155 			(USB_SS_MULT(desc->bmAttributes)) *
156 			usb_endpoint_maxp(&ep->desc);
157 	else if (usb_endpoint_xfer_int(&ep->desc))
158 		max_tx = usb_endpoint_maxp(&ep->desc) *
159 			(desc->bMaxBurst + 1);
160 	else
161 		max_tx = 999999;
162 	if (le16_to_cpu(desc->wBytesPerInterval) > max_tx) {
163 		dev_warn(ddev, "%s endpoint with wBytesPerInterval of %d in "
164 				"config %d interface %d altsetting %d ep %d: "
165 				"setting to %d\n",
166 				usb_endpoint_xfer_isoc(&ep->desc) ? "Isoc" : "Int",
167 				le16_to_cpu(desc->wBytesPerInterval),
168 				cfgno, inum, asnum, ep->desc.bEndpointAddress,
169 				max_tx);
170 		ep->ss_ep_comp.wBytesPerInterval = cpu_to_le16(max_tx);
171 	}
172 	/* Parse a possible SuperSpeedPlus isoc ep companion descriptor */
173 	if (usb_endpoint_xfer_isoc(&ep->desc) &&
174 	    USB_SS_SSP_ISOC_COMP(desc->bmAttributes))
175 		usb_parse_ssp_isoc_endpoint_companion(ddev, cfgno, inum, asnum,
176 							ep, buffer, size);
177 }
178 
179 static const unsigned short low_speed_maxpacket_maxes[4] = {
180 	[USB_ENDPOINT_XFER_CONTROL] = 8,
181 	[USB_ENDPOINT_XFER_ISOC] = 0,
182 	[USB_ENDPOINT_XFER_BULK] = 0,
183 	[USB_ENDPOINT_XFER_INT] = 8,
184 };
185 static const unsigned short full_speed_maxpacket_maxes[4] = {
186 	[USB_ENDPOINT_XFER_CONTROL] = 64,
187 	[USB_ENDPOINT_XFER_ISOC] = 1023,
188 	[USB_ENDPOINT_XFER_BULK] = 64,
189 	[USB_ENDPOINT_XFER_INT] = 64,
190 };
191 static const unsigned short high_speed_maxpacket_maxes[4] = {
192 	[USB_ENDPOINT_XFER_CONTROL] = 64,
193 	[USB_ENDPOINT_XFER_ISOC] = 1024,
194 
195 	/* Bulk should be 512, but some devices use 1024: we will warn below */
196 	[USB_ENDPOINT_XFER_BULK] = 1024,
197 	[USB_ENDPOINT_XFER_INT] = 1024,
198 };
199 static const unsigned short super_speed_maxpacket_maxes[4] = {
200 	[USB_ENDPOINT_XFER_CONTROL] = 512,
201 	[USB_ENDPOINT_XFER_ISOC] = 1024,
202 	[USB_ENDPOINT_XFER_BULK] = 1024,
203 	[USB_ENDPOINT_XFER_INT] = 1024,
204 };
205 
206 static bool endpoint_is_duplicate(struct usb_endpoint_descriptor *e1,
207 		struct usb_endpoint_descriptor *e2)
208 {
209 	if (e1->bEndpointAddress == e2->bEndpointAddress)
210 		return true;
211 
212 	if (usb_endpoint_xfer_control(e1) || usb_endpoint_xfer_control(e2)) {
213 		if (usb_endpoint_num(e1) == usb_endpoint_num(e2))
214 			return true;
215 	}
216 
217 	return false;
218 }
219 
220 /*
221  * Check for duplicate endpoint addresses in other interfaces and in the
222  * altsetting currently being parsed.
223  */
224 static bool config_endpoint_is_duplicate(struct usb_host_config *config,
225 		int inum, int asnum, struct usb_endpoint_descriptor *d)
226 {
227 	struct usb_endpoint_descriptor *epd;
228 	struct usb_interface_cache *intfc;
229 	struct usb_host_interface *alt;
230 	int i, j, k;
231 
232 	for (i = 0; i < config->desc.bNumInterfaces; ++i) {
233 		intfc = config->intf_cache[i];
234 
235 		for (j = 0; j < intfc->num_altsetting; ++j) {
236 			alt = &intfc->altsetting[j];
237 
238 			if (alt->desc.bInterfaceNumber == inum &&
239 					alt->desc.bAlternateSetting != asnum)
240 				continue;
241 
242 			for (k = 0; k < alt->desc.bNumEndpoints; ++k) {
243 				epd = &alt->endpoint[k].desc;
244 
245 				if (endpoint_is_duplicate(epd, d))
246 					return true;
247 			}
248 		}
249 	}
250 
251 	return false;
252 }
253 
254 static int usb_parse_endpoint(struct device *ddev, int cfgno,
255 		struct usb_host_config *config, int inum, int asnum,
256 		struct usb_host_interface *ifp, int num_ep,
257 		unsigned char *buffer, int size)
258 {
259 	unsigned char *buffer0 = buffer;
260 	struct usb_endpoint_descriptor *d;
261 	struct usb_host_endpoint *endpoint;
262 	int n, i, j, retval;
263 	unsigned int maxp;
264 	const unsigned short *maxpacket_maxes;
265 
266 	d = (struct usb_endpoint_descriptor *) buffer;
267 	buffer += d->bLength;
268 	size -= d->bLength;
269 
270 	if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
271 		n = USB_DT_ENDPOINT_AUDIO_SIZE;
272 	else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
273 		n = USB_DT_ENDPOINT_SIZE;
274 	else {
275 		dev_warn(ddev, "config %d interface %d altsetting %d has an "
276 		    "invalid endpoint descriptor of length %d, skipping\n",
277 		    cfgno, inum, asnum, d->bLength);
278 		goto skip_to_next_endpoint_or_interface_descriptor;
279 	}
280 
281 	i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
282 	if (i >= 16 || i == 0) {
283 		dev_warn(ddev, "config %d interface %d altsetting %d has an "
284 		    "invalid endpoint with address 0x%X, skipping\n",
285 		    cfgno, inum, asnum, d->bEndpointAddress);
286 		goto skip_to_next_endpoint_or_interface_descriptor;
287 	}
288 
289 	/* Only store as many endpoints as we have room for */
290 	if (ifp->desc.bNumEndpoints >= num_ep)
291 		goto skip_to_next_endpoint_or_interface_descriptor;
292 
293 	/* Check for duplicate endpoint addresses */
294 	if (config_endpoint_is_duplicate(config, inum, asnum, d)) {
295 		dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
296 				cfgno, inum, asnum, d->bEndpointAddress);
297 		goto skip_to_next_endpoint_or_interface_descriptor;
298 	}
299 
300 	endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
301 	++ifp->desc.bNumEndpoints;
302 
303 	memcpy(&endpoint->desc, d, n);
304 	INIT_LIST_HEAD(&endpoint->urb_list);
305 
306 	/*
307 	 * Fix up bInterval values outside the legal range.
308 	 * Use 10 or 8 ms if no proper value can be guessed.
309 	 */
310 	i = 0;		/* i = min, j = max, n = default */
311 	j = 255;
312 	if (usb_endpoint_xfer_int(d)) {
313 		i = 1;
314 		switch (to_usb_device(ddev)->speed) {
315 		case USB_SPEED_SUPER_PLUS:
316 		case USB_SPEED_SUPER:
317 		case USB_SPEED_HIGH:
318 			/*
319 			 * Many device manufacturers are using full-speed
320 			 * bInterval values in high-speed interrupt endpoint
321 			 * descriptors. Try to fix those and fall back to an
322 			 * 8-ms default value otherwise.
323 			 */
324 			n = fls(d->bInterval*8);
325 			if (n == 0)
326 				n = 7;	/* 8 ms = 2^(7-1) uframes */
327 			j = 16;
328 
329 			/*
330 			 * Adjust bInterval for quirked devices.
331 			 */
332 			/*
333 			 * This quirk fixes bIntervals reported in ms.
334 			 */
335 			if (to_usb_device(ddev)->quirks &
336 				USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
337 				n = clamp(fls(d->bInterval) + 3, i, j);
338 				i = j = n;
339 			}
340 			/*
341 			 * This quirk fixes bIntervals reported in
342 			 * linear microframes.
343 			 */
344 			if (to_usb_device(ddev)->quirks &
345 				USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
346 				n = clamp(fls(d->bInterval), i, j);
347 				i = j = n;
348 			}
349 			break;
350 		default:		/* USB_SPEED_FULL or _LOW */
351 			/*
352 			 * For low-speed, 10 ms is the official minimum.
353 			 * But some "overclocked" devices might want faster
354 			 * polling so we'll allow it.
355 			 */
356 			n = 10;
357 			break;
358 		}
359 	} else if (usb_endpoint_xfer_isoc(d)) {
360 		i = 1;
361 		j = 16;
362 		switch (to_usb_device(ddev)->speed) {
363 		case USB_SPEED_HIGH:
364 			n = 7;		/* 8 ms = 2^(7-1) uframes */
365 			break;
366 		default:		/* USB_SPEED_FULL */
367 			n = 4;		/* 8 ms = 2^(4-1) frames */
368 			break;
369 		}
370 	}
371 	if (d->bInterval < i || d->bInterval > j) {
372 		dev_warn(ddev, "config %d interface %d altsetting %d "
373 		    "endpoint 0x%X has an invalid bInterval %d, "
374 		    "changing to %d\n",
375 		    cfgno, inum, asnum,
376 		    d->bEndpointAddress, d->bInterval, n);
377 		endpoint->desc.bInterval = n;
378 	}
379 
380 	/* Some buggy low-speed devices have Bulk endpoints, which is
381 	 * explicitly forbidden by the USB spec.  In an attempt to make
382 	 * them usable, we will try treating them as Interrupt endpoints.
383 	 */
384 	if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
385 			usb_endpoint_xfer_bulk(d)) {
386 		dev_warn(ddev, "config %d interface %d altsetting %d "
387 		    "endpoint 0x%X is Bulk; changing to Interrupt\n",
388 		    cfgno, inum, asnum, d->bEndpointAddress);
389 		endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
390 		endpoint->desc.bInterval = 1;
391 		if (usb_endpoint_maxp(&endpoint->desc) > 8)
392 			endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
393 	}
394 
395 	/*
396 	 * Validate the wMaxPacketSize field.
397 	 * Some devices have isochronous endpoints in altsetting 0;
398 	 * the USB-2 spec requires such endpoints to have wMaxPacketSize = 0
399 	 * (see the end of section 5.6.3), so don't warn about them.
400 	 */
401 	maxp = usb_endpoint_maxp(&endpoint->desc);
402 	if (maxp == 0 && !(usb_endpoint_xfer_isoc(d) && asnum == 0)) {
403 		dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid wMaxPacketSize 0\n",
404 		    cfgno, inum, asnum, d->bEndpointAddress);
405 	}
406 
407 	/* Find the highest legal maxpacket size for this endpoint */
408 	i = 0;		/* additional transactions per microframe */
409 	switch (to_usb_device(ddev)->speed) {
410 	case USB_SPEED_LOW:
411 		maxpacket_maxes = low_speed_maxpacket_maxes;
412 		break;
413 	case USB_SPEED_FULL:
414 		maxpacket_maxes = full_speed_maxpacket_maxes;
415 		break;
416 	case USB_SPEED_HIGH:
417 		/* Bits 12..11 are allowed only for HS periodic endpoints */
418 		if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
419 			i = maxp & (BIT(12) | BIT(11));
420 			maxp &= ~i;
421 		}
422 		/* fallthrough */
423 	default:
424 		maxpacket_maxes = high_speed_maxpacket_maxes;
425 		break;
426 	case USB_SPEED_SUPER:
427 	case USB_SPEED_SUPER_PLUS:
428 		maxpacket_maxes = super_speed_maxpacket_maxes;
429 		break;
430 	}
431 	j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
432 
433 	if (maxp > j) {
434 		dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
435 		    cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
436 		maxp = j;
437 		endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
438 	}
439 
440 	/*
441 	 * Some buggy high speed devices have bulk endpoints using
442 	 * maxpacket sizes other than 512.  High speed HCDs may not
443 	 * be able to handle that particular bug, so let's warn...
444 	 */
445 	if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
446 			&& usb_endpoint_xfer_bulk(d)) {
447 		if (maxp != 512)
448 			dev_warn(ddev, "config %d interface %d altsetting %d "
449 				"bulk endpoint 0x%X has invalid maxpacket %d\n",
450 				cfgno, inum, asnum, d->bEndpointAddress,
451 				maxp);
452 	}
453 
454 	/* Parse a possible SuperSpeed endpoint companion descriptor */
455 	if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
456 		usb_parse_ss_endpoint_companion(ddev, cfgno,
457 				inum, asnum, endpoint, buffer, size);
458 
459 	/* Skip over any Class Specific or Vendor Specific descriptors;
460 	 * find the next endpoint or interface descriptor */
461 	endpoint->extra = buffer;
462 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
463 			USB_DT_INTERFACE, &n);
464 	endpoint->extralen = i;
465 	retval = buffer - buffer0 + i;
466 	if (n > 0)
467 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
468 		    n, plural(n), "endpoint");
469 	return retval;
470 
471 skip_to_next_endpoint_or_interface_descriptor:
472 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
473 	    USB_DT_INTERFACE, NULL);
474 	return buffer - buffer0 + i;
475 }
476 
477 void usb_release_interface_cache(struct kref *ref)
478 {
479 	struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
480 	int j;
481 
482 	for (j = 0; j < intfc->num_altsetting; j++) {
483 		struct usb_host_interface *alt = &intfc->altsetting[j];
484 
485 		kfree(alt->endpoint);
486 		kfree(alt->string);
487 	}
488 	kfree(intfc);
489 }
490 
491 static int usb_parse_interface(struct device *ddev, int cfgno,
492     struct usb_host_config *config, unsigned char *buffer, int size,
493     u8 inums[], u8 nalts[])
494 {
495 	unsigned char *buffer0 = buffer;
496 	struct usb_interface_descriptor	*d;
497 	int inum, asnum;
498 	struct usb_interface_cache *intfc;
499 	struct usb_host_interface *alt;
500 	int i, n;
501 	int len, retval;
502 	int num_ep, num_ep_orig;
503 
504 	d = (struct usb_interface_descriptor *) buffer;
505 	buffer += d->bLength;
506 	size -= d->bLength;
507 
508 	if (d->bLength < USB_DT_INTERFACE_SIZE)
509 		goto skip_to_next_interface_descriptor;
510 
511 	/* Which interface entry is this? */
512 	intfc = NULL;
513 	inum = d->bInterfaceNumber;
514 	for (i = 0; i < config->desc.bNumInterfaces; ++i) {
515 		if (inums[i] == inum) {
516 			intfc = config->intf_cache[i];
517 			break;
518 		}
519 	}
520 	if (!intfc || intfc->num_altsetting >= nalts[i])
521 		goto skip_to_next_interface_descriptor;
522 
523 	/* Check for duplicate altsetting entries */
524 	asnum = d->bAlternateSetting;
525 	for ((i = 0, alt = &intfc->altsetting[0]);
526 	      i < intfc->num_altsetting;
527 	     (++i, ++alt)) {
528 		if (alt->desc.bAlternateSetting == asnum) {
529 			dev_warn(ddev, "Duplicate descriptor for config %d "
530 			    "interface %d altsetting %d, skipping\n",
531 			    cfgno, inum, asnum);
532 			goto skip_to_next_interface_descriptor;
533 		}
534 	}
535 
536 	++intfc->num_altsetting;
537 	memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
538 
539 	/* Skip over any Class Specific or Vendor Specific descriptors;
540 	 * find the first endpoint or interface descriptor */
541 	alt->extra = buffer;
542 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
543 	    USB_DT_INTERFACE, &n);
544 	alt->extralen = i;
545 	if (n > 0)
546 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
547 		    n, plural(n), "interface");
548 	buffer += i;
549 	size -= i;
550 
551 	/* Allocate space for the right(?) number of endpoints */
552 	num_ep = num_ep_orig = alt->desc.bNumEndpoints;
553 	alt->desc.bNumEndpoints = 0;		/* Use as a counter */
554 	if (num_ep > USB_MAXENDPOINTS) {
555 		dev_warn(ddev, "too many endpoints for config %d interface %d "
556 		    "altsetting %d: %d, using maximum allowed: %d\n",
557 		    cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
558 		num_ep = USB_MAXENDPOINTS;
559 	}
560 
561 	if (num_ep > 0) {
562 		/* Can't allocate 0 bytes */
563 		len = sizeof(struct usb_host_endpoint) * num_ep;
564 		alt->endpoint = kzalloc(len, GFP_KERNEL);
565 		if (!alt->endpoint)
566 			return -ENOMEM;
567 	}
568 
569 	/* Parse all the endpoint descriptors */
570 	n = 0;
571 	while (size > 0) {
572 		if (((struct usb_descriptor_header *) buffer)->bDescriptorType
573 		     == USB_DT_INTERFACE)
574 			break;
575 		retval = usb_parse_endpoint(ddev, cfgno, config, inum, asnum,
576 				alt, num_ep, buffer, size);
577 		if (retval < 0)
578 			return retval;
579 		++n;
580 
581 		buffer += retval;
582 		size -= retval;
583 	}
584 
585 	if (n != num_ep_orig)
586 		dev_warn(ddev, "config %d interface %d altsetting %d has %d "
587 		    "endpoint descriptor%s, different from the interface "
588 		    "descriptor's value: %d\n",
589 		    cfgno, inum, asnum, n, plural(n), num_ep_orig);
590 	return buffer - buffer0;
591 
592 skip_to_next_interface_descriptor:
593 	i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
594 	    USB_DT_INTERFACE, NULL);
595 	return buffer - buffer0 + i;
596 }
597 
598 static int usb_parse_configuration(struct usb_device *dev, int cfgidx,
599     struct usb_host_config *config, unsigned char *buffer, int size)
600 {
601 	struct device *ddev = &dev->dev;
602 	unsigned char *buffer0 = buffer;
603 	int cfgno;
604 	int nintf, nintf_orig;
605 	int i, j, n;
606 	struct usb_interface_cache *intfc;
607 	unsigned char *buffer2;
608 	int size2;
609 	struct usb_descriptor_header *header;
610 	int retval;
611 	u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
612 	unsigned iad_num = 0;
613 
614 	memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
615 	nintf = nintf_orig = config->desc.bNumInterfaces;
616 	config->desc.bNumInterfaces = 0;	// Adjusted later
617 
618 	if (config->desc.bDescriptorType != USB_DT_CONFIG ||
619 	    config->desc.bLength < USB_DT_CONFIG_SIZE ||
620 	    config->desc.bLength > size) {
621 		dev_err(ddev, "invalid descriptor for config index %d: "
622 		    "type = 0x%X, length = %d\n", cfgidx,
623 		    config->desc.bDescriptorType, config->desc.bLength);
624 		return -EINVAL;
625 	}
626 	cfgno = config->desc.bConfigurationValue;
627 
628 	buffer += config->desc.bLength;
629 	size -= config->desc.bLength;
630 
631 	if (nintf > USB_MAXINTERFACES) {
632 		dev_warn(ddev, "config %d has too many interfaces: %d, "
633 		    "using maximum allowed: %d\n",
634 		    cfgno, nintf, USB_MAXINTERFACES);
635 		nintf = USB_MAXINTERFACES;
636 	}
637 
638 	/* Go through the descriptors, checking their length and counting the
639 	 * number of altsettings for each interface */
640 	n = 0;
641 	for ((buffer2 = buffer, size2 = size);
642 	      size2 > 0;
643 	     (buffer2 += header->bLength, size2 -= header->bLength)) {
644 
645 		if (size2 < sizeof(struct usb_descriptor_header)) {
646 			dev_warn(ddev, "config %d descriptor has %d excess "
647 			    "byte%s, ignoring\n",
648 			    cfgno, size2, plural(size2));
649 			break;
650 		}
651 
652 		header = (struct usb_descriptor_header *) buffer2;
653 		if ((header->bLength > size2) || (header->bLength < 2)) {
654 			dev_warn(ddev, "config %d has an invalid descriptor "
655 			    "of length %d, skipping remainder of the config\n",
656 			    cfgno, header->bLength);
657 			break;
658 		}
659 
660 		if (header->bDescriptorType == USB_DT_INTERFACE) {
661 			struct usb_interface_descriptor *d;
662 			int inum;
663 
664 			d = (struct usb_interface_descriptor *) header;
665 			if (d->bLength < USB_DT_INTERFACE_SIZE) {
666 				dev_warn(ddev, "config %d has an invalid "
667 				    "interface descriptor of length %d, "
668 				    "skipping\n", cfgno, d->bLength);
669 				continue;
670 			}
671 
672 			inum = d->bInterfaceNumber;
673 
674 			if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
675 			    n >= nintf_orig) {
676 				dev_warn(ddev, "config %d has more interface "
677 				    "descriptors, than it declares in "
678 				    "bNumInterfaces, ignoring interface "
679 				    "number: %d\n", cfgno, inum);
680 				continue;
681 			}
682 
683 			if (inum >= nintf_orig)
684 				dev_warn(ddev, "config %d has an invalid "
685 				    "interface number: %d but max is %d\n",
686 				    cfgno, inum, nintf_orig - 1);
687 
688 			/* Have we already encountered this interface?
689 			 * Count its altsettings */
690 			for (i = 0; i < n; ++i) {
691 				if (inums[i] == inum)
692 					break;
693 			}
694 			if (i < n) {
695 				if (nalts[i] < 255)
696 					++nalts[i];
697 			} else if (n < USB_MAXINTERFACES) {
698 				inums[n] = inum;
699 				nalts[n] = 1;
700 				++n;
701 			}
702 
703 		} else if (header->bDescriptorType ==
704 				USB_DT_INTERFACE_ASSOCIATION) {
705 			struct usb_interface_assoc_descriptor *d;
706 
707 			d = (struct usb_interface_assoc_descriptor *)header;
708 			if (d->bLength < USB_DT_INTERFACE_ASSOCIATION_SIZE) {
709 				dev_warn(ddev,
710 					 "config %d has an invalid interface association descriptor of length %d, skipping\n",
711 					 cfgno, d->bLength);
712 				continue;
713 			}
714 
715 			if (iad_num == USB_MAXIADS) {
716 				dev_warn(ddev, "found more Interface "
717 					       "Association Descriptors "
718 					       "than allocated for in "
719 					       "configuration %d\n", cfgno);
720 			} else {
721 				config->intf_assoc[iad_num] = d;
722 				iad_num++;
723 			}
724 
725 		} else if (header->bDescriptorType == USB_DT_DEVICE ||
726 			    header->bDescriptorType == USB_DT_CONFIG)
727 			dev_warn(ddev, "config %d contains an unexpected "
728 			    "descriptor of type 0x%X, skipping\n",
729 			    cfgno, header->bDescriptorType);
730 
731 	}	/* for ((buffer2 = buffer, size2 = size); ...) */
732 	size = buffer2 - buffer;
733 	config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
734 
735 	if (n != nintf)
736 		dev_warn(ddev, "config %d has %d interface%s, different from "
737 		    "the descriptor's value: %d\n",
738 		    cfgno, n, plural(n), nintf_orig);
739 	else if (n == 0)
740 		dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
741 	config->desc.bNumInterfaces = nintf = n;
742 
743 	/* Check for missing interface numbers */
744 	for (i = 0; i < nintf; ++i) {
745 		for (j = 0; j < nintf; ++j) {
746 			if (inums[j] == i)
747 				break;
748 		}
749 		if (j >= nintf)
750 			dev_warn(ddev, "config %d has no interface number "
751 			    "%d\n", cfgno, i);
752 	}
753 
754 	/* Allocate the usb_interface_caches and altsetting arrays */
755 	for (i = 0; i < nintf; ++i) {
756 		j = nalts[i];
757 		if (j > USB_MAXALTSETTING) {
758 			dev_warn(ddev, "too many alternate settings for "
759 			    "config %d interface %d: %d, "
760 			    "using maximum allowed: %d\n",
761 			    cfgno, inums[i], j, USB_MAXALTSETTING);
762 			nalts[i] = j = USB_MAXALTSETTING;
763 		}
764 
765 		intfc = kzalloc(struct_size(intfc, altsetting, j), GFP_KERNEL);
766 		config->intf_cache[i] = intfc;
767 		if (!intfc)
768 			return -ENOMEM;
769 		kref_init(&intfc->ref);
770 	}
771 
772 	/* FIXME: parse the BOS descriptor */
773 
774 	/* Skip over any Class Specific or Vendor Specific descriptors;
775 	 * find the first interface descriptor */
776 	config->extra = buffer;
777 	i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
778 	    USB_DT_INTERFACE, &n);
779 	config->extralen = i;
780 	if (n > 0)
781 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
782 		    n, plural(n), "configuration");
783 	buffer += i;
784 	size -= i;
785 
786 	/* Parse all the interface/altsetting descriptors */
787 	while (size > 0) {
788 		retval = usb_parse_interface(ddev, cfgno, config,
789 		    buffer, size, inums, nalts);
790 		if (retval < 0)
791 			return retval;
792 
793 		buffer += retval;
794 		size -= retval;
795 	}
796 
797 	/* Check for missing altsettings */
798 	for (i = 0; i < nintf; ++i) {
799 		intfc = config->intf_cache[i];
800 		for (j = 0; j < intfc->num_altsetting; ++j) {
801 			for (n = 0; n < intfc->num_altsetting; ++n) {
802 				if (intfc->altsetting[n].desc.
803 				    bAlternateSetting == j)
804 					break;
805 			}
806 			if (n >= intfc->num_altsetting)
807 				dev_warn(ddev, "config %d interface %d has no "
808 				    "altsetting %d\n", cfgno, inums[i], j);
809 		}
810 	}
811 
812 	return 0;
813 }
814 
815 /* hub-only!! ... and only exported for reset/reinit path.
816  * otherwise used internally on disconnect/destroy path
817  */
818 void usb_destroy_configuration(struct usb_device *dev)
819 {
820 	int c, i;
821 
822 	if (!dev->config)
823 		return;
824 
825 	if (dev->rawdescriptors) {
826 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
827 			kfree(dev->rawdescriptors[i]);
828 
829 		kfree(dev->rawdescriptors);
830 		dev->rawdescriptors = NULL;
831 	}
832 
833 	for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
834 		struct usb_host_config *cf = &dev->config[c];
835 
836 		kfree(cf->string);
837 		for (i = 0; i < cf->desc.bNumInterfaces; i++) {
838 			if (cf->intf_cache[i])
839 				kref_put(&cf->intf_cache[i]->ref,
840 					  usb_release_interface_cache);
841 		}
842 	}
843 	kfree(dev->config);
844 	dev->config = NULL;
845 }
846 
847 
848 /*
849  * Get the USB config descriptors, cache and parse'em
850  *
851  * hub-only!! ... and only in reset path, or usb_new_device()
852  * (used by real hubs and virtual root hubs)
853  */
854 int usb_get_configuration(struct usb_device *dev)
855 {
856 	struct device *ddev = &dev->dev;
857 	int ncfg = dev->descriptor.bNumConfigurations;
858 	unsigned int cfgno, length;
859 	unsigned char *bigbuffer;
860 	struct usb_config_descriptor *desc;
861 	int result;
862 
863 	if (ncfg > USB_MAXCONFIG) {
864 		dev_warn(ddev, "too many configurations: %d, "
865 		    "using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
866 		dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
867 	}
868 
869 	if (ncfg < 1) {
870 		dev_err(ddev, "no configurations\n");
871 		return -EINVAL;
872 	}
873 
874 	length = ncfg * sizeof(struct usb_host_config);
875 	dev->config = kzalloc(length, GFP_KERNEL);
876 	if (!dev->config)
877 		return -ENOMEM;
878 
879 	length = ncfg * sizeof(char *);
880 	dev->rawdescriptors = kzalloc(length, GFP_KERNEL);
881 	if (!dev->rawdescriptors)
882 		return -ENOMEM;
883 
884 	desc = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
885 	if (!desc)
886 		return -ENOMEM;
887 
888 	for (cfgno = 0; cfgno < ncfg; cfgno++) {
889 		/* We grab just the first descriptor so we know how long
890 		 * the whole configuration is */
891 		result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
892 		    desc, USB_DT_CONFIG_SIZE);
893 		if (result < 0) {
894 			dev_err(ddev, "unable to read config index %d "
895 			    "descriptor/%s: %d\n", cfgno, "start", result);
896 			if (result != -EPIPE)
897 				goto err;
898 			dev_err(ddev, "chopping to %d config(s)\n", cfgno);
899 			dev->descriptor.bNumConfigurations = cfgno;
900 			break;
901 		} else if (result < 4) {
902 			dev_err(ddev, "config index %d descriptor too short "
903 			    "(expected %i, got %i)\n", cfgno,
904 			    USB_DT_CONFIG_SIZE, result);
905 			result = -EINVAL;
906 			goto err;
907 		}
908 		length = max((int) le16_to_cpu(desc->wTotalLength),
909 		    USB_DT_CONFIG_SIZE);
910 
911 		/* Now that we know the length, get the whole thing */
912 		bigbuffer = kmalloc(length, GFP_KERNEL);
913 		if (!bigbuffer) {
914 			result = -ENOMEM;
915 			goto err;
916 		}
917 
918 		if (dev->quirks & USB_QUIRK_DELAY_INIT)
919 			msleep(200);
920 
921 		result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
922 		    bigbuffer, length);
923 		if (result < 0) {
924 			dev_err(ddev, "unable to read config index %d "
925 			    "descriptor/%s\n", cfgno, "all");
926 			kfree(bigbuffer);
927 			goto err;
928 		}
929 		if (result < length) {
930 			dev_warn(ddev, "config index %d descriptor too short "
931 			    "(expected %i, got %i)\n", cfgno, length, result);
932 			length = result;
933 		}
934 
935 		dev->rawdescriptors[cfgno] = bigbuffer;
936 
937 		result = usb_parse_configuration(dev, cfgno,
938 		    &dev->config[cfgno], bigbuffer, length);
939 		if (result < 0) {
940 			++cfgno;
941 			goto err;
942 		}
943 	}
944 
945 err:
946 	kfree(desc);
947 	dev->descriptor.bNumConfigurations = cfgno;
948 
949 	return result;
950 }
951 
952 void usb_release_bos_descriptor(struct usb_device *dev)
953 {
954 	if (dev->bos) {
955 		kfree(dev->bos->desc);
956 		kfree(dev->bos);
957 		dev->bos = NULL;
958 	}
959 }
960 
961 static const __u8 bos_desc_len[256] = {
962 	[USB_CAP_TYPE_WIRELESS_USB] = USB_DT_USB_WIRELESS_CAP_SIZE,
963 	[USB_CAP_TYPE_EXT]          = USB_DT_USB_EXT_CAP_SIZE,
964 	[USB_SS_CAP_TYPE]           = USB_DT_USB_SS_CAP_SIZE,
965 	[USB_SSP_CAP_TYPE]          = USB_DT_USB_SSP_CAP_SIZE(1),
966 	[CONTAINER_ID_TYPE]         = USB_DT_USB_SS_CONTN_ID_SIZE,
967 	[USB_PTM_CAP_TYPE]          = USB_DT_USB_PTM_ID_SIZE,
968 };
969 
970 /* Get BOS descriptor set */
971 int usb_get_bos_descriptor(struct usb_device *dev)
972 {
973 	struct device *ddev = &dev->dev;
974 	struct usb_bos_descriptor *bos;
975 	struct usb_dev_cap_header *cap;
976 	struct usb_ssp_cap_descriptor *ssp_cap;
977 	unsigned char *buffer, *buffer0;
978 	int length, total_len, num, i, ssac;
979 	__u8 cap_type;
980 	int ret;
981 
982 	bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);
983 	if (!bos)
984 		return -ENOMEM;
985 
986 	/* Get BOS descriptor */
987 	ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);
988 	if (ret < USB_DT_BOS_SIZE || bos->bLength < USB_DT_BOS_SIZE) {
989 		dev_err(ddev, "unable to get BOS descriptor or descriptor too short\n");
990 		if (ret >= 0)
991 			ret = -ENOMSG;
992 		kfree(bos);
993 		return ret;
994 	}
995 
996 	length = bos->bLength;
997 	total_len = le16_to_cpu(bos->wTotalLength);
998 	num = bos->bNumDeviceCaps;
999 	kfree(bos);
1000 	if (total_len < length)
1001 		return -EINVAL;
1002 
1003 	dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);
1004 	if (!dev->bos)
1005 		return -ENOMEM;
1006 
1007 	/* Now let's get the whole BOS descriptor set */
1008 	buffer = kzalloc(total_len, GFP_KERNEL);
1009 	if (!buffer) {
1010 		ret = -ENOMEM;
1011 		goto err;
1012 	}
1013 	dev->bos->desc = (struct usb_bos_descriptor *)buffer;
1014 
1015 	ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);
1016 	if (ret < total_len) {
1017 		dev_err(ddev, "unable to get BOS descriptor set\n");
1018 		if (ret >= 0)
1019 			ret = -ENOMSG;
1020 		goto err;
1021 	}
1022 
1023 	buffer0 = buffer;
1024 	total_len -= length;
1025 	buffer += length;
1026 
1027 	for (i = 0; i < num; i++) {
1028 		cap = (struct usb_dev_cap_header *)buffer;
1029 
1030 		if (total_len < sizeof(*cap) || total_len < cap->bLength) {
1031 			dev->bos->desc->bNumDeviceCaps = i;
1032 			break;
1033 		}
1034 		cap_type = cap->bDevCapabilityType;
1035 		length = cap->bLength;
1036 		if (bos_desc_len[cap_type] && length < bos_desc_len[cap_type]) {
1037 			dev->bos->desc->bNumDeviceCaps = i;
1038 			break;
1039 		}
1040 
1041 		if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {
1042 			dev_warn(ddev, "descriptor type invalid, skip\n");
1043 			continue;
1044 		}
1045 
1046 		switch (cap_type) {
1047 		case USB_CAP_TYPE_WIRELESS_USB:
1048 			/* Wireless USB cap descriptor is handled by wusb */
1049 			break;
1050 		case USB_CAP_TYPE_EXT:
1051 			dev->bos->ext_cap =
1052 				(struct usb_ext_cap_descriptor *)buffer;
1053 			break;
1054 		case USB_SS_CAP_TYPE:
1055 			dev->bos->ss_cap =
1056 				(struct usb_ss_cap_descriptor *)buffer;
1057 			break;
1058 		case USB_SSP_CAP_TYPE:
1059 			ssp_cap = (struct usb_ssp_cap_descriptor *)buffer;
1060 			ssac = (le32_to_cpu(ssp_cap->bmAttributes) &
1061 				USB_SSP_SUBLINK_SPEED_ATTRIBS);
1062 			if (length >= USB_DT_USB_SSP_CAP_SIZE(ssac))
1063 				dev->bos->ssp_cap = ssp_cap;
1064 			break;
1065 		case CONTAINER_ID_TYPE:
1066 			dev->bos->ss_id =
1067 				(struct usb_ss_container_id_descriptor *)buffer;
1068 			break;
1069 		case USB_PTM_CAP_TYPE:
1070 			dev->bos->ptm_cap =
1071 				(struct usb_ptm_cap_descriptor *)buffer;
1072 		default:
1073 			break;
1074 		}
1075 
1076 		total_len -= length;
1077 		buffer += length;
1078 	}
1079 	dev->bos->desc->wTotalLength = cpu_to_le16(buffer - buffer0);
1080 
1081 	return 0;
1082 
1083 err:
1084 	usb_release_bos_descriptor(dev);
1085 	return ret;
1086 }
1087