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