xref: /openbmc/linux/drivers/usb/core/config.c (revision b830f94f)
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 int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
207     int asnum, struct usb_host_interface *ifp, int num_ep,
208     unsigned char *buffer, int size)
209 {
210 	unsigned char *buffer0 = buffer;
211 	struct usb_endpoint_descriptor *d;
212 	struct usb_host_endpoint *endpoint;
213 	int n, i, j, retval;
214 	unsigned int maxp;
215 	const unsigned short *maxpacket_maxes;
216 
217 	d = (struct usb_endpoint_descriptor *) buffer;
218 	buffer += d->bLength;
219 	size -= d->bLength;
220 
221 	if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
222 		n = USB_DT_ENDPOINT_AUDIO_SIZE;
223 	else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
224 		n = USB_DT_ENDPOINT_SIZE;
225 	else {
226 		dev_warn(ddev, "config %d interface %d altsetting %d has an "
227 		    "invalid endpoint descriptor of length %d, skipping\n",
228 		    cfgno, inum, asnum, d->bLength);
229 		goto skip_to_next_endpoint_or_interface_descriptor;
230 	}
231 
232 	i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
233 	if (i >= 16 || i == 0) {
234 		dev_warn(ddev, "config %d interface %d altsetting %d has an "
235 		    "invalid endpoint with address 0x%X, skipping\n",
236 		    cfgno, inum, asnum, d->bEndpointAddress);
237 		goto skip_to_next_endpoint_or_interface_descriptor;
238 	}
239 
240 	/* Only store as many endpoints as we have room for */
241 	if (ifp->desc.bNumEndpoints >= num_ep)
242 		goto skip_to_next_endpoint_or_interface_descriptor;
243 
244 	/* Check for duplicate endpoint addresses */
245 	for (i = 0; i < ifp->desc.bNumEndpoints; ++i) {
246 		if (ifp->endpoint[i].desc.bEndpointAddress ==
247 		    d->bEndpointAddress) {
248 			dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
249 			    cfgno, inum, asnum, d->bEndpointAddress);
250 			goto skip_to_next_endpoint_or_interface_descriptor;
251 		}
252 	}
253 
254 	endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
255 	++ifp->desc.bNumEndpoints;
256 
257 	memcpy(&endpoint->desc, d, n);
258 	INIT_LIST_HEAD(&endpoint->urb_list);
259 
260 	/*
261 	 * Fix up bInterval values outside the legal range.
262 	 * Use 10 or 8 ms if no proper value can be guessed.
263 	 */
264 	i = 0;		/* i = min, j = max, n = default */
265 	j = 255;
266 	if (usb_endpoint_xfer_int(d)) {
267 		i = 1;
268 		switch (to_usb_device(ddev)->speed) {
269 		case USB_SPEED_SUPER_PLUS:
270 		case USB_SPEED_SUPER:
271 		case USB_SPEED_HIGH:
272 			/*
273 			 * Many device manufacturers are using full-speed
274 			 * bInterval values in high-speed interrupt endpoint
275 			 * descriptors. Try to fix those and fall back to an
276 			 * 8-ms default value otherwise.
277 			 */
278 			n = fls(d->bInterval*8);
279 			if (n == 0)
280 				n = 7;	/* 8 ms = 2^(7-1) uframes */
281 			j = 16;
282 
283 			/*
284 			 * Adjust bInterval for quirked devices.
285 			 */
286 			/*
287 			 * This quirk fixes bIntervals reported in ms.
288 			 */
289 			if (to_usb_device(ddev)->quirks &
290 				USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
291 				n = clamp(fls(d->bInterval) + 3, i, j);
292 				i = j = n;
293 			}
294 			/*
295 			 * This quirk fixes bIntervals reported in
296 			 * linear microframes.
297 			 */
298 			if (to_usb_device(ddev)->quirks &
299 				USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
300 				n = clamp(fls(d->bInterval), i, j);
301 				i = j = n;
302 			}
303 			break;
304 		default:		/* USB_SPEED_FULL or _LOW */
305 			/*
306 			 * For low-speed, 10 ms is the official minimum.
307 			 * But some "overclocked" devices might want faster
308 			 * polling so we'll allow it.
309 			 */
310 			n = 10;
311 			break;
312 		}
313 	} else if (usb_endpoint_xfer_isoc(d)) {
314 		i = 1;
315 		j = 16;
316 		switch (to_usb_device(ddev)->speed) {
317 		case USB_SPEED_HIGH:
318 			n = 7;		/* 8 ms = 2^(7-1) uframes */
319 			break;
320 		default:		/* USB_SPEED_FULL */
321 			n = 4;		/* 8 ms = 2^(4-1) frames */
322 			break;
323 		}
324 	}
325 	if (d->bInterval < i || d->bInterval > j) {
326 		dev_warn(ddev, "config %d interface %d altsetting %d "
327 		    "endpoint 0x%X has an invalid bInterval %d, "
328 		    "changing to %d\n",
329 		    cfgno, inum, asnum,
330 		    d->bEndpointAddress, d->bInterval, n);
331 		endpoint->desc.bInterval = n;
332 	}
333 
334 	/* Some buggy low-speed devices have Bulk endpoints, which is
335 	 * explicitly forbidden by the USB spec.  In an attempt to make
336 	 * them usable, we will try treating them as Interrupt endpoints.
337 	 */
338 	if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
339 			usb_endpoint_xfer_bulk(d)) {
340 		dev_warn(ddev, "config %d interface %d altsetting %d "
341 		    "endpoint 0x%X is Bulk; changing to Interrupt\n",
342 		    cfgno, inum, asnum, d->bEndpointAddress);
343 		endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
344 		endpoint->desc.bInterval = 1;
345 		if (usb_endpoint_maxp(&endpoint->desc) > 8)
346 			endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
347 	}
348 
349 	/* Validate the wMaxPacketSize field */
350 	maxp = usb_endpoint_maxp(&endpoint->desc);
351 
352 	/* Find the highest legal maxpacket size for this endpoint */
353 	i = 0;		/* additional transactions per microframe */
354 	switch (to_usb_device(ddev)->speed) {
355 	case USB_SPEED_LOW:
356 		maxpacket_maxes = low_speed_maxpacket_maxes;
357 		break;
358 	case USB_SPEED_FULL:
359 		maxpacket_maxes = full_speed_maxpacket_maxes;
360 		break;
361 	case USB_SPEED_HIGH:
362 		/* Bits 12..11 are allowed only for HS periodic endpoints */
363 		if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
364 			i = maxp & (BIT(12) | BIT(11));
365 			maxp &= ~i;
366 		}
367 		/* fallthrough */
368 	default:
369 		maxpacket_maxes = high_speed_maxpacket_maxes;
370 		break;
371 	case USB_SPEED_SUPER:
372 	case USB_SPEED_SUPER_PLUS:
373 		maxpacket_maxes = super_speed_maxpacket_maxes;
374 		break;
375 	}
376 	j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
377 
378 	if (maxp > j) {
379 		dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
380 		    cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
381 		maxp = j;
382 		endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
383 	}
384 
385 	/*
386 	 * Some buggy high speed devices have bulk endpoints using
387 	 * maxpacket sizes other than 512.  High speed HCDs may not
388 	 * be able to handle that particular bug, so let's warn...
389 	 */
390 	if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
391 			&& usb_endpoint_xfer_bulk(d)) {
392 		if (maxp != 512)
393 			dev_warn(ddev, "config %d interface %d altsetting %d "
394 				"bulk endpoint 0x%X has invalid maxpacket %d\n",
395 				cfgno, inum, asnum, d->bEndpointAddress,
396 				maxp);
397 	}
398 
399 	/* Parse a possible SuperSpeed endpoint companion descriptor */
400 	if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
401 		usb_parse_ss_endpoint_companion(ddev, cfgno,
402 				inum, asnum, endpoint, buffer, size);
403 
404 	/* Skip over any Class Specific or Vendor Specific descriptors;
405 	 * find the next endpoint or interface descriptor */
406 	endpoint->extra = buffer;
407 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
408 			USB_DT_INTERFACE, &n);
409 	endpoint->extralen = i;
410 	retval = buffer - buffer0 + i;
411 	if (n > 0)
412 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
413 		    n, plural(n), "endpoint");
414 	return retval;
415 
416 skip_to_next_endpoint_or_interface_descriptor:
417 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
418 	    USB_DT_INTERFACE, NULL);
419 	return buffer - buffer0 + i;
420 }
421 
422 void usb_release_interface_cache(struct kref *ref)
423 {
424 	struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
425 	int j;
426 
427 	for (j = 0; j < intfc->num_altsetting; j++) {
428 		struct usb_host_interface *alt = &intfc->altsetting[j];
429 
430 		kfree(alt->endpoint);
431 		kfree(alt->string);
432 	}
433 	kfree(intfc);
434 }
435 
436 static int usb_parse_interface(struct device *ddev, int cfgno,
437     struct usb_host_config *config, unsigned char *buffer, int size,
438     u8 inums[], u8 nalts[])
439 {
440 	unsigned char *buffer0 = buffer;
441 	struct usb_interface_descriptor	*d;
442 	int inum, asnum;
443 	struct usb_interface_cache *intfc;
444 	struct usb_host_interface *alt;
445 	int i, n;
446 	int len, retval;
447 	int num_ep, num_ep_orig;
448 
449 	d = (struct usb_interface_descriptor *) buffer;
450 	buffer += d->bLength;
451 	size -= d->bLength;
452 
453 	if (d->bLength < USB_DT_INTERFACE_SIZE)
454 		goto skip_to_next_interface_descriptor;
455 
456 	/* Which interface entry is this? */
457 	intfc = NULL;
458 	inum = d->bInterfaceNumber;
459 	for (i = 0; i < config->desc.bNumInterfaces; ++i) {
460 		if (inums[i] == inum) {
461 			intfc = config->intf_cache[i];
462 			break;
463 		}
464 	}
465 	if (!intfc || intfc->num_altsetting >= nalts[i])
466 		goto skip_to_next_interface_descriptor;
467 
468 	/* Check for duplicate altsetting entries */
469 	asnum = d->bAlternateSetting;
470 	for ((i = 0, alt = &intfc->altsetting[0]);
471 	      i < intfc->num_altsetting;
472 	     (++i, ++alt)) {
473 		if (alt->desc.bAlternateSetting == asnum) {
474 			dev_warn(ddev, "Duplicate descriptor for config %d "
475 			    "interface %d altsetting %d, skipping\n",
476 			    cfgno, inum, asnum);
477 			goto skip_to_next_interface_descriptor;
478 		}
479 	}
480 
481 	++intfc->num_altsetting;
482 	memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
483 
484 	/* Skip over any Class Specific or Vendor Specific descriptors;
485 	 * find the first endpoint or interface descriptor */
486 	alt->extra = buffer;
487 	i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
488 	    USB_DT_INTERFACE, &n);
489 	alt->extralen = i;
490 	if (n > 0)
491 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
492 		    n, plural(n), "interface");
493 	buffer += i;
494 	size -= i;
495 
496 	/* Allocate space for the right(?) number of endpoints */
497 	num_ep = num_ep_orig = alt->desc.bNumEndpoints;
498 	alt->desc.bNumEndpoints = 0;		/* Use as a counter */
499 	if (num_ep > USB_MAXENDPOINTS) {
500 		dev_warn(ddev, "too many endpoints for config %d interface %d "
501 		    "altsetting %d: %d, using maximum allowed: %d\n",
502 		    cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
503 		num_ep = USB_MAXENDPOINTS;
504 	}
505 
506 	if (num_ep > 0) {
507 		/* Can't allocate 0 bytes */
508 		len = sizeof(struct usb_host_endpoint) * num_ep;
509 		alt->endpoint = kzalloc(len, GFP_KERNEL);
510 		if (!alt->endpoint)
511 			return -ENOMEM;
512 	}
513 
514 	/* Parse all the endpoint descriptors */
515 	n = 0;
516 	while (size > 0) {
517 		if (((struct usb_descriptor_header *) buffer)->bDescriptorType
518 		     == USB_DT_INTERFACE)
519 			break;
520 		retval = usb_parse_endpoint(ddev, cfgno, inum, asnum, alt,
521 		    num_ep, buffer, size);
522 		if (retval < 0)
523 			return retval;
524 		++n;
525 
526 		buffer += retval;
527 		size -= retval;
528 	}
529 
530 	if (n != num_ep_orig)
531 		dev_warn(ddev, "config %d interface %d altsetting %d has %d "
532 		    "endpoint descriptor%s, different from the interface "
533 		    "descriptor's value: %d\n",
534 		    cfgno, inum, asnum, n, plural(n), num_ep_orig);
535 	return buffer - buffer0;
536 
537 skip_to_next_interface_descriptor:
538 	i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
539 	    USB_DT_INTERFACE, NULL);
540 	return buffer - buffer0 + i;
541 }
542 
543 static int usb_parse_configuration(struct usb_device *dev, int cfgidx,
544     struct usb_host_config *config, unsigned char *buffer, int size)
545 {
546 	struct device *ddev = &dev->dev;
547 	unsigned char *buffer0 = buffer;
548 	int cfgno;
549 	int nintf, nintf_orig;
550 	int i, j, n;
551 	struct usb_interface_cache *intfc;
552 	unsigned char *buffer2;
553 	int size2;
554 	struct usb_descriptor_header *header;
555 	int retval;
556 	u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
557 	unsigned iad_num = 0;
558 
559 	memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
560 	nintf = nintf_orig = config->desc.bNumInterfaces;
561 	config->desc.bNumInterfaces = 0;	// Adjusted later
562 
563 	if (config->desc.bDescriptorType != USB_DT_CONFIG ||
564 	    config->desc.bLength < USB_DT_CONFIG_SIZE ||
565 	    config->desc.bLength > size) {
566 		dev_err(ddev, "invalid descriptor for config index %d: "
567 		    "type = 0x%X, length = %d\n", cfgidx,
568 		    config->desc.bDescriptorType, config->desc.bLength);
569 		return -EINVAL;
570 	}
571 	cfgno = config->desc.bConfigurationValue;
572 
573 	buffer += config->desc.bLength;
574 	size -= config->desc.bLength;
575 
576 	if (nintf > USB_MAXINTERFACES) {
577 		dev_warn(ddev, "config %d has too many interfaces: %d, "
578 		    "using maximum allowed: %d\n",
579 		    cfgno, nintf, USB_MAXINTERFACES);
580 		nintf = USB_MAXINTERFACES;
581 	}
582 
583 	/* Go through the descriptors, checking their length and counting the
584 	 * number of altsettings for each interface */
585 	n = 0;
586 	for ((buffer2 = buffer, size2 = size);
587 	      size2 > 0;
588 	     (buffer2 += header->bLength, size2 -= header->bLength)) {
589 
590 		if (size2 < sizeof(struct usb_descriptor_header)) {
591 			dev_warn(ddev, "config %d descriptor has %d excess "
592 			    "byte%s, ignoring\n",
593 			    cfgno, size2, plural(size2));
594 			break;
595 		}
596 
597 		header = (struct usb_descriptor_header *) buffer2;
598 		if ((header->bLength > size2) || (header->bLength < 2)) {
599 			dev_warn(ddev, "config %d has an invalid descriptor "
600 			    "of length %d, skipping remainder of the config\n",
601 			    cfgno, header->bLength);
602 			break;
603 		}
604 
605 		if (header->bDescriptorType == USB_DT_INTERFACE) {
606 			struct usb_interface_descriptor *d;
607 			int inum;
608 
609 			d = (struct usb_interface_descriptor *) header;
610 			if (d->bLength < USB_DT_INTERFACE_SIZE) {
611 				dev_warn(ddev, "config %d has an invalid "
612 				    "interface descriptor of length %d, "
613 				    "skipping\n", cfgno, d->bLength);
614 				continue;
615 			}
616 
617 			inum = d->bInterfaceNumber;
618 
619 			if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
620 			    n >= nintf_orig) {
621 				dev_warn(ddev, "config %d has more interface "
622 				    "descriptors, than it declares in "
623 				    "bNumInterfaces, ignoring interface "
624 				    "number: %d\n", cfgno, inum);
625 				continue;
626 			}
627 
628 			if (inum >= nintf_orig)
629 				dev_warn(ddev, "config %d has an invalid "
630 				    "interface number: %d but max is %d\n",
631 				    cfgno, inum, nintf_orig - 1);
632 
633 			/* Have we already encountered this interface?
634 			 * Count its altsettings */
635 			for (i = 0; i < n; ++i) {
636 				if (inums[i] == inum)
637 					break;
638 			}
639 			if (i < n) {
640 				if (nalts[i] < 255)
641 					++nalts[i];
642 			} else if (n < USB_MAXINTERFACES) {
643 				inums[n] = inum;
644 				nalts[n] = 1;
645 				++n;
646 			}
647 
648 		} else if (header->bDescriptorType ==
649 				USB_DT_INTERFACE_ASSOCIATION) {
650 			struct usb_interface_assoc_descriptor *d;
651 
652 			d = (struct usb_interface_assoc_descriptor *)header;
653 			if (d->bLength < USB_DT_INTERFACE_ASSOCIATION_SIZE) {
654 				dev_warn(ddev,
655 					 "config %d has an invalid interface association descriptor of length %d, skipping\n",
656 					 cfgno, d->bLength);
657 				continue;
658 			}
659 
660 			if (iad_num == USB_MAXIADS) {
661 				dev_warn(ddev, "found more Interface "
662 					       "Association Descriptors "
663 					       "than allocated for in "
664 					       "configuration %d\n", cfgno);
665 			} else {
666 				config->intf_assoc[iad_num] = d;
667 				iad_num++;
668 			}
669 
670 		} else if (header->bDescriptorType == USB_DT_DEVICE ||
671 			    header->bDescriptorType == USB_DT_CONFIG)
672 			dev_warn(ddev, "config %d contains an unexpected "
673 			    "descriptor of type 0x%X, skipping\n",
674 			    cfgno, header->bDescriptorType);
675 
676 	}	/* for ((buffer2 = buffer, size2 = size); ...) */
677 	size = buffer2 - buffer;
678 	config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
679 
680 	if (n != nintf)
681 		dev_warn(ddev, "config %d has %d interface%s, different from "
682 		    "the descriptor's value: %d\n",
683 		    cfgno, n, plural(n), nintf_orig);
684 	else if (n == 0)
685 		dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
686 	config->desc.bNumInterfaces = nintf = n;
687 
688 	/* Check for missing interface numbers */
689 	for (i = 0; i < nintf; ++i) {
690 		for (j = 0; j < nintf; ++j) {
691 			if (inums[j] == i)
692 				break;
693 		}
694 		if (j >= nintf)
695 			dev_warn(ddev, "config %d has no interface number "
696 			    "%d\n", cfgno, i);
697 	}
698 
699 	/* Allocate the usb_interface_caches and altsetting arrays */
700 	for (i = 0; i < nintf; ++i) {
701 		j = nalts[i];
702 		if (j > USB_MAXALTSETTING) {
703 			dev_warn(ddev, "too many alternate settings for "
704 			    "config %d interface %d: %d, "
705 			    "using maximum allowed: %d\n",
706 			    cfgno, inums[i], j, USB_MAXALTSETTING);
707 			nalts[i] = j = USB_MAXALTSETTING;
708 		}
709 
710 		intfc = kzalloc(struct_size(intfc, altsetting, j), GFP_KERNEL);
711 		config->intf_cache[i] = intfc;
712 		if (!intfc)
713 			return -ENOMEM;
714 		kref_init(&intfc->ref);
715 	}
716 
717 	/* FIXME: parse the BOS descriptor */
718 
719 	/* Skip over any Class Specific or Vendor Specific descriptors;
720 	 * find the first interface descriptor */
721 	config->extra = buffer;
722 	i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
723 	    USB_DT_INTERFACE, &n);
724 	config->extralen = i;
725 	if (n > 0)
726 		dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
727 		    n, plural(n), "configuration");
728 	buffer += i;
729 	size -= i;
730 
731 	/* Parse all the interface/altsetting descriptors */
732 	while (size > 0) {
733 		retval = usb_parse_interface(ddev, cfgno, config,
734 		    buffer, size, inums, nalts);
735 		if (retval < 0)
736 			return retval;
737 
738 		buffer += retval;
739 		size -= retval;
740 	}
741 
742 	/* Check for missing altsettings */
743 	for (i = 0; i < nintf; ++i) {
744 		intfc = config->intf_cache[i];
745 		for (j = 0; j < intfc->num_altsetting; ++j) {
746 			for (n = 0; n < intfc->num_altsetting; ++n) {
747 				if (intfc->altsetting[n].desc.
748 				    bAlternateSetting == j)
749 					break;
750 			}
751 			if (n >= intfc->num_altsetting)
752 				dev_warn(ddev, "config %d interface %d has no "
753 				    "altsetting %d\n", cfgno, inums[i], j);
754 		}
755 	}
756 
757 	return 0;
758 }
759 
760 /* hub-only!! ... and only exported for reset/reinit path.
761  * otherwise used internally on disconnect/destroy path
762  */
763 void usb_destroy_configuration(struct usb_device *dev)
764 {
765 	int c, i;
766 
767 	if (!dev->config)
768 		return;
769 
770 	if (dev->rawdescriptors) {
771 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
772 			kfree(dev->rawdescriptors[i]);
773 
774 		kfree(dev->rawdescriptors);
775 		dev->rawdescriptors = NULL;
776 	}
777 
778 	for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
779 		struct usb_host_config *cf = &dev->config[c];
780 
781 		kfree(cf->string);
782 		for (i = 0; i < cf->desc.bNumInterfaces; i++) {
783 			if (cf->intf_cache[i])
784 				kref_put(&cf->intf_cache[i]->ref,
785 					  usb_release_interface_cache);
786 		}
787 	}
788 	kfree(dev->config);
789 	dev->config = NULL;
790 }
791 
792 
793 /*
794  * Get the USB config descriptors, cache and parse'em
795  *
796  * hub-only!! ... and only in reset path, or usb_new_device()
797  * (used by real hubs and virtual root hubs)
798  */
799 int usb_get_configuration(struct usb_device *dev)
800 {
801 	struct device *ddev = &dev->dev;
802 	int ncfg = dev->descriptor.bNumConfigurations;
803 	int result = -ENOMEM;
804 	unsigned int cfgno, length;
805 	unsigned char *bigbuffer;
806 	struct usb_config_descriptor *desc;
807 
808 	if (ncfg > USB_MAXCONFIG) {
809 		dev_warn(ddev, "too many configurations: %d, "
810 		    "using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
811 		dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
812 	}
813 
814 	if (ncfg < 1) {
815 		dev_err(ddev, "no configurations\n");
816 		return -EINVAL;
817 	}
818 
819 	length = ncfg * sizeof(struct usb_host_config);
820 	dev->config = kzalloc(length, GFP_KERNEL);
821 	if (!dev->config)
822 		goto err2;
823 
824 	length = ncfg * sizeof(char *);
825 	dev->rawdescriptors = kzalloc(length, GFP_KERNEL);
826 	if (!dev->rawdescriptors)
827 		goto err2;
828 
829 	desc = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
830 	if (!desc)
831 		goto err2;
832 
833 	for (cfgno = 0; cfgno < ncfg; cfgno++) {
834 		/* We grab just the first descriptor so we know how long
835 		 * the whole configuration is */
836 		result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
837 		    desc, USB_DT_CONFIG_SIZE);
838 		if (result < 0) {
839 			dev_err(ddev, "unable to read config index %d "
840 			    "descriptor/%s: %d\n", cfgno, "start", result);
841 			if (result != -EPIPE)
842 				goto err;
843 			dev_err(ddev, "chopping to %d config(s)\n", cfgno);
844 			dev->descriptor.bNumConfigurations = cfgno;
845 			break;
846 		} else if (result < 4) {
847 			dev_err(ddev, "config index %d descriptor too short "
848 			    "(expected %i, got %i)\n", cfgno,
849 			    USB_DT_CONFIG_SIZE, result);
850 			result = -EINVAL;
851 			goto err;
852 		}
853 		length = max((int) le16_to_cpu(desc->wTotalLength),
854 		    USB_DT_CONFIG_SIZE);
855 
856 		/* Now that we know the length, get the whole thing */
857 		bigbuffer = kmalloc(length, GFP_KERNEL);
858 		if (!bigbuffer) {
859 			result = -ENOMEM;
860 			goto err;
861 		}
862 
863 		if (dev->quirks & USB_QUIRK_DELAY_INIT)
864 			msleep(200);
865 
866 		result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
867 		    bigbuffer, length);
868 		if (result < 0) {
869 			dev_err(ddev, "unable to read config index %d "
870 			    "descriptor/%s\n", cfgno, "all");
871 			kfree(bigbuffer);
872 			goto err;
873 		}
874 		if (result < length) {
875 			dev_warn(ddev, "config index %d descriptor too short "
876 			    "(expected %i, got %i)\n", cfgno, length, result);
877 			length = result;
878 		}
879 
880 		dev->rawdescriptors[cfgno] = bigbuffer;
881 
882 		result = usb_parse_configuration(dev, cfgno,
883 		    &dev->config[cfgno], bigbuffer, length);
884 		if (result < 0) {
885 			++cfgno;
886 			goto err;
887 		}
888 	}
889 
890 err:
891 	kfree(desc);
892 	dev->descriptor.bNumConfigurations = cfgno;
893 err2:
894 	if (result == -ENOMEM)
895 		dev_err(ddev, "out of memory\n");
896 	return result;
897 }
898 
899 void usb_release_bos_descriptor(struct usb_device *dev)
900 {
901 	if (dev->bos) {
902 		kfree(dev->bos->desc);
903 		kfree(dev->bos);
904 		dev->bos = NULL;
905 	}
906 }
907 
908 static const __u8 bos_desc_len[256] = {
909 	[USB_CAP_TYPE_WIRELESS_USB] = USB_DT_USB_WIRELESS_CAP_SIZE,
910 	[USB_CAP_TYPE_EXT]          = USB_DT_USB_EXT_CAP_SIZE,
911 	[USB_SS_CAP_TYPE]           = USB_DT_USB_SS_CAP_SIZE,
912 	[USB_SSP_CAP_TYPE]          = USB_DT_USB_SSP_CAP_SIZE(1),
913 	[CONTAINER_ID_TYPE]         = USB_DT_USB_SS_CONTN_ID_SIZE,
914 	[USB_PTM_CAP_TYPE]          = USB_DT_USB_PTM_ID_SIZE,
915 };
916 
917 /* Get BOS descriptor set */
918 int usb_get_bos_descriptor(struct usb_device *dev)
919 {
920 	struct device *ddev = &dev->dev;
921 	struct usb_bos_descriptor *bos;
922 	struct usb_dev_cap_header *cap;
923 	struct usb_ssp_cap_descriptor *ssp_cap;
924 	unsigned char *buffer;
925 	int length, total_len, num, i, ssac;
926 	__u8 cap_type;
927 	int ret;
928 
929 	bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);
930 	if (!bos)
931 		return -ENOMEM;
932 
933 	/* Get BOS descriptor */
934 	ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);
935 	if (ret < USB_DT_BOS_SIZE || bos->bLength < USB_DT_BOS_SIZE) {
936 		dev_err(ddev, "unable to get BOS descriptor or descriptor too short\n");
937 		if (ret >= 0)
938 			ret = -ENOMSG;
939 		kfree(bos);
940 		return ret;
941 	}
942 
943 	length = bos->bLength;
944 	total_len = le16_to_cpu(bos->wTotalLength);
945 	num = bos->bNumDeviceCaps;
946 	kfree(bos);
947 	if (total_len < length)
948 		return -EINVAL;
949 
950 	dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);
951 	if (!dev->bos)
952 		return -ENOMEM;
953 
954 	/* Now let's get the whole BOS descriptor set */
955 	buffer = kzalloc(total_len, GFP_KERNEL);
956 	if (!buffer) {
957 		ret = -ENOMEM;
958 		goto err;
959 	}
960 	dev->bos->desc = (struct usb_bos_descriptor *)buffer;
961 
962 	ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);
963 	if (ret < total_len) {
964 		dev_err(ddev, "unable to get BOS descriptor set\n");
965 		if (ret >= 0)
966 			ret = -ENOMSG;
967 		goto err;
968 	}
969 	total_len -= length;
970 
971 	for (i = 0; i < num; i++) {
972 		buffer += length;
973 		cap = (struct usb_dev_cap_header *)buffer;
974 
975 		if (total_len < sizeof(*cap) || total_len < cap->bLength) {
976 			dev->bos->desc->bNumDeviceCaps = i;
977 			break;
978 		}
979 		cap_type = cap->bDevCapabilityType;
980 		length = cap->bLength;
981 		if (bos_desc_len[cap_type] && length < bos_desc_len[cap_type]) {
982 			dev->bos->desc->bNumDeviceCaps = i;
983 			break;
984 		}
985 
986 		total_len -= length;
987 
988 		if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {
989 			dev_warn(ddev, "descriptor type invalid, skip\n");
990 			continue;
991 		}
992 
993 		switch (cap_type) {
994 		case USB_CAP_TYPE_WIRELESS_USB:
995 			/* Wireless USB cap descriptor is handled by wusb */
996 			break;
997 		case USB_CAP_TYPE_EXT:
998 			dev->bos->ext_cap =
999 				(struct usb_ext_cap_descriptor *)buffer;
1000 			break;
1001 		case USB_SS_CAP_TYPE:
1002 			dev->bos->ss_cap =
1003 				(struct usb_ss_cap_descriptor *)buffer;
1004 			break;
1005 		case USB_SSP_CAP_TYPE:
1006 			ssp_cap = (struct usb_ssp_cap_descriptor *)buffer;
1007 			ssac = (le32_to_cpu(ssp_cap->bmAttributes) &
1008 				USB_SSP_SUBLINK_SPEED_ATTRIBS);
1009 			if (length >= USB_DT_USB_SSP_CAP_SIZE(ssac))
1010 				dev->bos->ssp_cap = ssp_cap;
1011 			break;
1012 		case CONTAINER_ID_TYPE:
1013 			dev->bos->ss_id =
1014 				(struct usb_ss_container_id_descriptor *)buffer;
1015 			break;
1016 		case USB_PTM_CAP_TYPE:
1017 			dev->bos->ptm_cap =
1018 				(struct usb_ptm_cap_descriptor *)buffer;
1019 		default:
1020 			break;
1021 		}
1022 	}
1023 
1024 	return 0;
1025 
1026 err:
1027 	usb_release_bos_descriptor(dev);
1028 	return ret;
1029 }
1030