xref: /freebsd/sys/dev/usb/template/usb_template.c (revision 4ed925457ab06e83238a5db33e89ccc94b99a713)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2007 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * This file contains sub-routines to build up USB descriptors from
29  * USB templates.
30  */
31 
32 #include <sys/stdint.h>
33 #include <sys/stddef.h>
34 #include <sys/param.h>
35 #include <sys/queue.h>
36 #include <sys/types.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/bus.h>
40 #include <sys/linker_set.h>
41 #include <sys/module.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/condvar.h>
45 #include <sys/sysctl.h>
46 #include <sys/sx.h>
47 #include <sys/unistd.h>
48 #include <sys/callout.h>
49 #include <sys/malloc.h>
50 #include <sys/priv.h>
51 
52 #include <dev/usb/usb.h>
53 #include <dev/usb/usbdi.h>
54 #include <dev/usb/usbdi_util.h>
55 #include "usbdevs.h"
56 
57 #include <dev/usb/usb_cdc.h>
58 #include <dev/usb/usb_core.h>
59 #include <dev/usb/usb_dynamic.h>
60 #include <dev/usb/usb_busdma.h>
61 #include <dev/usb/usb_process.h>
62 #include <dev/usb/usb_device.h>
63 
64 #define	USB_DEBUG_VAR usb_debug
65 #include <dev/usb/usb_debug.h>
66 
67 #include <dev/usb/usb_controller.h>
68 #include <dev/usb/usb_bus.h>
69 #include <dev/usb/template/usb_template.h>
70 
71 MODULE_DEPEND(usb_template, usb, 1, 1, 1);
72 MODULE_VERSION(usb_template, 1);
73 
74 /* function prototypes */
75 
76 static void	usb_make_raw_desc(struct usb_temp_setup *, const uint8_t *);
77 static void	usb_make_endpoint_desc(struct usb_temp_setup *,
78 		    const struct usb_temp_endpoint_desc *);
79 static void	usb_make_interface_desc(struct usb_temp_setup *,
80 		    const struct usb_temp_interface_desc *);
81 static void	usb_make_config_desc(struct usb_temp_setup *,
82 		    const struct usb_temp_config_desc *);
83 static void	usb_make_device_desc(struct usb_temp_setup *,
84 		    const struct usb_temp_device_desc *);
85 static uint8_t	usb_hw_ep_match(const struct usb_hw_ep_profile *, uint8_t,
86 		    uint8_t);
87 static uint8_t	usb_hw_ep_find_match(struct usb_hw_ep_scratch *,
88 		    struct usb_hw_ep_scratch_sub *, uint8_t);
89 static uint8_t	usb_hw_ep_get_needs(struct usb_hw_ep_scratch *, uint8_t,
90 		    uint8_t);
91 static usb_error_t usb_hw_ep_resolve(struct usb_device *,
92 		    struct usb_descriptor *);
93 static const struct usb_temp_device_desc *usb_temp_get_tdd(struct usb_device *);
94 static void	*usb_temp_get_device_desc(struct usb_device *);
95 static void	*usb_temp_get_qualifier_desc(struct usb_device *);
96 static void	*usb_temp_get_config_desc(struct usb_device *, uint16_t *,
97 		    uint8_t);
98 static const void *usb_temp_get_string_desc(struct usb_device *, uint16_t,
99 		    uint8_t);
100 static const void *usb_temp_get_vendor_desc(struct usb_device *,
101 		    const struct usb_device_request *);
102 static const void *usb_temp_get_hub_desc(struct usb_device *);
103 static usb_error_t usb_temp_get_desc(struct usb_device *,
104 		    struct usb_device_request *, const void **, uint16_t *);
105 static usb_error_t usb_temp_setup(struct usb_device *,
106 		    const struct usb_temp_device_desc *);
107 static void	usb_temp_unsetup(struct usb_device *);
108 static usb_error_t usb_temp_setup_by_index(struct usb_device *,
109 		    uint16_t index);
110 static void	usb_temp_init(void *);
111 
112 /*------------------------------------------------------------------------*
113  *	usb_make_raw_desc
114  *
115  * This function will insert a raw USB descriptor into the generated
116  * USB configuration.
117  *------------------------------------------------------------------------*/
118 static void
119 usb_make_raw_desc(struct usb_temp_setup *temp,
120     const uint8_t *raw)
121 {
122 	void *dst;
123 	uint8_t len;
124 
125 	/*
126          * The first byte of any USB descriptor gives the length.
127          */
128 	if (raw) {
129 		len = raw[0];
130 		if (temp->buf) {
131 			dst = USB_ADD_BYTES(temp->buf, temp->size);
132 			bcopy(raw, dst, len);
133 
134 			/* check if we have got a CDC union descriptor */
135 
136 			if ((raw[0] >= sizeof(struct usb_cdc_union_descriptor)) &&
137 			    (raw[1] == UDESC_CS_INTERFACE) &&
138 			    (raw[2] == UDESCSUB_CDC_UNION)) {
139 				struct usb_cdc_union_descriptor *ud = (void *)dst;
140 
141 				/* update the interface numbers */
142 
143 				ud->bMasterInterface +=
144 				    temp->bInterfaceNumber;
145 				ud->bSlaveInterface[0] +=
146 				    temp->bInterfaceNumber;
147 			}
148 		}
149 		temp->size += len;
150 	}
151 }
152 
153 /*------------------------------------------------------------------------*
154  *	usb_make_endpoint_desc
155  *
156  * This function will generate an USB endpoint descriptor from the
157  * given USB template endpoint descriptor, which will be inserted into
158  * the USB configuration.
159  *------------------------------------------------------------------------*/
160 static void
161 usb_make_endpoint_desc(struct usb_temp_setup *temp,
162     const struct usb_temp_endpoint_desc *ted)
163 {
164 	struct usb_endpoint_descriptor *ed;
165 	const void **rd;
166 	uint16_t old_size;
167 	uint16_t mps;
168 	uint8_t ea = 0;			/* Endpoint Address */
169 	uint8_t et = 0;			/* Endpiont Type */
170 
171 	/* Reserve memory */
172 	old_size = temp->size;
173 	temp->size += sizeof(*ed);
174 
175 	/* Scan all Raw Descriptors first */
176 
177 	rd = ted->ppRawDesc;
178 	if (rd) {
179 		while (*rd) {
180 			usb_make_raw_desc(temp, *rd);
181 			rd++;
182 		}
183 	}
184 	if (ted->pPacketSize == NULL) {
185 		/* not initialized */
186 		temp->err = USB_ERR_INVAL;
187 		return;
188 	}
189 	mps = ted->pPacketSize->mps[temp->usb_speed];
190 	if (mps == 0) {
191 		/* not initialized */
192 		temp->err = USB_ERR_INVAL;
193 		return;
194 	} else if (mps == UE_ZERO_MPS) {
195 		/* escape for Zero Max Packet Size */
196 		mps = 0;
197 	}
198 	ea = (ted->bEndpointAddress & (UE_ADDR | UE_DIR_IN | UE_DIR_OUT));
199 	et = (ted->bmAttributes & UE_XFERTYPE);
200 
201 	/*
202 	 * Fill out the real USB endpoint descriptor
203 	 * in case there is a buffer present:
204 	 */
205 	if (temp->buf) {
206 		ed = USB_ADD_BYTES(temp->buf, old_size);
207 		ed->bLength = sizeof(*ed);
208 		ed->bDescriptorType = UDESC_ENDPOINT;
209 		ed->bEndpointAddress = ea;
210 		ed->bmAttributes = ted->bmAttributes;
211 		USETW(ed->wMaxPacketSize, mps);
212 
213 		/* setup bInterval parameter */
214 
215 		if (ted->pIntervals &&
216 		    ted->pIntervals->bInterval[temp->usb_speed]) {
217 			ed->bInterval =
218 			    ted->pIntervals->bInterval[temp->usb_speed];
219 		} else {
220 			switch (et) {
221 			case UE_BULK:
222 			case UE_CONTROL:
223 				ed->bInterval = 0;	/* not used */
224 				break;
225 			case UE_INTERRUPT:
226 				switch (temp->usb_speed) {
227 				case USB_SPEED_LOW:
228 				case USB_SPEED_FULL:
229 					ed->bInterval = 1;	/* 1 ms */
230 					break;
231 				default:
232 					ed->bInterval = 8;	/* 8*125 us */
233 					break;
234 				}
235 				break;
236 			default:	/* UE_ISOCHRONOUS */
237 				switch (temp->usb_speed) {
238 				case USB_SPEED_LOW:
239 				case USB_SPEED_FULL:
240 					ed->bInterval = 1;	/* 1 ms */
241 					break;
242 				default:
243 					ed->bInterval = 1;	/* 125 us */
244 					break;
245 				}
246 				break;
247 			}
248 		}
249 	}
250 	temp->bNumEndpoints++;
251 }
252 
253 /*------------------------------------------------------------------------*
254  *	usb_make_interface_desc
255  *
256  * This function will generate an USB interface descriptor from the
257  * given USB template interface descriptor, which will be inserted
258  * into the USB configuration.
259  *------------------------------------------------------------------------*/
260 static void
261 usb_make_interface_desc(struct usb_temp_setup *temp,
262     const struct usb_temp_interface_desc *tid)
263 {
264 	struct usb_interface_descriptor *id;
265 	const struct usb_temp_endpoint_desc **ted;
266 	const void **rd;
267 	uint16_t old_size;
268 
269 	/* Reserve memory */
270 
271 	old_size = temp->size;
272 	temp->size += sizeof(*id);
273 
274 	/* Update interface and alternate interface numbers */
275 
276 	if (tid->isAltInterface == 0) {
277 		temp->bAlternateSetting = 0;
278 		temp->bInterfaceNumber++;
279 	} else {
280 		temp->bAlternateSetting++;
281 	}
282 
283 	/* Scan all Raw Descriptors first */
284 
285 	rd = tid->ppRawDesc;
286 
287 	if (rd) {
288 		while (*rd) {
289 			usb_make_raw_desc(temp, *rd);
290 			rd++;
291 		}
292 	}
293 	/* Reset some counters */
294 
295 	temp->bNumEndpoints = 0;
296 
297 	/* Scan all Endpoint Descriptors second */
298 
299 	ted = tid->ppEndpoints;
300 	if (ted) {
301 		while (*ted) {
302 			usb_make_endpoint_desc(temp, *ted);
303 			ted++;
304 		}
305 	}
306 	/*
307 	 * Fill out the real USB interface descriptor
308 	 * in case there is a buffer present:
309 	 */
310 	if (temp->buf) {
311 		id = USB_ADD_BYTES(temp->buf, old_size);
312 		id->bLength = sizeof(*id);
313 		id->bDescriptorType = UDESC_INTERFACE;
314 		id->bInterfaceNumber = temp->bInterfaceNumber;
315 		id->bAlternateSetting = temp->bAlternateSetting;
316 		id->bNumEndpoints = temp->bNumEndpoints;
317 		id->bInterfaceClass = tid->bInterfaceClass;
318 		id->bInterfaceSubClass = tid->bInterfaceSubClass;
319 		id->bInterfaceProtocol = tid->bInterfaceProtocol;
320 		id->iInterface = tid->iInterface;
321 	}
322 }
323 
324 /*------------------------------------------------------------------------*
325  *	usb_make_config_desc
326  *
327  * This function will generate an USB config descriptor from the given
328  * USB template config descriptor, which will be inserted into the USB
329  * configuration.
330  *------------------------------------------------------------------------*/
331 static void
332 usb_make_config_desc(struct usb_temp_setup *temp,
333     const struct usb_temp_config_desc *tcd)
334 {
335 	struct usb_config_descriptor *cd;
336 	const struct usb_temp_interface_desc **tid;
337 	uint16_t old_size;
338 
339 	/* Reserve memory */
340 
341 	old_size = temp->size;
342 	temp->size += sizeof(*cd);
343 
344 	/* Reset some counters */
345 
346 	temp->bInterfaceNumber = 0 - 1;
347 	temp->bAlternateSetting = 0;
348 
349 	/* Scan all the USB interfaces */
350 
351 	tid = tcd->ppIfaceDesc;
352 	if (tid) {
353 		while (*tid) {
354 			usb_make_interface_desc(temp, *tid);
355 			tid++;
356 		}
357 	}
358 	/*
359 	 * Fill out the real USB config descriptor
360 	 * in case there is a buffer present:
361 	 */
362 	if (temp->buf) {
363 		cd = USB_ADD_BYTES(temp->buf, old_size);
364 
365 		/* compute total size */
366 		old_size = temp->size - old_size;
367 
368 		cd->bLength = sizeof(*cd);
369 		cd->bDescriptorType = UDESC_CONFIG;
370 		USETW(cd->wTotalLength, old_size);
371 		cd->bNumInterface = temp->bInterfaceNumber + 1;
372 		cd->bConfigurationValue = temp->bConfigurationValue;
373 		cd->iConfiguration = tcd->iConfiguration;
374 		cd->bmAttributes = tcd->bmAttributes;
375 		cd->bMaxPower = tcd->bMaxPower;
376 		cd->bmAttributes |= (UC_REMOTE_WAKEUP | UC_BUS_POWERED);
377 
378 		if (temp->self_powered) {
379 			cd->bmAttributes |= UC_SELF_POWERED;
380 		} else {
381 			cd->bmAttributes &= ~UC_SELF_POWERED;
382 		}
383 	}
384 }
385 
386 /*------------------------------------------------------------------------*
387  *	usb_make_device_desc
388  *
389  * This function will generate an USB device descriptor from the
390  * given USB template device descriptor.
391  *------------------------------------------------------------------------*/
392 static void
393 usb_make_device_desc(struct usb_temp_setup *temp,
394     const struct usb_temp_device_desc *tdd)
395 {
396 	struct usb_temp_data *utd;
397 	const struct usb_temp_config_desc **tcd;
398 	uint16_t old_size;
399 
400 	/* Reserve memory */
401 
402 	old_size = temp->size;
403 	temp->size += sizeof(*utd);
404 
405 	/* Scan all the USB configs */
406 
407 	temp->bConfigurationValue = 1;
408 	tcd = tdd->ppConfigDesc;
409 	if (tcd) {
410 		while (*tcd) {
411 			usb_make_config_desc(temp, *tcd);
412 			temp->bConfigurationValue++;
413 			tcd++;
414 		}
415 	}
416 	/*
417 	 * Fill out the real USB device descriptor
418 	 * in case there is a buffer present:
419 	 */
420 
421 	if (temp->buf) {
422 		utd = USB_ADD_BYTES(temp->buf, old_size);
423 
424 		/* Store a pointer to our template device descriptor */
425 		utd->tdd = tdd;
426 
427 		/* Fill out USB device descriptor */
428 		utd->udd.bLength = sizeof(utd->udd);
429 		utd->udd.bDescriptorType = UDESC_DEVICE;
430 		utd->udd.bDeviceClass = tdd->bDeviceClass;
431 		utd->udd.bDeviceSubClass = tdd->bDeviceSubClass;
432 		utd->udd.bDeviceProtocol = tdd->bDeviceProtocol;
433 		USETW(utd->udd.idVendor, tdd->idVendor);
434 		USETW(utd->udd.idProduct, tdd->idProduct);
435 		USETW(utd->udd.bcdDevice, tdd->bcdDevice);
436 		utd->udd.iManufacturer = tdd->iManufacturer;
437 		utd->udd.iProduct = tdd->iProduct;
438 		utd->udd.iSerialNumber = tdd->iSerialNumber;
439 		utd->udd.bNumConfigurations = temp->bConfigurationValue - 1;
440 
441 		/*
442 		 * Fill out the USB device qualifier. Pretend that we
443 		 * don't support any other speeds by setting
444 		 * "bNumConfigurations" equal to zero. That saves us
445 		 * generating an extra set of configuration
446 		 * descriptors.
447 		 */
448 		utd->udq.bLength = sizeof(utd->udq);
449 		utd->udq.bDescriptorType = UDESC_DEVICE_QUALIFIER;
450 		utd->udq.bDeviceClass = tdd->bDeviceClass;
451 		utd->udq.bDeviceSubClass = tdd->bDeviceSubClass;
452 		utd->udq.bDeviceProtocol = tdd->bDeviceProtocol;
453 		utd->udq.bNumConfigurations = 0;
454 		USETW(utd->udq.bcdUSB, 0x0200);
455 		utd->udq.bMaxPacketSize0 = 0;
456 
457 		switch (temp->usb_speed) {
458 		case USB_SPEED_LOW:
459 			USETW(utd->udd.bcdUSB, 0x0110);
460 			utd->udd.bMaxPacketSize = 8;
461 			break;
462 		case USB_SPEED_FULL:
463 			USETW(utd->udd.bcdUSB, 0x0110);
464 			utd->udd.bMaxPacketSize = 32;
465 			break;
466 		case USB_SPEED_HIGH:
467 			USETW(utd->udd.bcdUSB, 0x0200);
468 			utd->udd.bMaxPacketSize = 64;
469 			break;
470 		case USB_SPEED_VARIABLE:
471 			USETW(utd->udd.bcdUSB, 0x0250);
472 			utd->udd.bMaxPacketSize = 255;	/* 512 bytes */
473 			break;
474 		default:
475 			temp->err = USB_ERR_INVAL;
476 			break;
477 		}
478 	}
479 }
480 
481 /*------------------------------------------------------------------------*
482  *	usb_hw_ep_match
483  *
484  * Return values:
485  *    0: The endpoint profile does not match the criterias
486  * Else: The endpoint profile matches the criterias
487  *------------------------------------------------------------------------*/
488 static uint8_t
489 usb_hw_ep_match(const struct usb_hw_ep_profile *pf,
490     uint8_t ep_type, uint8_t ep_dir_in)
491 {
492 	if (ep_type == UE_CONTROL) {
493 		/* special */
494 		return (pf->support_control);
495 	}
496 	if ((pf->support_in && ep_dir_in) ||
497 	    (pf->support_out && !ep_dir_in)) {
498 		if ((pf->support_interrupt && (ep_type == UE_INTERRUPT)) ||
499 		    (pf->support_isochronous && (ep_type == UE_ISOCHRONOUS)) ||
500 		    (pf->support_bulk && (ep_type == UE_BULK))) {
501 			return (1);
502 		}
503 	}
504 	return (0);
505 }
506 
507 /*------------------------------------------------------------------------*
508  *	usb_hw_ep_find_match
509  *
510  * This function is used to find the best matching endpoint profile
511  * for and endpoint belonging to an USB descriptor.
512  *
513  * Return values:
514  *    0: Success. Got a match.
515  * Else: Failure. No match.
516  *------------------------------------------------------------------------*/
517 static uint8_t
518 usb_hw_ep_find_match(struct usb_hw_ep_scratch *ues,
519     struct usb_hw_ep_scratch_sub *ep, uint8_t is_simplex)
520 {
521 	const struct usb_hw_ep_profile *pf;
522 	uint16_t distance;
523 	uint16_t temp;
524 	uint16_t max_frame_size;
525 	uint8_t n;
526 	uint8_t best_n;
527 	uint8_t dir_in;
528 	uint8_t dir_out;
529 
530 	distance = 0xFFFF;
531 	best_n = 0;
532 
533 	if ((!ep->needs_in) && (!ep->needs_out)) {
534 		return (0);		/* we are done */
535 	}
536 	if (ep->needs_ep_type == UE_CONTROL) {
537 		dir_in = 1;
538 		dir_out = 1;
539 	} else {
540 		if (ep->needs_in) {
541 			dir_in = 1;
542 			dir_out = 0;
543 		} else {
544 			dir_in = 0;
545 			dir_out = 1;
546 		}
547 	}
548 
549 	for (n = 1; n != (USB_EP_MAX / 2); n++) {
550 
551 		/* get HW endpoint profile */
552 		(ues->methods->get_hw_ep_profile) (ues->udev, &pf, n);
553 		if (pf == NULL) {
554 			/* end of profiles */
555 			break;
556 		}
557 		/* check if IN-endpoint is reserved */
558 		if (dir_in || pf->is_simplex) {
559 			if (ues->bmInAlloc[n / 8] & (1 << (n % 8))) {
560 				/* mismatch */
561 				continue;
562 			}
563 		}
564 		/* check if OUT-endpoint is reserved */
565 		if (dir_out || pf->is_simplex) {
566 			if (ues->bmOutAlloc[n / 8] & (1 << (n % 8))) {
567 				/* mismatch */
568 				continue;
569 			}
570 		}
571 		/* check simplex */
572 		if (pf->is_simplex == is_simplex) {
573 			/* mismatch */
574 			continue;
575 		}
576 		/* check if HW endpoint matches */
577 		if (!usb_hw_ep_match(pf, ep->needs_ep_type, dir_in)) {
578 			/* mismatch */
579 			continue;
580 		}
581 		/* get maximum frame size */
582 		if (dir_in)
583 			max_frame_size = pf->max_in_frame_size;
584 		else
585 			max_frame_size = pf->max_out_frame_size;
586 
587 		/* check if we have a matching profile */
588 		if (max_frame_size >= ep->max_frame_size) {
589 			temp = (max_frame_size - ep->max_frame_size);
590 			if (distance > temp) {
591 				distance = temp;
592 				best_n = n;
593 				ep->pf = pf;
594 			}
595 		}
596 	}
597 
598 	/* see if we got a match */
599 	if (best_n != 0) {
600 		/* get the correct profile */
601 		pf = ep->pf;
602 
603 		/* reserve IN-endpoint */
604 		if (dir_in) {
605 			ues->bmInAlloc[best_n / 8] |=
606 			    (1 << (best_n % 8));
607 			ep->hw_endpoint_in = best_n | UE_DIR_IN;
608 			ep->needs_in = 0;
609 		}
610 		/* reserve OUT-endpoint */
611 		if (dir_out) {
612 			ues->bmOutAlloc[best_n / 8] |=
613 			    (1 << (best_n % 8));
614 			ep->hw_endpoint_out = best_n | UE_DIR_OUT;
615 			ep->needs_out = 0;
616 		}
617 		return (0);		/* got a match */
618 	}
619 	return (1);			/* failure */
620 }
621 
622 /*------------------------------------------------------------------------*
623  *	usb_hw_ep_get_needs
624  *
625  * This function will figure out the type and number of endpoints
626  * which are needed for an USB configuration.
627  *
628  * Return values:
629  *    0: Success.
630  * Else: Failure.
631  *------------------------------------------------------------------------*/
632 static uint8_t
633 usb_hw_ep_get_needs(struct usb_hw_ep_scratch *ues,
634     uint8_t ep_type, uint8_t is_complete)
635 {
636 	const struct usb_hw_ep_profile *pf;
637 	struct usb_hw_ep_scratch_sub *ep_iface;
638 	struct usb_hw_ep_scratch_sub *ep_curr;
639 	struct usb_hw_ep_scratch_sub *ep_max;
640 	struct usb_hw_ep_scratch_sub *ep_end;
641 	struct usb_descriptor *desc;
642 	struct usb_interface_descriptor *id;
643 	struct usb_endpoint_descriptor *ed;
644 	enum usb_dev_speed speed;
645 	uint16_t wMaxPacketSize;
646 	uint16_t temp;
647 	uint8_t ep_no;
648 
649 	ep_iface = ues->ep_max;
650 	ep_curr = ues->ep_max;
651 	ep_end = ues->ep + USB_EP_MAX;
652 	ep_max = ues->ep_max;
653 	desc = NULL;
654 	speed = usbd_get_speed(ues->udev);
655 
656 repeat:
657 
658 	while ((desc = usb_desc_foreach(ues->cd, desc))) {
659 
660 		if ((desc->bDescriptorType == UDESC_INTERFACE) &&
661 		    (desc->bLength >= sizeof(*id))) {
662 
663 			id = (void *)desc;
664 
665 			if (id->bAlternateSetting == 0) {
666 				/* going forward */
667 				ep_iface = ep_max;
668 			} else {
669 				/* reset */
670 				ep_curr = ep_iface;
671 			}
672 		}
673 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
674 		    (desc->bLength >= sizeof(*ed))) {
675 
676 			ed = (void *)desc;
677 
678 			goto handle_endpoint_desc;
679 		}
680 	}
681 	ues->ep_max = ep_max;
682 	return (0);
683 
684 handle_endpoint_desc:
685 	temp = (ed->bmAttributes & UE_XFERTYPE);
686 
687 	if (temp == ep_type) {
688 
689 		if (ep_curr == ep_end) {
690 			/* too many endpoints */
691 			return (1);	/* failure */
692 		}
693 		wMaxPacketSize = UGETW(ed->wMaxPacketSize);
694 		if ((wMaxPacketSize & 0xF800) &&
695 		    (speed == USB_SPEED_HIGH)) {
696 			/* handle packet multiplier */
697 			temp = (wMaxPacketSize >> 11) & 3;
698 			wMaxPacketSize &= 0x7FF;
699 			if (temp == 1) {
700 				wMaxPacketSize *= 2;
701 			} else {
702 				wMaxPacketSize *= 3;
703 			}
704 		}
705 		/*
706 		 * Check if we have a fixed endpoint number, else the
707 		 * endpoint number is allocated dynamically:
708 		 */
709 		ep_no = (ed->bEndpointAddress & UE_ADDR);
710 		if (ep_no != 0) {
711 
712 			/* get HW endpoint profile */
713 			(ues->methods->get_hw_ep_profile)
714 			    (ues->udev, &pf, ep_no);
715 			if (pf == NULL) {
716 				/* HW profile does not exist - failure */
717 				DPRINTFN(0, "Endpoint profile %u "
718 				    "does not exist\n", ep_no);
719 				return (1);
720 			}
721 			/* reserve fixed endpoint number */
722 			if (ep_type == UE_CONTROL) {
723 				ues->bmInAlloc[ep_no / 8] |=
724 				    (1 << (ep_no % 8));
725 				ues->bmOutAlloc[ep_no / 8] |=
726 				    (1 << (ep_no % 8));
727 				if ((pf->max_in_frame_size < wMaxPacketSize) ||
728 				    (pf->max_out_frame_size < wMaxPacketSize)) {
729 					DPRINTFN(0, "Endpoint profile %u "
730 					    "has too small buffer\n", ep_no);
731 					return (1);
732 				}
733 			} else if (ed->bEndpointAddress & UE_DIR_IN) {
734 				ues->bmInAlloc[ep_no / 8] |=
735 				    (1 << (ep_no % 8));
736 				if (pf->max_in_frame_size < wMaxPacketSize) {
737 					DPRINTFN(0, "Endpoint profile %u "
738 					    "has too small buffer\n", ep_no);
739 					return (1);
740 				}
741 			} else {
742 				ues->bmOutAlloc[ep_no / 8] |=
743 				    (1 << (ep_no % 8));
744 				if (pf->max_out_frame_size < wMaxPacketSize) {
745 					DPRINTFN(0, "Endpoint profile %u "
746 					    "has too small buffer\n", ep_no);
747 					return (1);
748 				}
749 			}
750 		} else if (is_complete) {
751 
752 			/* check if we have enough buffer space */
753 			if (wMaxPacketSize >
754 			    ep_curr->max_frame_size) {
755 				return (1);	/* failure */
756 			}
757 			if (ed->bEndpointAddress & UE_DIR_IN) {
758 				ed->bEndpointAddress =
759 				    ep_curr->hw_endpoint_in;
760 			} else {
761 				ed->bEndpointAddress =
762 				    ep_curr->hw_endpoint_out;
763 			}
764 
765 		} else {
766 
767 			/* compute the maximum frame size */
768 			if (ep_curr->max_frame_size < wMaxPacketSize) {
769 				ep_curr->max_frame_size = wMaxPacketSize;
770 			}
771 			if (temp == UE_CONTROL) {
772 				ep_curr->needs_in = 1;
773 				ep_curr->needs_out = 1;
774 			} else {
775 				if (ed->bEndpointAddress & UE_DIR_IN) {
776 					ep_curr->needs_in = 1;
777 				} else {
778 					ep_curr->needs_out = 1;
779 				}
780 			}
781 			ep_curr->needs_ep_type = ep_type;
782 		}
783 
784 		ep_curr++;
785 		if (ep_max < ep_curr) {
786 			ep_max = ep_curr;
787 		}
788 	}
789 	goto repeat;
790 }
791 
792 /*------------------------------------------------------------------------*
793  *	usb_hw_ep_resolve
794  *
795  * This function will try to resolve endpoint requirements by the
796  * given endpoint profiles that the USB hardware reports.
797  *
798  * Return values:
799  *    0: Success
800  * Else: Failure
801  *------------------------------------------------------------------------*/
802 static usb_error_t
803 usb_hw_ep_resolve(struct usb_device *udev,
804     struct usb_descriptor *desc)
805 {
806 	struct usb_hw_ep_scratch *ues;
807 	struct usb_hw_ep_scratch_sub *ep;
808 	const struct usb_hw_ep_profile *pf;
809 	struct usb_bus_methods *methods;
810 	struct usb_device_descriptor *dd;
811 	uint16_t mps;
812 
813 	if (desc == NULL) {
814 		return (USB_ERR_INVAL);
815 	}
816 	/* get bus methods */
817 	methods = udev->bus->methods;
818 
819 	if (methods->get_hw_ep_profile == NULL) {
820 		return (USB_ERR_INVAL);
821 	}
822 	if (desc->bDescriptorType == UDESC_DEVICE) {
823 
824 		if (desc->bLength < sizeof(*dd)) {
825 			return (USB_ERR_INVAL);
826 		}
827 		dd = (void *)desc;
828 
829 		/* get HW control endpoint 0 profile */
830 		(methods->get_hw_ep_profile) (udev, &pf, 0);
831 		if (pf == NULL) {
832 			return (USB_ERR_INVAL);
833 		}
834 		if (!usb_hw_ep_match(pf, UE_CONTROL, 0)) {
835 			DPRINTFN(0, "Endpoint 0 does not "
836 			    "support control\n");
837 			return (USB_ERR_INVAL);
838 		}
839 		mps = dd->bMaxPacketSize;
840 
841 		if (udev->speed == USB_SPEED_FULL) {
842 			/*
843 			 * We can optionally choose another packet size !
844 			 */
845 			while (1) {
846 				/* check if "mps" is ok */
847 				if (pf->max_in_frame_size >= mps) {
848 					break;
849 				}
850 				/* reduce maximum packet size */
851 				mps /= 2;
852 
853 				/* check if "mps" is too small */
854 				if (mps < 8) {
855 					return (USB_ERR_INVAL);
856 				}
857 			}
858 
859 			dd->bMaxPacketSize = mps;
860 
861 		} else {
862 			/* We only have one choice */
863 			if (mps == 255) {
864 				mps = 512;
865 			}
866 			/* Check if we support the specified wMaxPacketSize */
867 			if (pf->max_in_frame_size < mps) {
868 				return (USB_ERR_INVAL);
869 			}
870 		}
871 		return (0);		/* success */
872 	}
873 	if (desc->bDescriptorType != UDESC_CONFIG) {
874 		return (USB_ERR_INVAL);
875 	}
876 	if (desc->bLength < sizeof(*(ues->cd))) {
877 		return (USB_ERR_INVAL);
878 	}
879 	ues = udev->bus->scratch[0].hw_ep_scratch;
880 
881 	bzero(ues, sizeof(*ues));
882 
883 	ues->ep_max = ues->ep;
884 	ues->cd = (void *)desc;
885 	ues->methods = methods;
886 	ues->udev = udev;
887 
888 	/* Get all the endpoints we need */
889 
890 	if (usb_hw_ep_get_needs(ues, UE_ISOCHRONOUS, 0) ||
891 	    usb_hw_ep_get_needs(ues, UE_INTERRUPT, 0) ||
892 	    usb_hw_ep_get_needs(ues, UE_CONTROL, 0) ||
893 	    usb_hw_ep_get_needs(ues, UE_BULK, 0)) {
894 		DPRINTFN(0, "Could not get needs\n");
895 		return (USB_ERR_INVAL);
896 	}
897 	for (ep = ues->ep; ep != ues->ep_max; ep++) {
898 
899 		while (ep->needs_in || ep->needs_out) {
900 
901 			/*
902 		         * First try to use a simplex endpoint.
903 		         * Then try to use a duplex endpoint.
904 		         */
905 			if (usb_hw_ep_find_match(ues, ep, 1) &&
906 			    usb_hw_ep_find_match(ues, ep, 0)) {
907 				DPRINTFN(0, "Could not find match\n");
908 				return (USB_ERR_INVAL);
909 			}
910 		}
911 	}
912 
913 	ues->ep_max = ues->ep;
914 
915 	/* Update all endpoint addresses */
916 
917 	if (usb_hw_ep_get_needs(ues, UE_ISOCHRONOUS, 1) ||
918 	    usb_hw_ep_get_needs(ues, UE_INTERRUPT, 1) ||
919 	    usb_hw_ep_get_needs(ues, UE_CONTROL, 1) ||
920 	    usb_hw_ep_get_needs(ues, UE_BULK, 1)) {
921 		DPRINTFN(0, "Could not update endpoint address\n");
922 		return (USB_ERR_INVAL);
923 	}
924 	return (0);			/* success */
925 }
926 
927 /*------------------------------------------------------------------------*
928  *	usb_temp_get_tdd
929  *
930  * Returns:
931  *  NULL: No USB template device descriptor found.
932  *  Else: Pointer to the USB template device descriptor.
933  *------------------------------------------------------------------------*/
934 static const struct usb_temp_device_desc *
935 usb_temp_get_tdd(struct usb_device *udev)
936 {
937 	if (udev->usb_template_ptr == NULL) {
938 		return (NULL);
939 	}
940 	return (udev->usb_template_ptr->tdd);
941 }
942 
943 /*------------------------------------------------------------------------*
944  *	usb_temp_get_device_desc
945  *
946  * Returns:
947  *  NULL: No USB device descriptor found.
948  *  Else: Pointer to USB device descriptor.
949  *------------------------------------------------------------------------*/
950 static void *
951 usb_temp_get_device_desc(struct usb_device *udev)
952 {
953 	struct usb_device_descriptor *dd;
954 
955 	if (udev->usb_template_ptr == NULL) {
956 		return (NULL);
957 	}
958 	dd = &udev->usb_template_ptr->udd;
959 	if (dd->bDescriptorType != UDESC_DEVICE) {
960 		/* sanity check failed */
961 		return (NULL);
962 	}
963 	return (dd);
964 }
965 
966 /*------------------------------------------------------------------------*
967  *	usb_temp_get_qualifier_desc
968  *
969  * Returns:
970  *  NULL: No USB device_qualifier descriptor found.
971  *  Else: Pointer to USB device_qualifier descriptor.
972  *------------------------------------------------------------------------*/
973 static void *
974 usb_temp_get_qualifier_desc(struct usb_device *udev)
975 {
976 	struct usb_device_qualifier *dq;
977 
978 	if (udev->usb_template_ptr == NULL) {
979 		return (NULL);
980 	}
981 	dq = &udev->usb_template_ptr->udq;
982 	if (dq->bDescriptorType != UDESC_DEVICE_QUALIFIER) {
983 		/* sanity check failed */
984 		return (NULL);
985 	}
986 	return (dq);
987 }
988 
989 /*------------------------------------------------------------------------*
990  *	usb_temp_get_config_desc
991  *
992  * Returns:
993  *  NULL: No USB config descriptor found.
994  *  Else: Pointer to USB config descriptor having index "index".
995  *------------------------------------------------------------------------*/
996 static void *
997 usb_temp_get_config_desc(struct usb_device *udev,
998     uint16_t *pLength, uint8_t index)
999 {
1000 	struct usb_device_descriptor *dd;
1001 	struct usb_config_descriptor *cd;
1002 	uint16_t temp;
1003 
1004 	if (udev->usb_template_ptr == NULL) {
1005 		return (NULL);
1006 	}
1007 	dd = &udev->usb_template_ptr->udd;
1008 	cd = (void *)(udev->usb_template_ptr + 1);
1009 
1010 	if (index >= dd->bNumConfigurations) {
1011 		/* out of range */
1012 		return (NULL);
1013 	}
1014 	while (index--) {
1015 		if (cd->bDescriptorType != UDESC_CONFIG) {
1016 			/* sanity check failed */
1017 			return (NULL);
1018 		}
1019 		temp = UGETW(cd->wTotalLength);
1020 		cd = USB_ADD_BYTES(cd, temp);
1021 	}
1022 
1023 	if (pLength) {
1024 		*pLength = UGETW(cd->wTotalLength);
1025 	}
1026 	return (cd);
1027 }
1028 
1029 /*------------------------------------------------------------------------*
1030  *	usb_temp_get_vendor_desc
1031  *
1032  * Returns:
1033  *  NULL: No vendor descriptor found.
1034  *  Else: Pointer to a vendor descriptor.
1035  *------------------------------------------------------------------------*/
1036 static const void *
1037 usb_temp_get_vendor_desc(struct usb_device *udev,
1038     const struct usb_device_request *req)
1039 {
1040 	const struct usb_temp_device_desc *tdd;
1041 
1042 	tdd = usb_temp_get_tdd(udev);
1043 	if (tdd == NULL) {
1044 		return (NULL);
1045 	}
1046 	if (tdd->getVendorDesc == NULL) {
1047 		return (NULL);
1048 	}
1049 	return ((tdd->getVendorDesc) (req));
1050 }
1051 
1052 /*------------------------------------------------------------------------*
1053  *	usb_temp_get_string_desc
1054  *
1055  * Returns:
1056  *  NULL: No string descriptor found.
1057  *  Else: Pointer to a string descriptor.
1058  *------------------------------------------------------------------------*/
1059 static const void *
1060 usb_temp_get_string_desc(struct usb_device *udev,
1061     uint16_t lang_id, uint8_t string_index)
1062 {
1063 	const struct usb_temp_device_desc *tdd;
1064 
1065 	tdd = usb_temp_get_tdd(udev);
1066 	if (tdd == NULL) {
1067 		return (NULL);
1068 	}
1069 	if (tdd->getStringDesc == NULL) {
1070 		return (NULL);
1071 	}
1072 	return ((tdd->getStringDesc) (lang_id, string_index));
1073 }
1074 
1075 /*------------------------------------------------------------------------*
1076  *	usb_temp_get_hub_desc
1077  *
1078  * Returns:
1079  *  NULL: No USB HUB descriptor found.
1080  *  Else: Pointer to a USB HUB descriptor.
1081  *------------------------------------------------------------------------*/
1082 static const void *
1083 usb_temp_get_hub_desc(struct usb_device *udev)
1084 {
1085 	return (NULL);			/* needs to be implemented */
1086 }
1087 
1088 /*------------------------------------------------------------------------*
1089  *	usb_temp_get_desc
1090  *
1091  * This function is a demultiplexer for local USB device side control
1092  * endpoint requests.
1093  *------------------------------------------------------------------------*/
1094 static usb_error_t
1095 usb_temp_get_desc(struct usb_device *udev, struct usb_device_request *req,
1096     const void **pPtr, uint16_t *pLength)
1097 {
1098 	const uint8_t *buf;
1099 	uint16_t len;
1100 
1101 	buf = NULL;
1102 	len = 0;
1103 
1104 	switch (req->bmRequestType) {
1105 	case UT_READ_DEVICE:
1106 		switch (req->bRequest) {
1107 		case UR_GET_DESCRIPTOR:
1108 			goto tr_handle_get_descriptor;
1109 		default:
1110 			goto tr_stalled;
1111 		}
1112 		break;
1113 	case UT_READ_CLASS_DEVICE:
1114 		switch (req->bRequest) {
1115 		case UR_GET_DESCRIPTOR:
1116 			goto tr_handle_get_class_descriptor;
1117 		default:
1118 			goto tr_stalled;
1119 		}
1120 		break;
1121 	case UT_READ_VENDOR_DEVICE:
1122 	case UT_READ_VENDOR_OTHER:
1123 		buf = usb_temp_get_vendor_desc(udev, req);
1124 		goto tr_valid;
1125 	default:
1126 		goto tr_stalled;
1127 	}
1128 
1129 tr_handle_get_descriptor:
1130 	switch (req->wValue[1]) {
1131 	case UDESC_DEVICE:
1132 		if (req->wValue[0]) {
1133 			goto tr_stalled;
1134 		}
1135 		buf = usb_temp_get_device_desc(udev);
1136 		goto tr_valid;
1137 	case UDESC_DEVICE_QUALIFIER:
1138 		if (udev->speed != USB_SPEED_HIGH) {
1139 			goto tr_stalled;
1140 		}
1141 		if (req->wValue[0]) {
1142 			goto tr_stalled;
1143 		}
1144 		buf = usb_temp_get_qualifier_desc(udev);
1145 		goto tr_valid;
1146 	case UDESC_OTHER_SPEED_CONFIGURATION:
1147 		if (udev->speed != USB_SPEED_HIGH) {
1148 			goto tr_stalled;
1149 		}
1150 	case UDESC_CONFIG:
1151 		buf = usb_temp_get_config_desc(udev,
1152 		    &len, req->wValue[0]);
1153 		goto tr_valid;
1154 	case UDESC_STRING:
1155 		buf = usb_temp_get_string_desc(udev,
1156 		    UGETW(req->wIndex), req->wValue[0]);
1157 		goto tr_valid;
1158 	default:
1159 		goto tr_stalled;
1160 	}
1161 	goto tr_stalled;
1162 
1163 tr_handle_get_class_descriptor:
1164 	if (req->wValue[0]) {
1165 		goto tr_stalled;
1166 	}
1167 	buf = usb_temp_get_hub_desc(udev);
1168 	goto tr_valid;
1169 
1170 tr_valid:
1171 	if (buf == NULL) {
1172 		goto tr_stalled;
1173 	}
1174 	if (len == 0) {
1175 		len = buf[0];
1176 	}
1177 	*pPtr = buf;
1178 	*pLength = len;
1179 	return (0);	/* success */
1180 
1181 tr_stalled:
1182 	*pPtr = NULL;
1183 	*pLength = 0;
1184 	return (0);	/* we ignore failures */
1185 }
1186 
1187 /*------------------------------------------------------------------------*
1188  *	usb_temp_setup
1189  *
1190  * This function generates USB descriptors according to the given USB
1191  * template device descriptor. It will also try to figure out the best
1192  * matching endpoint addresses using the hardware endpoint profiles.
1193  *
1194  * Returns:
1195  *    0: Success
1196  * Else: Failure
1197  *------------------------------------------------------------------------*/
1198 static usb_error_t
1199 usb_temp_setup(struct usb_device *udev,
1200     const struct usb_temp_device_desc *tdd)
1201 {
1202 	struct usb_temp_setup *uts;
1203 	void *buf;
1204 	uint8_t n;
1205 
1206 	if (tdd == NULL) {
1207 		/* be NULL safe */
1208 		return (0);
1209 	}
1210 	uts = udev->bus->scratch[0].temp_setup;
1211 
1212 	bzero(uts, sizeof(*uts));
1213 
1214 	uts->usb_speed = udev->speed;
1215 	uts->self_powered = udev->flags.self_powered;
1216 
1217 	/* first pass */
1218 
1219 	usb_make_device_desc(uts, tdd);
1220 
1221 	if (uts->err) {
1222 		/* some error happened */
1223 		return (uts->err);
1224 	}
1225 	/* sanity check */
1226 	if (uts->size == 0) {
1227 		return (USB_ERR_INVAL);
1228 	}
1229 	/* allocate zeroed memory */
1230 	uts->buf = malloc(uts->size, M_USB, M_WAITOK | M_ZERO);
1231 	if (uts->buf == NULL) {
1232 		/* could not allocate memory */
1233 		return (USB_ERR_NOMEM);
1234 	}
1235 	/* second pass */
1236 
1237 	uts->size = 0;
1238 
1239 	usb_make_device_desc(uts, tdd);
1240 
1241 	/*
1242 	 * Store a pointer to our descriptors:
1243 	 */
1244 	udev->usb_template_ptr = uts->buf;
1245 
1246 	if (uts->err) {
1247 		/* some error happened during second pass */
1248 		goto error;
1249 	}
1250 	/*
1251 	 * Resolve all endpoint addresses !
1252 	 */
1253 	buf = usb_temp_get_device_desc(udev);
1254 	uts->err = usb_hw_ep_resolve(udev, buf);
1255 	if (uts->err) {
1256 		DPRINTFN(0, "Could not resolve endpoints for "
1257 		    "Device Descriptor, error = %s\n",
1258 		    usbd_errstr(uts->err));
1259 		goto error;
1260 	}
1261 	for (n = 0;; n++) {
1262 
1263 		buf = usb_temp_get_config_desc(udev, NULL, n);
1264 		if (buf == NULL) {
1265 			break;
1266 		}
1267 		uts->err = usb_hw_ep_resolve(udev, buf);
1268 		if (uts->err) {
1269 			DPRINTFN(0, "Could not resolve endpoints for "
1270 			    "Config Descriptor %u, error = %s\n", n,
1271 			    usbd_errstr(uts->err));
1272 			goto error;
1273 		}
1274 	}
1275 	return (uts->err);
1276 
1277 error:
1278 	usb_temp_unsetup(udev);
1279 	return (uts->err);
1280 }
1281 
1282 /*------------------------------------------------------------------------*
1283  *	usb_temp_unsetup
1284  *
1285  * This function frees any memory associated with the currently
1286  * setup template, if any.
1287  *------------------------------------------------------------------------*/
1288 static void
1289 usb_temp_unsetup(struct usb_device *udev)
1290 {
1291 	if (udev->usb_template_ptr) {
1292 
1293 		free(udev->usb_template_ptr, M_USB);
1294 
1295 		udev->usb_template_ptr = NULL;
1296 	}
1297 }
1298 
1299 static usb_error_t
1300 usb_temp_setup_by_index(struct usb_device *udev, uint16_t index)
1301 {
1302 	usb_error_t err;
1303 
1304 	switch (index) {
1305 	case 0:
1306 		err = usb_temp_setup(udev, &usb_template_msc);
1307 		break;
1308 	case 1:
1309 		err = usb_temp_setup(udev, &usb_template_cdce);
1310 		break;
1311 	case 2:
1312 		err = usb_temp_setup(udev, &usb_template_mtp);
1313 		break;
1314 	default:
1315 		return (USB_ERR_INVAL);
1316 	}
1317 
1318 	return (err);
1319 }
1320 
1321 static void
1322 usb_temp_init(void *arg)
1323 {
1324 	/* register our functions */
1325 	usb_temp_get_desc_p = &usb_temp_get_desc;
1326 	usb_temp_setup_by_index_p = &usb_temp_setup_by_index;
1327 	usb_temp_unsetup_p = &usb_temp_unsetup;
1328 }
1329 
1330 SYSINIT(usb_temp_init, SI_SUB_LOCK, SI_ORDER_FIRST, usb_temp_init, NULL);
1331 SYSUNINIT(usb_temp_unload, SI_SUB_LOCK, SI_ORDER_ANY, usb_temp_unload, NULL);
1332