Home | History | Annotate | Line # | Download | only in usb
uvideo.c revision 1.22
      1 /*	$NetBSD: uvideo.c,v 1.22 2008/11/28 17:20:02 jmorse Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2008 Patrick Mahoney
      5  * All rights reserved.
      6  *
      7  * This code was written by Patrick Mahoney (pat (at) polycrystal.org) as
      8  * part of Google Summer of Code 2008.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * USB video specs:
     41  *      http://www.usb.org/developers/devclass_docs/USB_Video_Class_1_1.zip
     42  */
     43 
     44 #include <sys/cdefs.h>
     45 __KERNEL_RCSID(0, "$NetBSD: uvideo.c,v 1.22 2008/11/28 17:20:02 jmorse Exp $");
     46 
     47 #ifdef _MODULE
     48 #include <sys/module.h>
     49 #endif
     50 
     51 #include <sys/param.h>
     52 #include <sys/systm.h>
     53 #include <sys/kernel.h>
     54 /* #include <sys/malloc.h> */
     55 #include <sys/kmem.h>
     56 #include <sys/device.h>
     57 #include <sys/ioctl.h>
     58 #include <sys/uio.h>
     59 #include <sys/tty.h>
     60 #include <sys/file.h>
     61 #include <sys/select.h>
     62 #include <sys/proc.h>
     63 #include <sys/conf.h>
     64 #include <sys/vnode.h>
     65 #include <sys/poll.h>
     66 #include <sys/queue.h>	/* SLIST */
     67 #include <sys/kthread.h>
     68 
     69 #include <sys/videoio.h>
     70 #include <dev/video_if.h>
     71 
     72 #include <dev/usb/usb.h>
     73 #include <dev/usb/usbdi.h>
     74 #include <dev/usb/usbdi_util.h>
     75 #include <dev/usb/usb_quirks.h>
     76 
     77 #include <dev/usb/uvideoreg.h>
     78 
     79 #if !defined(_MODULE)
     80 #include "opt_uvideo.h"
     81 #endif
     82 
     83 #define UVIDEO_NXFERS	3
     84 #define PRI_UVIDEO	PRI_BIO
     85 
     86 /* #define UVIDEO_DISABLE_MJPEG */
     87 
     88 #ifdef UVIDEO_DEBUG
     89 #define DPRINTF(x)	do { if (uvideodebug) logprintf x; } while (0)
     90 #define DPRINTFN(n,x)	do { if (uvideodebug>(n)) logprintf x; } while (0)
     91 int	uvideodebug = 20;
     92 #else
     93 #define DPRINTF(x)
     94 #define DPRINTFN(n,x)
     95 #endif
     96 
     97 typedef enum {
     98 	UVIDEO_STATE_CLOSED,
     99 	UVIDEO_STATE_OPENING,
    100 	UVIDEO_STATE_IDLE
    101 } uvideo_state;
    102 
    103 struct uvideo_camera_terminal {
    104 	uint16_t	ct_objective_focal_min;
    105 	uint16_t	ct_objective_focal_max;
    106 	uint16_t	ct_ocular_focal_length;
    107 };
    108 
    109 struct uvideo_processing_unit {
    110 	uint16_t	pu_max_multiplier; /* digital zoom */
    111 	uint8_t		pu_video_standards;
    112 };
    113 
    114 struct uvideo_extension_unit {
    115 	guid_t		xu_guid;
    116 };
    117 
    118 /* For simplicity, we consider a Terminal a special case of Unit
    119  * rather than a separate entity. */
    120 struct uvideo_unit {
    121 	uint8_t		vu_id;
    122 	uint8_t		vu_type;
    123 	uint8_t		vu_dst_id;
    124 	uint8_t		vu_nsrcs;
    125 	union {
    126 		uint8_t	vu_src_id;	/* vu_nsrcs = 1 */
    127 		uint8_t	*vu_src_id_ary; /* vu_nsrcs > 1 */
    128 	} s;
    129 
    130 	/* fields for individual unit/terminal types */
    131 	union {
    132 		struct uvideo_camera_terminal	vu_camera;
    133 		struct uvideo_processing_unit	vu_processing;
    134 		struct uvideo_extension_unit	vu_extension;
    135 	} u;
    136 
    137 	/* Used by camera terminal, processing and extention units. */
    138 	uint8_t		vu_control_size; /* number of bytes in vu_controls */
    139 	uint8_t		*vu_controls;	 /* array of bytes. bits are
    140 					  * numbered from 0 at least
    141 					  * significant bit to
    142 					  * (8*vu_control_size - 1)*/
    143 };
    144 
    145 struct uvideo_alternate {
    146 	uint8_t		altno;
    147 	uint8_t		interval;
    148 	uint16_t	max_packet_size;
    149 	SLIST_ENTRY(uvideo_alternate)	entries;
    150 };
    151 SLIST_HEAD(altlist, uvideo_alternate);
    152 
    153 #define UVIDEO_FORMAT_GET_FORMAT_INDEX(fmt)	\
    154 	((fmt)->format.priv & 0xff)
    155 #define UVIDEO_FORMAT_GET_FRAME_INDEX(fmt)	\
    156 	(((fmt)->format.priv >> 8) & 0xff)
    157 /* TODO: find a better way to set bytes within this 32 bit value? */
    158 #define UVIDEO_FORMAT_SET_FORMAT_INDEX(fmt, index) do {	\
    159 		(fmt)->format.priv &= ~0xff;		\
    160 		(fmt)->format.priv |= ((index) & 0xff);	\
    161 	} while (0)
    162 #define UVIDEO_FORMAT_SET_FRAME_INDEX(fmt, index) do {			\
    163 		(fmt)->format.priv &= ~(0xff << 8);			\
    164 		((fmt)->format.priv |= (((index) & 0xff) << 8));	\
    165 	} while (0)
    166 
    167 struct uvideo_pixel_format {
    168 	enum video_pixel_format	pixel_format;
    169 	SIMPLEQ_ENTRY(uvideo_pixel_format) entries;
    170 };
    171 SIMPLEQ_HEAD(uvideo_pixel_format_list, uvideo_pixel_format);
    172 
    173 struct uvideo_format {
    174 	struct video_format	format;
    175 	SIMPLEQ_ENTRY(uvideo_format) entries;
    176 };
    177 SIMPLEQ_HEAD(uvideo_format_list, uvideo_format);
    178 
    179 struct uvideo_isoc_xfer;
    180 struct uvideo_stream;
    181 
    182 struct uvideo_isoc {
    183 	struct uvideo_isoc_xfer	*i_ix;
    184 	struct uvideo_stream	*i_vs;
    185 	usbd_xfer_handle	i_xfer;
    186 	uint8_t			*i_buf;
    187 	uint16_t		*i_frlengths;
    188 };
    189 
    190 struct uvideo_isoc_xfer {
    191 	uint8_t			ix_endpt;
    192 	usbd_pipe_handle	ix_pipe;
    193 	struct uvideo_isoc	ix_i[UVIDEO_NXFERS];
    194 	uint32_t		ix_nframes;
    195 	uint32_t		ix_uframe_len;
    196 
    197 	struct altlist		ix_altlist;
    198 };
    199 
    200 struct uvideo_bulk_xfer {
    201 	uint8_t			bx_endpt;
    202 	usbd_pipe_handle	bx_pipe;
    203 	usbd_xfer_handle	bx_xfer;
    204 	uint8_t			*bx_buffer;
    205 	int			bx_buflen;
    206 	bool			bx_running;
    207 	kcondvar_t		bx_cv;
    208 	kmutex_t		bx_lock;
    209 };
    210 
    211 struct uvideo_stream {
    212 	struct uvideo_softc	*vs_parent;
    213 	usbd_interface_handle	vs_iface;
    214 	uint8_t			vs_ifaceno;
    215 	uint8_t			vs_subtype;  /* input or output */
    216 	uint16_t		vs_probelen; /* length of probe and
    217 					      * commit data; varies
    218 					      * depending on version
    219 					      * of spec. */
    220 	struct uvideo_format_list vs_formats;
    221 	struct uvideo_pixel_format_list vs_pixel_formats;
    222 	struct video_format	*vs_default_format;
    223 	struct video_format	vs_current_format;
    224 
    225 	/* usb transfer details */
    226 	uint8_t			vs_xfer_type;
    227 	union {
    228 		struct uvideo_bulk_xfer	bulk;
    229 		struct uvideo_isoc_xfer isoc;
    230 	} vs_xfer;
    231 
    232 	int			vs_frameno;	/* toggles between 0 and 1 */
    233 
    234 	/* current video format */
    235 	uint32_t		vs_max_payload_size;
    236 	uint32_t		vs_max_frame_size;
    237 	uint32_t		vs_frame_interval;
    238 	SLIST_ENTRY(uvideo_stream) entries;
    239 };
    240 SLIST_HEAD(uvideo_stream_list, uvideo_stream);
    241 
    242 struct uvideo_softc {
    243         USBBASEDEVICE   	sc_dev;		/* base device */
    244         usbd_device_handle      sc_udev;	/* device */
    245 	usbd_interface_handle   sc_iface;	/* interface handle */
    246         int     		sc_ifaceno;	/* interface number */
    247 	char			*sc_devname;
    248 
    249 	device_ptr_t		sc_videodev;
    250 
    251 	int			sc_dying;
    252 	uvideo_state		sc_state;
    253 
    254 	uint8_t			sc_nunits;
    255 	struct uvideo_unit	**sc_unit;
    256 
    257 	struct uvideo_stream	*sc_stream_in;
    258 
    259 	struct uvideo_stream_list sc_stream_list;
    260 };
    261 
    262 int	uvideo_match(device_t, cfdata_t, void *);
    263 void	uvideo_attach(device_t, device_t, void *);
    264 int	uvideo_detach(device_t, int);
    265 void	uvideo_childdet(device_t, device_t);
    266 int	uvideo_activate(device_t, enum devact);
    267 
    268 static int	uvideo_open(void *, int);
    269 static void	uvideo_close(void *);
    270 static const char * uvideo_get_devname(void *);
    271 
    272 static int	uvideo_enum_format(void *, uint32_t, struct video_format *);
    273 static int	uvideo_get_format(void *, struct video_format *);
    274 static int	uvideo_set_format(void *, struct video_format *);
    275 static int	uvideo_try_format(void *, struct video_format *);
    276 static int	uvideo_start_transfer(void *);
    277 static int	uvideo_stop_transfer(void *);
    278 
    279 static int	uvideo_get_control_group(void *,
    280 					 struct video_control_group *);
    281 static int	uvideo_set_control_group(void *,
    282 					 const struct video_control_group *);
    283 
    284 static usbd_status	uvideo_init_control(
    285 	struct uvideo_softc *,
    286 	const usb_interface_descriptor_t *,
    287 	usbd_desc_iter_t *);
    288 static usbd_status	uvideo_init_collection(
    289 	struct uvideo_softc *,
    290 	const usb_interface_descriptor_t *,
    291 	usbd_desc_iter_t *);
    292 
    293 /* Functions for unit & terminal descriptors */
    294 static struct uvideo_unit *	uvideo_unit_alloc(const uvideo_descriptor_t *);
    295 static usbd_status		uvideo_unit_init(struct uvideo_unit *,
    296 						 const uvideo_descriptor_t *);
    297 static void			uvideo_unit_free(struct uvideo_unit *);
    298 static usbd_status		uvideo_unit_alloc_controls(struct uvideo_unit *,
    299 							   uint8_t,
    300 							   const uint8_t *);
    301 static void			uvideo_unit_free_controls(struct uvideo_unit *);
    302 static usbd_status		uvideo_unit_alloc_sources(struct uvideo_unit *,
    303 							  uint8_t,
    304 							  const uint8_t *);
    305 static void			uvideo_unit_free_sources(struct uvideo_unit *);
    306 
    307 
    308 
    309 
    310 /* Functions for uvideo_stream, primary unit associated with a video
    311  * driver or device file. */
    312 static struct uvideo_stream *	uvideo_find_stream(struct uvideo_softc *,
    313 						   uint8_t);
    314 #if 0
    315 static struct uvideo_format *	uvideo_stream_find_format(
    316 	struct uvideo_stream *,
    317 	uint8_t, uint8_t);
    318 #endif
    319 static struct uvideo_format *	uvideo_stream_guess_format(
    320 	struct uvideo_stream *,
    321 	enum video_pixel_format, uint32_t, uint32_t);
    322 static struct uvideo_stream *	uvideo_stream_alloc(void);
    323 static usbd_status		uvideo_stream_init(
    324 	struct uvideo_stream *stream,
    325 	struct uvideo_softc *sc,
    326 	const usb_interface_descriptor_t *ifdesc,
    327 	uint8_t idx);
    328 static usbd_status		uvideo_stream_init_desc(
    329 	struct uvideo_stream *,
    330 	const usb_interface_descriptor_t *ifdesc,
    331 	usbd_desc_iter_t *iter);
    332 static usbd_status		uvideo_stream_init_frame_based_format(
    333 	struct uvideo_stream *,
    334 	const uvideo_descriptor_t *,
    335 	usbd_desc_iter_t *);
    336 static void			uvideo_stream_free(struct uvideo_stream *);
    337 
    338 static int		uvideo_stream_start_xfer(struct uvideo_stream *);
    339 static int		uvideo_stream_stop_xfer(struct uvideo_stream *);
    340 static usbd_status	uvideo_stream_recv_process(struct uvideo_stream *,
    341 						   uint8_t *, uint32_t);
    342 static usbd_status	uvideo_stream_recv_isoc_start(struct uvideo_stream *);
    343 static usbd_status	uvideo_stream_recv_isoc_start1(struct uvideo_isoc *);
    344 static void		uvideo_stream_recv_isoc_complete(usbd_xfer_handle,
    345 							 usbd_private_handle,
    346 							 usbd_status);
    347 static void		uvideo_stream_recv_bulk_transfer(void *);
    348 
    349 /* format probe and commit */
    350 #define uvideo_stream_probe(vs, act, data)				\
    351 	(uvideo_stream_probe_and_commit((vs), (act),			\
    352 					UVIDEO_VS_PROBE_CONTROL, (data)))
    353 #define uvideo_stream_commit(vs, act, data)				\
    354 	(uvideo_stream_probe_and_commit((vs), (act),			\
    355 					UVIDEO_VS_COMMIT_CONTROL, (data)))
    356 static usbd_status	uvideo_stream_probe_and_commit(struct uvideo_stream *,
    357 						       uint8_t, uint8_t,
    358 						       void *);
    359 static void		uvideo_init_probe_data(uvideo_probe_and_commit_data_t *);
    360 
    361 
    362 static const usb_descriptor_t * usb_desc_iter_peek_next(usbd_desc_iter_t *);
    363 static const usb_interface_descriptor_t * usb_desc_iter_next_interface(
    364 	usbd_desc_iter_t *);
    365 static const usb_descriptor_t * usb_desc_iter_next_non_interface(
    366 	usbd_desc_iter_t *);
    367 
    368 static int	usb_guid_cmp(const usb_guid_t *, const guid_t *);
    369 
    370 
    371 CFATTACH_DECL2_NEW(uvideo, sizeof(struct uvideo_softc),
    372     uvideo_match, uvideo_attach, uvideo_detach, uvideo_activate, NULL,
    373     uvideo_childdet);
    374 
    375 extern struct cfdriver uvideo_cd;
    376 
    377 
    378 static const struct video_hw_if uvideo_hw_if = {
    379 	.open = uvideo_open,
    380 	.close = uvideo_close,
    381 	.get_devname = uvideo_get_devname,
    382 	.enum_format = uvideo_enum_format,
    383 	.get_format = uvideo_get_format,
    384 	.set_format = uvideo_set_format,
    385 	.try_format = uvideo_try_format,
    386 	.start_transfer = uvideo_start_transfer,
    387 	.stop_transfer = uvideo_stop_transfer,
    388 	.control_iter_init = NULL,
    389 	.control_iter_next = NULL,
    390 	.get_control_desc_group = NULL,
    391 	.get_control_group = uvideo_get_control_group,
    392 	.set_control_group = uvideo_set_control_group,
    393 };
    394 
    395 #ifdef UVIDEO_DEBUG
    396 /* Some functions to print out descriptors.  Mostly useless other than
    397  * debugging/exploration purposes. */
    398 static void usb_guid_print(const usb_guid_t *);
    399 static void print_descriptor(const usb_descriptor_t *);
    400 static void print_interface_descriptor(const usb_interface_descriptor_t *);
    401 static void print_endpoint_descriptor(const usb_endpoint_descriptor_t *);
    402 
    403 static void print_vc_descriptor(const usb_descriptor_t *);
    404 static void print_vs_descriptor(const usb_descriptor_t *);
    405 
    406 static void print_vc_header_descriptor(
    407 	const uvideo_vc_header_descriptor_t *);
    408 static void print_input_terminal_descriptor(
    409 	const uvideo_input_terminal_descriptor_t *);
    410 static void print_output_terminal_descriptor(
    411 	const uvideo_output_terminal_descriptor_t *);
    412 static void print_camera_terminal_descriptor(
    413 	const uvideo_camera_terminal_descriptor_t *);
    414 static void print_selector_unit_descriptor(
    415 	const uvideo_selector_unit_descriptor_t *);
    416 static void print_processing_unit_descriptor(
    417 	const uvideo_processing_unit_descriptor_t *);
    418 static void print_extension_unit_descriptor(
    419 	const uvideo_extension_unit_descriptor_t *);
    420 static void print_interrupt_endpoint_descriptor(
    421 	const uvideo_vc_interrupt_endpoint_descriptor_t *);
    422 
    423 static void print_vs_input_header_descriptor(
    424 	const uvideo_vs_input_header_descriptor_t *);
    425 static void print_vs_output_header_descriptor(
    426 	const uvideo_vs_output_header_descriptor_t *);
    427 
    428 static void print_vs_format_uncompressed_descriptor(
    429 	const uvideo_vs_format_uncompressed_descriptor_t *);
    430 static void print_vs_frame_uncompressed_descriptor(
    431 	const uvideo_vs_frame_uncompressed_descriptor_t *);
    432 static void print_vs_format_mjpeg_descriptor(
    433 	const uvideo_vs_format_mjpeg_descriptor_t *);
    434 static void print_vs_frame_mjpeg_descriptor(
    435 	const uvideo_vs_frame_mjpeg_descriptor_t *);
    436 static void print_vs_format_dv_descriptor(
    437 	const uvideo_vs_format_dv_descriptor_t *);
    438 #endif /* !UVIDEO_DEBUG */
    439 
    440 #define GET(type, descp, field) (((const type *)(descp))->field)
    441 #define GETP(type, descp, field) (&(((const type *)(descp))->field))
    442 
    443 /* Given a format descriptor and frame descriptor, copy values common
    444  * to all formats into a struct uvideo_format. */
    445 #define UVIDEO_FORMAT_INIT_FRAME_BASED(format_type, format_desc,	\
    446 				       frame_type, frame_desc,		\
    447 				       format)				\
    448 	do {								\
    449 		UVIDEO_FORMAT_SET_FORMAT_INDEX(				\
    450 			format,						\
    451 			GET(format_type, format_desc, bFormatIndex));	\
    452 		UVIDEO_FORMAT_SET_FRAME_INDEX(				\
    453 			format,						\
    454 			GET(frame_type, frame_desc, bFrameIndex));	\
    455 		format->format.width =					\
    456 		    UGETW(GET(frame_type, frame_desc, wWidth));		\
    457 		format->format.height =					\
    458 		    UGETW(GET(frame_type, frame_desc, wHeight));	\
    459 		format->format.aspect_x =				\
    460 		    GET(format_type, format_desc, bAspectRatioX);	\
    461 		format->format.aspect_y =				\
    462 		    GET(format_type, format_desc, bAspectRatioY);	\
    463 	} while (0)
    464 
    465 
    466 USB_MATCH(uvideo)
    467 {
    468 	USB_IFMATCH_START(uvideo, uaa);
    469 
    470         /* TODO: May need to change in the future to work with
    471          * Interface Association Descriptor. */
    472 
    473 	/* Trigger on the Video Control Interface which must be present */
    474 	if (uaa->class == UICLASS_VIDEO &&
    475 	    uaa->subclass == UISUBCLASS_VIDEOCONTROL)
    476 		return UMATCH_IFACECLASS_IFACESUBCLASS;
    477 
    478 	return UMATCH_NONE;
    479 }
    480 
    481 USB_ATTACH(uvideo)
    482 {
    483 	USB_IFATTACH_START(uvideo, sc, uaa);
    484 	usbd_desc_iter_t iter;
    485 	const usb_interface_descriptor_t *ifdesc;
    486 	struct uvideo_stream *vs;
    487 	usbd_status err;
    488 	uint8_t ifaceidx;
    489 
    490 	sc->sc_dev = self;
    491 
    492 	sc->sc_devname = usbd_devinfo_alloc(uaa->device, 0);
    493 
    494 	aprint_naive("\n");
    495 	aprint_normal(": %s\n", sc->sc_devname);
    496 
    497 	sc->sc_udev = uaa->device;
    498 	sc->sc_iface = uaa->iface;
    499 	sc->sc_ifaceno = uaa->ifaceno;
    500 	sc->sc_dying = 0;
    501 	sc->sc_state = UVIDEO_STATE_CLOSED;
    502 	SLIST_INIT(&sc->sc_stream_list);
    503 
    504 #ifdef UVIDEO_DEBUG
    505 	/* Debugging dump of descriptors. TODO: move this to userspace
    506 	 * via a custom IOCTL or something. */
    507 	const usb_descriptor_t *desc;
    508 	usb_desc_iter_init(sc->sc_udev, &iter);
    509 	while ((desc = usb_desc_iter_next(&iter)) != NULL) {
    510 		/* print out all descriptors */
    511 		printf("uvideo_attach: ");
    512 		print_descriptor(desc);
    513 	}
    514 #endif /* !UVIDEO_DEBUG */
    515 
    516 	/* iterate through interface descriptors and initialize softc */
    517 	usb_desc_iter_init(sc->sc_udev, &iter);
    518 	for (ifaceidx = 0;
    519 	     (ifdesc = usb_desc_iter_next_interface(&iter)) != NULL;
    520 	     ++ifaceidx)
    521 	{
    522 		if (ifdesc->bInterfaceClass != UICLASS_VIDEO) {
    523 			DPRINTFN(50, ("uvideo_attach: "
    524 				      "ignoring non-uvc interface: "
    525 				      "len=%d type=0x%02x "
    526 				      "class=0x%02x subclass=0x%02x\n",
    527 				      ifdesc->bLength,
    528 				      ifdesc->bDescriptorType,
    529 				      ifdesc->bInterfaceClass,
    530 				      ifdesc->bInterfaceSubClass));
    531 			continue;
    532 		}
    533 
    534 		switch (ifdesc->bInterfaceSubClass) {
    535 		case UISUBCLASS_VIDEOCONTROL:
    536 			err = uvideo_init_control(sc, ifdesc, &iter);
    537 			if (err != USBD_NORMAL_COMPLETION) {
    538 				DPRINTF(("uvideo_attach: error with interface "
    539 					 "%d, VideoControl, "
    540 					 "descriptor len=%d type=0x%02x: "
    541 					 "%s (%d)\n",
    542 					 ifdesc->bInterfaceNumber,
    543 					 ifdesc->bLength,
    544 					 ifdesc->bDescriptorType,
    545 					 usbd_errstr(err), err));
    546 			}
    547 			break;
    548 		case UISUBCLASS_VIDEOSTREAMING:
    549 			vs = uvideo_find_stream(sc, ifdesc->bInterfaceNumber);
    550 			if (vs == NULL) {
    551 				vs = uvideo_stream_alloc();
    552 				if (vs == NULL) {
    553 					DPRINTF(("uvideo_attach: "
    554 						 "failed to alloc stream\n"));
    555 					err = USBD_NOMEM;
    556 					goto bad;
    557 				}
    558 				err = uvideo_stream_init(vs, sc, ifdesc,
    559 							 ifaceidx);
    560 				if (err != USBD_NORMAL_COMPLETION) {
    561 					DPRINTF(("uvideo_attach: "
    562 						 "error initializing stream: "
    563 						 "%s (%d)\n",
    564 						 usbd_errstr(err), err));
    565 					goto bad;
    566 				}
    567 			}
    568 			err = uvideo_stream_init_desc(vs, ifdesc, &iter);
    569 			if (err != USBD_NORMAL_COMPLETION) {
    570 				DPRINTF(("uvideo_attach: "
    571 					 "error initializing stream descriptor: "
    572 					 "%s (%d)\n",
    573 					 usbd_errstr(err), err));
    574 				goto bad;
    575 			}
    576 			/* TODO: for now, set (each) stream to stream_in. */
    577 			sc->sc_stream_in = vs;
    578 			break;
    579 		case UISUBCLASS_VIDEOCOLLECTION:
    580 			err = uvideo_init_collection(sc, ifdesc, &iter);
    581 			if (err != USBD_NORMAL_COMPLETION) {
    582 				DPRINTF(("uvideo_attach: error with interface "
    583 				       "%d, VideoCollection, "
    584 				       "descriptor len=%d type=0x%02x: "
    585 				       "%s (%d)\n",
    586 				       ifdesc->bInterfaceNumber,
    587 				       ifdesc->bLength,
    588 				       ifdesc->bDescriptorType,
    589 				       usbd_errstr(err), err));
    590 				goto bad;
    591 			}
    592 			break;
    593 		default:
    594 			DPRINTF(("uvideo_attach: unknown UICLASS_VIDEO "
    595 				 "subclass=0x%02x\n",
    596 				 ifdesc->bInterfaceSubClass));
    597 			break;
    598 		}
    599 
    600 	}
    601 
    602 
    603 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    604 			   USBDEV(sc->sc_dev));
    605 
    606 	if (!pmf_device_register(self, NULL, NULL))
    607 		aprint_error_dev(self, "couldn't establish power handler\n");
    608 
    609 	sc->sc_videodev = video_attach_mi(&uvideo_hw_if, sc->sc_dev);
    610 	DPRINTF(("uvideo_attach: attached video driver at %p\n",
    611 		 sc->sc_videodev));
    612 
    613 	USB_ATTACH_SUCCESS_RETURN;
    614 
    615 bad:
    616 	if (err != USBD_NORMAL_COMPLETION) {
    617 		DPRINTF(("uvideo_attach: error: %s (%d)\n",
    618 			 usbd_errstr(err), err));
    619 	}
    620 	USB_ATTACH_ERROR_RETURN;
    621 }
    622 
    623 
    624 int
    625 uvideo_activate(device_t self, enum devact act)
    626 {
    627 	struct uvideo_softc *sc;
    628 	int rv;
    629 
    630 	sc = device_private(self);
    631 	rv = 0;
    632 	switch (act) {
    633 	case DVACT_ACTIVATE:
    634 		return EOPNOTSUPP;
    635 
    636 	case DVACT_DEACTIVATE:
    637 		DPRINTF(("uvideo_activate: deactivating\n"));
    638 		if (sc->sc_videodev != NULL)
    639 			rv = config_deactivate(sc->sc_videodev);
    640 		sc->sc_dying = 1;
    641 		break;
    642 	}
    643 	return rv;
    644 }
    645 
    646 
    647 /* Detach child (video interface) */
    648 void
    649 uvideo_childdet(device_t self, device_t child)
    650 {
    651 	struct uvideo_softc *sc = device_private(self);
    652 
    653 	KASSERT(sc->sc_videodev == child);
    654 	sc->sc_videodev = NULL;
    655 }
    656 
    657 
    658 int
    659 uvideo_detach(device_t self, int flags)
    660 {
    661 	struct uvideo_softc *sc;
    662 	struct uvideo_stream *vs;
    663 	int rv;
    664 
    665 	sc = device_private(self);
    666 	rv = 0;
    667 
    668 	sc->sc_dying = 1;
    669 
    670 	pmf_device_deregister(self);
    671 
    672 	usbd_devinfo_free(sc->sc_devname);
    673 
    674 	/* TODO: close the device if it is currently opened?  Or will
    675 	 * close be called automatically? */
    676 
    677 	while (!SLIST_EMPTY(&sc->sc_stream_list)) {
    678 		vs = SLIST_FIRST(&sc->sc_stream_list);
    679 		SLIST_REMOVE_HEAD(&sc->sc_stream_list, entries);
    680 		uvideo_stream_free(vs);
    681 	}
    682 
    683 	/* Wait for outstanding request to complete.  TODO: what is
    684 	 * appropriate here? */
    685 	usbd_delay_ms(sc->sc_udev, 1000);
    686 
    687 	DPRINTFN(15, ("uvideo: detaching from %s\n",
    688 		USBDEVNAME(sc->sc_dev)));
    689 
    690 	if (sc->sc_videodev != NULL)
    691 		rv = config_detach(sc->sc_videodev, flags);
    692 
    693 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    694 	    USBDEV(sc->sc_dev));
    695 
    696 	return rv;
    697 }
    698 
    699 /* Search the stream list for a stream matching the interface number.
    700  * This is an O(n) search, but most devices should have only one or at
    701  * most two streams. */
    702 static struct uvideo_stream *
    703 uvideo_find_stream(struct uvideo_softc *sc, uint8_t ifaceno)
    704 {
    705 	struct uvideo_stream *vs;
    706 
    707 	SLIST_FOREACH(vs, &sc->sc_stream_list, entries) {
    708 		if (vs->vs_ifaceno == ifaceno)
    709 			return vs;
    710 	}
    711 
    712 	return NULL;
    713 }
    714 
    715 /* Search the format list for the given format and frame index.  This
    716  * might be improved through indexing, but the format and frame count
    717  * is unknown ahead of time (only after iterating through the
    718  * usb device descriptors). */
    719 #if 0
    720 static struct uvideo_format *
    721 uvideo_stream_find_format(struct uvideo_stream *vs,
    722 			  uint8_t format_index, uint8_t frame_index)
    723 {
    724 	struct uvideo_format *format;
    725 
    726 	SIMPLEQ_FOREACH(format, &vs->vs_formats, entries) {
    727 		if (UVIDEO_FORMAT_GET_FORMAT_INDEX(format) == format_index &&
    728 		    UVIDEO_FORMAT_GET_FRAME_INDEX(format) == frame_index)
    729 			return format;
    730 	}
    731 	return NULL;
    732 }
    733 #endif
    734 
    735 static struct uvideo_format *
    736 uvideo_stream_guess_format(struct uvideo_stream *vs,
    737 			   enum video_pixel_format pixel_format,
    738 			   uint32_t width, uint32_t height)
    739 {
    740 	struct uvideo_format *format, *gformat = NULL;
    741 
    742 	SIMPLEQ_FOREACH(format, &vs->vs_formats, entries) {
    743 		if (format->format.pixel_format != pixel_format)
    744 			continue;
    745 		if (format->format.width <= width &&
    746 		    format->format.height <= height) {
    747 			if (gformat == NULL ||
    748 			    (gformat->format.width < format->format.width &&
    749 			     gformat->format.height < format->format.height))
    750 				gformat = format;
    751 		}
    752 	}
    753 
    754 	return gformat;
    755 }
    756 
    757 static struct uvideo_stream *
    758 uvideo_stream_alloc(void)
    759 {
    760 	return (kmem_alloc(sizeof(struct uvideo_stream), KM_NOSLEEP));
    761 }
    762 
    763 
    764 static usbd_status
    765 uvideo_init_control(struct uvideo_softc *sc,
    766 		    const usb_interface_descriptor_t *ifdesc,
    767 		    usbd_desc_iter_t *iter)
    768 {
    769 	const usb_descriptor_t *desc;
    770 	const uvideo_descriptor_t *uvdesc;
    771 	usbd_desc_iter_t orig;
    772 	uint8_t i, j, nunits;
    773 
    774 	/* save original iterator state */
    775 	memcpy(&orig, iter, sizeof(orig));
    776 
    777 	/* count number of units and terminals */
    778 	nunits = 0;
    779 	while ((desc = usb_desc_iter_next_non_interface(iter)) != NULL) {
    780 		uvdesc = (const uvideo_descriptor_t *)desc;
    781 
    782 		if (uvdesc->bDescriptorType != UDESC_CS_INTERFACE)
    783 			continue;
    784 		if (uvdesc->bDescriptorSubtype < UDESC_INPUT_TERMINAL ||
    785 		    uvdesc->bDescriptorSubtype > UDESC_EXTENSION_UNIT)
    786 			continue;
    787 		++nunits;
    788 	}
    789 
    790 	if (nunits == 0) {
    791 		DPRINTF(("uvideo_init_control: no units\n"));
    792 		return USBD_NORMAL_COMPLETION;
    793 	}
    794 
    795 	/* allocate space for units */
    796 	sc->sc_nunits = nunits;
    797 	sc->sc_unit = kmem_alloc(sizeof(*sc->sc_unit) * nunits, KM_SLEEP);
    798 	if (sc->sc_unit == NULL)
    799 		goto enomem;
    800 
    801 	/* restore original iterator state */
    802 	memcpy(iter, &orig, sizeof(orig));
    803 
    804 	/* iterate again, initializing the units */
    805 	i = 0;
    806 	while ((desc = usb_desc_iter_next_non_interface(iter)) != NULL) {
    807 		uvdesc = (const uvideo_descriptor_t *)desc;
    808 
    809 		if (uvdesc->bDescriptorType != UDESC_CS_INTERFACE)
    810 			continue;
    811 		if (uvdesc->bDescriptorSubtype < UDESC_INPUT_TERMINAL ||
    812 		    uvdesc->bDescriptorSubtype > UDESC_EXTENSION_UNIT)
    813 			continue;
    814 
    815 		sc->sc_unit[i] = uvideo_unit_alloc(uvdesc);
    816 		/* TODO: free other units before returning? */
    817 		if (sc->sc_unit[i] == NULL)
    818 			goto enomem;
    819 		++i;
    820 	}
    821 
    822 	return USBD_NORMAL_COMPLETION;
    823 
    824 enomem:
    825 	if (sc->sc_unit != NULL) {
    826 		for (j = 0; j < i; ++j) {
    827 			uvideo_unit_free(sc->sc_unit[j]);
    828 			sc->sc_unit[j] = NULL;
    829 		}
    830 		kmem_free(sc->sc_unit, sizeof(*sc->sc_unit) * nunits);
    831 		sc->sc_unit = NULL;
    832 	}
    833 	sc->sc_nunits = 0;
    834 
    835 	return USBD_NOMEM;
    836 }
    837 
    838 static usbd_status
    839 uvideo_init_collection(struct uvideo_softc *sc,
    840 		       const usb_interface_descriptor_t *ifdesc,
    841 		       usbd_desc_iter_t *iter)
    842 {
    843 	DPRINTF(("uvideo: ignoring Video Collection\n"));
    844 	return USBD_NORMAL_COMPLETION;
    845 }
    846 
    847 /* Allocates space for and initializes a uvideo unit based on the
    848  * given descriptor.  Returns NULL with bad descriptor or ENOMEM. */
    849 static struct uvideo_unit *
    850 uvideo_unit_alloc(const uvideo_descriptor_t *desc)
    851 {
    852 	struct uvideo_unit *vu;
    853 	usbd_status err;
    854 
    855 	if (desc->bDescriptorType != UDESC_CS_INTERFACE)
    856 		return NULL;
    857 
    858 	vu = kmem_alloc(sizeof(*vu), KM_SLEEP);
    859 	if (vu == NULL)
    860 		return NULL;
    861 
    862 	err = uvideo_unit_init(vu, desc);
    863 	if (err != USBD_NORMAL_COMPLETION) {
    864 		DPRINTF(("uvideo_unit_alloc: error initializing unit: "
    865 			 "%s (%d)\n", usbd_errstr(err), err));
    866 		kmem_free(vu, sizeof(*vu));
    867 		return NULL;
    868 	}
    869 
    870 	return vu;
    871 }
    872 
    873 static usbd_status
    874 uvideo_unit_init(struct uvideo_unit *vu, const uvideo_descriptor_t *desc)
    875 {
    876 	struct uvideo_camera_terminal *ct;
    877 	struct uvideo_processing_unit *pu;
    878 	struct uvideo_extension_unit *xu;
    879 
    880 	const uvideo_input_terminal_descriptor_t *input;
    881 	const uvideo_output_terminal_descriptor_t *output;
    882 	const uvideo_camera_terminal_descriptor_t *camera;
    883 	const uvideo_selector_unit_descriptor_t *selector;
    884 	const uvideo_processing_unit_descriptor_t *processing;
    885 	const uvideo_extension_unit_descriptor_t *extension;
    886 
    887 	memset(vu, 0, sizeof(*vu));
    888 
    889 	switch (desc->bDescriptorSubtype) {
    890 	case UDESC_INPUT_TERMINAL:
    891 		input = (const uvideo_input_terminal_descriptor_t *)desc;
    892 		switch (UGETW(input->wTerminalType)) {
    893 		case UVIDEO_ITT_CAMERA:
    894 			camera =
    895 			    (const uvideo_camera_terminal_descriptor_t *)desc;
    896 			ct = &vu->u.vu_camera;
    897 
    898 			ct->ct_objective_focal_min =
    899 			    UGETW(camera->wObjectiveFocalLengthMin);
    900 			ct->ct_objective_focal_max =
    901 			    UGETW(camera->wObjectiveFocalLengthMax);
    902 			ct->ct_ocular_focal_length =
    903 			    UGETW(camera->wOcularFocalLength);
    904 
    905 			uvideo_unit_alloc_controls(vu, camera->bControlSize,
    906 						   camera->bmControls);
    907 			break;
    908 		default:
    909 			DPRINTF(("uvideo_unit_init: "
    910 				 "unknown input terminal type 0x%04x\n",
    911 				 UGETW(input->wTerminalType)));
    912 			return USBD_INVAL;
    913 		}
    914 		break;
    915 	case UDESC_OUTPUT_TERMINAL:
    916 		output = (const uvideo_output_terminal_descriptor_t *)desc;
    917 		break;
    918 	case UDESC_SELECTOR_UNIT:
    919 		selector = (const uvideo_selector_unit_descriptor_t *)desc;
    920 
    921 		uvideo_unit_alloc_sources(vu, selector->bNrInPins,
    922 					  selector->baSourceID);
    923 		break;
    924 	case UDESC_PROCESSING_UNIT:
    925 		processing = (const uvideo_processing_unit_descriptor_t *)desc;
    926 		pu = &vu->u.vu_processing;
    927 
    928 		pu->pu_video_standards = PU_GET_VIDEO_STANDARDS(processing);
    929 		pu->pu_max_multiplier = UGETW(processing->wMaxMultiplier);
    930 
    931 		uvideo_unit_alloc_sources(vu, 1, &processing->bSourceID);
    932 		uvideo_unit_alloc_controls(vu, processing->bControlSize,
    933 					   processing->bmControls);
    934 		break;
    935 	case UDESC_EXTENSION_UNIT:
    936 		extension = (const uvideo_extension_unit_descriptor_t *)desc;
    937 		xu = &vu->u.vu_extension;
    938 		/* TODO: copy guid */
    939 
    940 		uvideo_unit_alloc_sources(vu, extension->bNrInPins,
    941 					  extension->baSourceID);
    942 		uvideo_unit_alloc_controls(vu, XU_GET_CONTROL_SIZE(extension),
    943 					   XU_GET_CONTROLS(extension));
    944 		break;
    945 	default:
    946 		DPRINTF(("uvideo_unit_alloc: unknown descriptor "
    947 			 "type=0x%02x subtype=0x%02x\n",
    948 			 desc->bDescriptorType, desc->bDescriptorSubtype));
    949 		return USBD_INVAL;
    950 	}
    951 
    952 	return USBD_NORMAL_COMPLETION;
    953 }
    954 
    955 static void
    956 uvideo_unit_free(struct uvideo_unit *vu)
    957 {
    958 	uvideo_unit_free_sources(vu);
    959 	uvideo_unit_free_controls(vu);
    960 	kmem_free(vu, sizeof(*vu));
    961 }
    962 
    963 static usbd_status
    964 uvideo_unit_alloc_sources(struct uvideo_unit *vu,
    965 			  uint8_t nsrcs, const uint8_t *src_ids)
    966 {
    967 	vu->vu_nsrcs = nsrcs;
    968 
    969 	if (nsrcs == 0) {
    970 		/* do nothing */
    971 	} else if (nsrcs == 1) {
    972 		vu->s.vu_src_id = src_ids[0];
    973 	} else {
    974 		vu->s.vu_src_id_ary =
    975 		    kmem_alloc(sizeof(*vu->s.vu_src_id_ary) * nsrcs, KM_SLEEP);
    976 		if (vu->s.vu_src_id_ary == NULL) {
    977 			vu->vu_nsrcs = 0;
    978 			return USBD_NOMEM;
    979 		}
    980 
    981 		memcpy(vu->s.vu_src_id_ary, src_ids, nsrcs);
    982 	}
    983 
    984 	return USBD_NORMAL_COMPLETION;
    985 }
    986 
    987 static void
    988 uvideo_unit_free_sources(struct uvideo_unit *vu)
    989 {
    990 	if (vu->vu_nsrcs == 1)
    991 		return;
    992 
    993 	kmem_free(vu->s.vu_src_id_ary,
    994 		  sizeof(*vu->s.vu_src_id_ary) * vu->vu_nsrcs);
    995 	vu->vu_nsrcs = 0;
    996 	vu->s.vu_src_id_ary = NULL;
    997 }
    998 
    999 static usbd_status
   1000 uvideo_unit_alloc_controls(struct uvideo_unit *vu, uint8_t size,
   1001 			   const uint8_t *controls)
   1002 {
   1003 	vu->vu_controls = kmem_alloc(sizeof(*vu->vu_controls) * size, KM_SLEEP);
   1004 	if (vu->vu_controls == NULL)
   1005 		return USBD_NOMEM;
   1006 
   1007 	vu->vu_control_size = size;
   1008 	memcpy(vu->vu_controls, controls, size);
   1009 
   1010 	return USBD_NORMAL_COMPLETION;
   1011 }
   1012 
   1013 static void
   1014 uvideo_unit_free_controls(struct uvideo_unit *vu)
   1015 {
   1016 	kmem_free(vu->vu_controls,
   1017 		  sizeof(*vu->vu_controls) * vu->vu_control_size);
   1018 	vu->vu_controls = NULL;
   1019 	vu->vu_control_size = 0;
   1020 }
   1021 
   1022 
   1023 /* Initialize a stream from a Video Streaming interface
   1024  * descriptor. Adds the stream to the stream_list in uvideo_softc.
   1025  * This should be called once for new streams, and
   1026  * uvideo_stream_init_desc() should then be called for this and each
   1027  * additional interface with the same interface number. */
   1028 static usbd_status
   1029 uvideo_stream_init(struct uvideo_stream *vs,
   1030 		   struct uvideo_softc *sc,
   1031 		   const usb_interface_descriptor_t *ifdesc,
   1032 		   uint8_t idx)
   1033 {
   1034 	uWord len;
   1035 	usbd_status err;
   1036 
   1037 	SLIST_INSERT_HEAD(&sc->sc_stream_list, vs, entries);
   1038 	memset(vs, 0, sizeof(*vs));
   1039 	vs->vs_parent = sc;
   1040 	vs->vs_ifaceno = ifdesc->bInterfaceNumber;
   1041 	vs->vs_subtype = 0;
   1042 	SIMPLEQ_INIT(&vs->vs_formats);
   1043 	SIMPLEQ_INIT(&vs->vs_pixel_formats);
   1044 	vs->vs_default_format = NULL;
   1045 	vs->vs_current_format.priv = -1;
   1046 	vs->vs_xfer_type = 0;
   1047 
   1048 	err = usbd_device2interface_handle(sc->sc_udev, idx, &vs->vs_iface);
   1049 	if (err != USBD_NORMAL_COMPLETION) {
   1050 		DPRINTF(("uvideo_stream_init: "
   1051 			 "error getting vs interface: "
   1052 			 "%s (%d)\n",
   1053 			 usbd_errstr(err), err));
   1054 		return err;
   1055 	}
   1056 
   1057 	/* For Xbox Live Vision camera, linux-uvc folk say we need to
   1058 	 * set an alternate interface and wait ~3 seconds prior to
   1059 	 * doing the format probe/commit.  We set to alternate
   1060 	 * interface 0, which is the default, zero bandwidth
   1061 	 * interface.  This should not have adverse affects on other
   1062 	 * cameras.  Errors are ignored. */
   1063 	err = usbd_set_interface(vs->vs_iface, 0);
   1064 	if (err != USBD_NORMAL_COMPLETION) {
   1065 		DPRINTF(("uvideo_stream_init: error setting alt interface: "
   1066 			 "%s (%d)\n",
   1067 			 usbd_errstr(err), err));
   1068 	}
   1069 
   1070 	/* Initialize probe and commit data size.  This value is
   1071 	 * dependent on the version of the spec the hardware
   1072 	 * implements. */
   1073 	err = uvideo_stream_probe(vs, UR_GET_LEN, len);
   1074 	if (err != USBD_NORMAL_COMPLETION) {
   1075 		DPRINTF(("uvideo_stream_init: "
   1076 			 "error getting probe data len: "
   1077 			 "%s (%d)\n",
   1078 			 usbd_errstr(err), err));
   1079 		vs->vs_probelen = 26; /* conservative v1.0 length */
   1080 	} else {
   1081 		DPRINTFN(15,("uvideo_stream_init: probelen=%d\n", UGETW(len)));
   1082 		vs->vs_probelen = UGETW(len);
   1083 	}
   1084 
   1085 	return USBD_NORMAL_COMPLETION;
   1086 }
   1087 
   1088 /* Further stream initialization based on a Video Streaming interface
   1089  * descriptor and following descriptors belonging to that interface.
   1090  * Iterates through all descriptors belonging to this particular
   1091  * interface descriptor, modifying the iterator.  This may be called
   1092  * multiple times because there may be several alternate interfaces
   1093  * associated with the same interface number. */
   1094 static usbd_status
   1095 uvideo_stream_init_desc(struct uvideo_stream *vs,
   1096 			const usb_interface_descriptor_t *ifdesc,
   1097 			usbd_desc_iter_t *iter)
   1098 {
   1099 	const usb_descriptor_t *desc;
   1100 	const uvideo_descriptor_t *uvdesc;
   1101 	struct uvideo_bulk_xfer *bx;
   1102 	struct uvideo_isoc_xfer *ix;
   1103 	struct uvideo_alternate *alt;
   1104 	uint8_t xfer_type, xfer_dir;
   1105 	uint8_t bmAttributes, bEndpointAddress;
   1106 	int i;
   1107 
   1108 	/* Iterate until the next interface descriptor.  All
   1109 	 * descriptors until then belong to this streaming
   1110 	 * interface. */
   1111 	while ((desc = usb_desc_iter_next_non_interface(iter)) != NULL) {
   1112 		uvdesc = (const uvideo_descriptor_t *)desc;
   1113 
   1114 		switch (uvdesc->bDescriptorType) {
   1115 		case UDESC_ENDPOINT:
   1116 			bmAttributes = GET(usb_endpoint_descriptor_t,
   1117 					   desc, bmAttributes);
   1118 			bEndpointAddress = GET(usb_endpoint_descriptor_t,
   1119 					       desc, bEndpointAddress);
   1120 			xfer_type = UE_GET_XFERTYPE(bmAttributes);
   1121 			xfer_dir = UE_GET_DIR(bEndpointAddress);
   1122 			if (xfer_type == UE_BULK && xfer_dir == UE_DIR_IN) {
   1123 				bx = &vs->vs_xfer.bulk;
   1124 				if (vs->vs_xfer_type == 0) {
   1125 					DPRINTFN(15, ("uvideo_attach: "
   1126 						      "BULK stream *\n"));
   1127 					vs->vs_xfer_type = UE_BULK;
   1128 					bx->bx_endpt = bEndpointAddress;
   1129 					DPRINTF(("uvideo_attach: BULK "
   1130 						 "endpoint %x\n",
   1131 						 bx->bx_endpt));
   1132 					bx->bx_running = false;
   1133 					cv_init(&bx->bx_cv,
   1134 					    device_xname(vs->vs_parent->sc_dev)
   1135 					    );
   1136 					mutex_init(&bx->bx_lock,
   1137 					  MUTEX_DEFAULT, IPL_NONE);
   1138 				}
   1139 			} else if (xfer_type == UE_ISOCHRONOUS) {
   1140 				ix = &vs->vs_xfer.isoc;
   1141 				for (i = 0; i < UVIDEO_NXFERS; i++) {
   1142 					ix->ix_i[i].i_ix = ix;
   1143 					ix->ix_i[i].i_vs = vs;
   1144 				}
   1145 				if (vs->vs_xfer_type == 0) {
   1146 					DPRINTFN(15, ("uvideo_attach: "
   1147 						      "ISOC stream *\n"));
   1148 					SLIST_INIT(&ix->ix_altlist);
   1149 					vs->vs_xfer_type = UE_ISOCHRONOUS;
   1150 					ix->ix_endpt =
   1151 					    GET(usb_endpoint_descriptor_t,
   1152 						desc, bEndpointAddress);
   1153 				}
   1154 
   1155 				alt = kmem_alloc(sizeof(*alt), KM_NOSLEEP);
   1156 				if (alt == NULL)
   1157 					return USBD_NOMEM;
   1158 
   1159 				alt->altno = ifdesc->bAlternateSetting;
   1160 				alt->interval =
   1161 				    GET(usb_endpoint_descriptor_t,
   1162 					desc, bInterval);
   1163 
   1164 				alt->max_packet_size =
   1165 				UE_GET_SIZE(UGETW(GET(usb_endpoint_descriptor_t,
   1166 					desc, wMaxPacketSize)));
   1167 				alt->max_packet_size *=
   1168 					(UE_GET_TRANS(UGETW(GET(
   1169 						usb_endpoint_descriptor_t, desc,
   1170 						wMaxPacketSize)))) + 1;
   1171 
   1172 				SLIST_INSERT_HEAD(&ix->ix_altlist,
   1173 						  alt, entries);
   1174 			}
   1175 			break;
   1176 		case UDESC_CS_INTERFACE:
   1177 			if (ifdesc->bAlternateSetting != 0) {
   1178 				DPRINTF(("uvideo_stream_init_alternate: "
   1179 					 "unexpected class-specific descriptor "
   1180 					 "len=%d type=0x%02x subtype=0x%02x\n",
   1181 					 uvdesc->bLength,
   1182 					 uvdesc->bDescriptorType,
   1183 					 uvdesc->bDescriptorSubtype));
   1184 				break;
   1185 			}
   1186 
   1187 			switch (uvdesc->bDescriptorSubtype) {
   1188 			case UDESC_VS_INPUT_HEADER:
   1189 				vs->vs_subtype = UDESC_VS_INPUT_HEADER;
   1190 				break;
   1191 			case UDESC_VS_OUTPUT_HEADER:
   1192 				/* TODO: handle output stream */
   1193 				DPRINTF(("uvideo: VS output not implemented\n"));
   1194 				vs->vs_subtype = UDESC_VS_OUTPUT_HEADER;
   1195 				return USBD_INVAL;
   1196 			case UDESC_VS_FORMAT_UNCOMPRESSED:
   1197 			case UDESC_VS_FORMAT_FRAME_BASED:
   1198 			case UDESC_VS_FORMAT_MJPEG:
   1199 				uvideo_stream_init_frame_based_format(vs,
   1200 								      uvdesc,
   1201 								      iter);
   1202 				break;
   1203 			case UDESC_VS_FORMAT_MPEG2TS:
   1204 			case UDESC_VS_FORMAT_DV:
   1205 			case UDESC_VS_FORMAT_STREAM_BASED:
   1206 			default:
   1207 				DPRINTF(("uvideo: unimplemented VS CS "
   1208 					 "descriptor len=%d type=0x%02x "
   1209 					 "subtype=0x%02x\n",
   1210 					 uvdesc->bLength,
   1211 					 uvdesc->bDescriptorType,
   1212 					 uvdesc->bDescriptorSubtype));
   1213 				break;
   1214 			}
   1215 			break;
   1216 		default:
   1217 			DPRINTF(("uvideo_stream_init_desc: "
   1218 				 "unknown descriptor "
   1219 				 "len=%d type=0x%02x\n",
   1220 				 uvdesc->bLength,
   1221 				 uvdesc->bDescriptorType));
   1222 			break;
   1223 		}
   1224 	}
   1225 
   1226 	return USBD_NORMAL_COMPLETION;
   1227 }
   1228 
   1229 /* Finialize and free memory associated with this stream. */
   1230 static void
   1231 uvideo_stream_free(struct uvideo_stream *vs)
   1232 {
   1233 	struct uvideo_alternate *alt;
   1234 	struct uvideo_pixel_format *pixel_format;
   1235 	struct uvideo_format *format;
   1236 
   1237 	/* free linked list of alternate interfaces */
   1238 	if (vs->vs_xfer_type == UE_ISOCHRONOUS) {
   1239 		while (!SLIST_EMPTY(&vs->vs_xfer.isoc.ix_altlist)) {
   1240 			alt = SLIST_FIRST(&vs->vs_xfer.isoc.ix_altlist);
   1241 			SLIST_REMOVE_HEAD(&vs->vs_xfer.isoc.ix_altlist,
   1242 					  entries);
   1243 			kmem_free(alt, sizeof(*alt));
   1244 		}
   1245 	}
   1246 
   1247 	/* free linked-list of formats and pixel formats */
   1248 	while ((format = SIMPLEQ_FIRST(&vs->vs_formats)) != NULL) {
   1249 		SIMPLEQ_REMOVE_HEAD(&vs->vs_formats, entries);
   1250 		kmem_free(format, sizeof(struct uvideo_format));
   1251 	}
   1252 	while ((pixel_format = SIMPLEQ_FIRST(&vs->vs_pixel_formats)) != NULL) {
   1253 		SIMPLEQ_REMOVE_HEAD(&vs->vs_pixel_formats, entries);
   1254 		kmem_free(pixel_format, sizeof(struct uvideo_pixel_format));
   1255 	}
   1256 
   1257 	kmem_free(vs, sizeof(*vs));
   1258 }
   1259 
   1260 
   1261 static usbd_status
   1262 uvideo_stream_init_frame_based_format(struct uvideo_stream *vs,
   1263 				      const uvideo_descriptor_t *format_desc,
   1264 				      usbd_desc_iter_t *iter)
   1265 {
   1266 	struct uvideo_pixel_format *pformat, *pfiter;
   1267 	enum video_pixel_format pixel_format;
   1268 	struct uvideo_format *format;
   1269 	const uvideo_descriptor_t *uvdesc;
   1270 	uint8_t subtype, default_index, index;
   1271 	uint32_t frame_interval;
   1272 	const usb_guid_t *guid;
   1273 
   1274 	pixel_format = VIDEO_FORMAT_UNDEFINED;
   1275 
   1276 	switch (format_desc->bDescriptorSubtype) {
   1277 	case UDESC_VS_FORMAT_UNCOMPRESSED:
   1278 		subtype = UDESC_VS_FRAME_UNCOMPRESSED;
   1279 		default_index = GET(uvideo_vs_format_uncompressed_descriptor_t,
   1280 				    format_desc,
   1281 				    bDefaultFrameIndex);
   1282 		guid = GETP(uvideo_vs_format_uncompressed_descriptor_t,
   1283 			    format_desc,
   1284 			    guidFormat);
   1285 		if (usb_guid_cmp(guid, &uvideo_guid_format_yuy2) == 0)
   1286 			pixel_format = VIDEO_FORMAT_YUY2;
   1287 		else if (usb_guid_cmp(guid, &uvideo_guid_format_nv12) == 0)
   1288 			pixel_format = VIDEO_FORMAT_NV12;
   1289 		else if (usb_guid_cmp(guid, &uvideo_guid_format_uyvy) == 0)
   1290 			pixel_format = VIDEO_FORMAT_UYVY;
   1291 		break;
   1292 	case UDESC_VS_FORMAT_FRAME_BASED:
   1293 		subtype = UDESC_VS_FRAME_FRAME_BASED;
   1294 		default_index = GET(uvideo_format_frame_based_descriptor_t,
   1295 				    format_desc,
   1296 				    bDefaultFrameIndex);
   1297 		break;
   1298 	case UDESC_VS_FORMAT_MJPEG:
   1299 		subtype = UDESC_VS_FRAME_MJPEG;
   1300 		default_index = GET(uvideo_vs_format_mjpeg_descriptor_t,
   1301 				    format_desc,
   1302 				    bDefaultFrameIndex);
   1303 		pixel_format = VIDEO_FORMAT_MJPEG;
   1304 		break;
   1305 	default:
   1306 		DPRINTF(("uvideo: unknown frame based format %d\n",
   1307 			 format_desc->bDescriptorSubtype));
   1308 		return USBD_INVAL;
   1309 	}
   1310 
   1311 	pformat = NULL;
   1312 	SIMPLEQ_FOREACH(pfiter, &vs->vs_pixel_formats, entries) {
   1313 		if (pfiter->pixel_format == pixel_format) {
   1314 			pformat = pfiter;
   1315 			break;
   1316 		}
   1317 	}
   1318 	if (pixel_format != VIDEO_FORMAT_UNDEFINED && pformat == NULL) {
   1319 		pformat = kmem_zalloc(sizeof(*pformat), KM_SLEEP);
   1320 		pformat->pixel_format = pixel_format;
   1321 		DPRINTF(("uvideo: Adding pixel format %d\n",
   1322 		    pixel_format));
   1323 		SIMPLEQ_INSERT_TAIL(&vs->vs_pixel_formats,
   1324 		    pformat, entries);
   1325 	}
   1326 
   1327 	/* Iterate through frame descriptors directly following the
   1328 	 * format descriptor, and add a format to the format list for
   1329 	 * each frame descriptor. */
   1330 	while ((uvdesc = (const uvideo_descriptor_t *) usb_desc_iter_peek_next(iter)) &&
   1331 	       (uvdesc != NULL) && (uvdesc->bDescriptorSubtype == subtype))
   1332 	{
   1333 		uvdesc = (const uvideo_descriptor_t *) usb_desc_iter_next(iter);
   1334 
   1335 		format = kmem_zalloc(sizeof(struct uvideo_format), KM_SLEEP);
   1336 		if (format == NULL) {
   1337 			DPRINTF(("uvideo: failed to alloc video format\n"));
   1338 			return USBD_NOMEM;
   1339 		}
   1340 
   1341 		format->format.pixel_format = pixel_format;
   1342 
   1343 		switch (format_desc->bDescriptorSubtype) {
   1344 		case UDESC_VS_FORMAT_UNCOMPRESSED:
   1345 #ifdef UVIDEO_DEBUG
   1346 			if (pixel_format == VIDEO_FORMAT_UNDEFINED &&
   1347 			    uvideodebug) {
   1348 				guid = GETP(
   1349 				    uvideo_vs_format_uncompressed_descriptor_t,
   1350 				    format_desc,
   1351 				    guidFormat);
   1352 
   1353 				DPRINTF(("uvideo: format undefined "));
   1354 				usb_guid_print(guid);
   1355 				DPRINTF(("\n"));
   1356 			}
   1357 #endif
   1358 
   1359 			UVIDEO_FORMAT_INIT_FRAME_BASED(
   1360 				uvideo_vs_format_uncompressed_descriptor_t,
   1361 				format_desc,
   1362 				uvideo_vs_frame_uncompressed_descriptor_t,
   1363 				uvdesc,
   1364 				format);
   1365 			format->format.sample_size =
   1366 			    UGETDW(
   1367 			      GET(uvideo_vs_frame_uncompressed_descriptor_t,
   1368 			      uvdesc, dwMaxVideoFrameBufferSize));
   1369 			format->format.stride =
   1370 			    format->format.sample_size / format->format.height;
   1371 			index = GET(uvideo_vs_frame_uncompressed_descriptor_t,
   1372 				    uvdesc,
   1373 				    bFrameIndex);
   1374 			frame_interval =
   1375 			    UGETDW(
   1376 				GET(uvideo_vs_frame_uncompressed_descriptor_t,
   1377 				uvdesc,
   1378 				dwDefaultFrameInterval));
   1379 			break;
   1380 		case UDESC_VS_FORMAT_MJPEG:
   1381 			UVIDEO_FORMAT_INIT_FRAME_BASED(
   1382 				uvideo_vs_format_mjpeg_descriptor_t,
   1383 				format_desc,
   1384 				uvideo_vs_frame_mjpeg_descriptor_t,
   1385 				uvdesc,
   1386 				format);
   1387 			format->format.sample_size =
   1388 			    UGETDW(
   1389 				GET(uvideo_vs_frame_mjpeg_descriptor_t,
   1390 			        uvdesc, dwMaxVideoFrameBufferSize));
   1391 			format->format.stride =
   1392 			    format->format.sample_size / format->format.height;
   1393 			index = GET(uvideo_vs_frame_mjpeg_descriptor_t,
   1394 				    uvdesc,
   1395 				    bFrameIndex);
   1396 			frame_interval =
   1397 			    UGETDW(
   1398 				GET(uvideo_vs_frame_mjpeg_descriptor_t,
   1399 				uvdesc,
   1400 				dwDefaultFrameInterval));
   1401 			break;
   1402 		case UDESC_VS_FORMAT_FRAME_BASED:
   1403 			format->format.pixel_format = VIDEO_FORMAT_UNDEFINED;
   1404 			UVIDEO_FORMAT_INIT_FRAME_BASED(
   1405 				uvideo_format_frame_based_descriptor_t,
   1406 				format_desc,
   1407 				uvideo_frame_frame_based_descriptor_t,
   1408 				uvdesc,
   1409 				format);
   1410 			index = GET(uvideo_frame_frame_based_descriptor_t,
   1411 				    uvdesc,
   1412 				    bFrameIndex);
   1413 			format->format.stride =
   1414 			    UGETDW(
   1415 				GET(uvideo_frame_frame_based_descriptor_t,
   1416 			        uvdesc, dwBytesPerLine));
   1417 			format->format.sample_size =
   1418 			    format->format.stride * format->format.height;
   1419 			frame_interval =
   1420 			    UGETDW(
   1421 				GET(uvideo_frame_frame_based_descriptor_t,
   1422 				uvdesc, dwDefaultFrameInterval));
   1423 			break;
   1424 		default:
   1425 			/* shouldn't ever get here */
   1426 			DPRINTF(("uvideo: unknown frame based format %d\n",
   1427 				 format_desc->bDescriptorSubtype));
   1428 			kmem_free(format, sizeof(struct uvideo_format));
   1429 			return USBD_INVAL;
   1430 		}
   1431 
   1432 		DPRINTF(("uvideo: found format (index %d) type %d "
   1433 		    "size %ux%u size %u stride %u interval %u\n",
   1434 		    index, format->format.pixel_format, format->format.width,
   1435 		    format->format.height, format->format.sample_size,
   1436 		    format->format.stride, frame_interval));
   1437 
   1438 		SIMPLEQ_INSERT_TAIL(&vs->vs_formats, format, entries);
   1439 
   1440 		if (vs->vs_default_format == NULL && index == default_index
   1441 #ifdef UVIDEO_DISABLE_MJPEG
   1442 		    && subtype != UDESC_VS_FRAME_MJPEG
   1443 #endif
   1444 		    ) {
   1445 			DPRINTF((" ^ picking this one\n"));
   1446 			vs->vs_default_format = &format->format;
   1447 			vs->vs_frame_interval = frame_interval;
   1448 		}
   1449 
   1450 	}
   1451 
   1452 	return USBD_NORMAL_COMPLETION;
   1453 }
   1454 
   1455 static int
   1456 uvideo_stream_start_xfer(struct uvideo_stream *vs)
   1457 {
   1458 	struct uvideo_softc *sc = vs->vs_parent;
   1459 	struct uvideo_bulk_xfer *bx;
   1460 	struct uvideo_isoc_xfer *ix;
   1461 	uint32_t vframe_len;	/* rough bytes per video frame */
   1462 	uint32_t uframe_len;	/* bytes per usb frame (TODO: or microframe?) */
   1463 	uint32_t nframes;	/* number of usb frames (TODO: or microframs?) */
   1464 	int i, ret;
   1465 
   1466 	struct uvideo_alternate *alt, *alt_maybe;
   1467 	usbd_status err;
   1468 
   1469 	switch (vs->vs_xfer_type) {
   1470 	case UE_BULK:
   1471 		ret = 0;
   1472 		bx = &vs->vs_xfer.bulk;
   1473 
   1474 		bx->bx_xfer = usbd_alloc_xfer(sc->sc_udev);
   1475 		if (bx->bx_xfer == NULL) {
   1476 			DPRINTF(("uvideo: couldn't allocate xfer\n"));
   1477 			return ENOMEM;
   1478 		}
   1479 		DPRINTF(("uvideo: xfer %p\n", bx->bx_xfer));
   1480 
   1481 		bx->bx_buflen = vs->vs_max_payload_size;
   1482 
   1483 		DPRINTF(("uvideo: allocating %u byte buffer\n", bx->bx_buflen));
   1484 		bx->bx_buffer = usbd_alloc_buffer(bx->bx_xfer, bx->bx_buflen);
   1485 
   1486 		if (bx->bx_buffer == NULL) {
   1487 			DPRINTF(("uvideo: couldn't allocate buffer\n"));
   1488 			return ENOMEM;
   1489 		}
   1490 
   1491 		err = usbd_open_pipe(vs->vs_iface, bx->bx_endpt, 0,
   1492 		    &bx->bx_pipe);
   1493 		if (err != USBD_NORMAL_COMPLETION) {
   1494 			DPRINTF(("uvideo: error opening pipe: %s (%d)\n",
   1495 				 usbd_errstr(err), err));
   1496 			return EIO;
   1497 		}
   1498 		DPRINTF(("uvideo: pipe %p\n", bx->bx_pipe));
   1499 
   1500 		mutex_enter(&bx->bx_lock);
   1501 		if (bx->bx_running == false) {
   1502 			bx->bx_running = true;
   1503 			ret = kthread_create(PRI_UVIDEO, 0, NULL,
   1504 			    uvideo_stream_recv_bulk_transfer, vs,
   1505 			    NULL, device_xname(sc->sc_dev));
   1506 			if (ret) {
   1507 				DPRINTF(("uvideo: couldn't create kthread:"
   1508 					 " %d\n", err));
   1509 				bx->bx_running = false;
   1510 				mutex_exit(&bx->bx_lock);
   1511 				return err;
   1512 			}
   1513 		} else
   1514 			aprint_error_dev(sc->sc_dev,
   1515 			    "transfer already in progress\n");
   1516 		mutex_exit(&bx->bx_lock);
   1517 
   1518 		DPRINTF(("uvideo: thread created\n"));
   1519 
   1520 		return 0;
   1521 	case UE_ISOCHRONOUS:
   1522 		ix = &vs->vs_xfer.isoc;
   1523 
   1524 		/* Choose an alternate interface most suitable for
   1525 		 * this format.  Choose the smallest size that can
   1526 		 * contain max_payload_size.
   1527 		 *
   1528 		 * It is assumed that the list is sorted in descending
   1529 		 * order from largest to smallest packet size.
   1530 		 *
   1531 		 * TODO: what should the strategy be for choosing an
   1532 		 * alt interface?
   1533 		 */
   1534 		alt = NULL;
   1535 		SLIST_FOREACH(alt_maybe, &ix->ix_altlist, entries) {
   1536 			/* TODO: define "packet" and "payload".  I think
   1537 			 * several packets can make up one payload which would
   1538 			 * call into question this method of selecting an
   1539 			 * alternate interface... */
   1540 
   1541 			if (alt == NULL ||
   1542 			    alt_maybe->max_packet_size >= alt->max_packet_size)
   1543 				alt = alt_maybe;
   1544 		}
   1545 
   1546 		if (alt == NULL) {
   1547 			DPRINTF(("uvideo_stream_start_xfer: "
   1548 				 "no suitable alternate interface found\n"));
   1549 			return EINVAL;
   1550 		}
   1551 
   1552 		DPRINTFN(15,("uvideo_stream_start_xfer: "
   1553 			     "choosing alternate interface "
   1554 			     "%d wMaxPacketSize=%d bInterval=%d\n",
   1555 			     alt->altno, alt->max_packet_size, alt->interval));
   1556 
   1557 		err = usbd_set_interface(vs->vs_iface, alt->altno);
   1558 		if (err != USBD_NORMAL_COMPLETION) {
   1559 			DPRINTF(("uvideo_stream_start_xfer: "
   1560 				 "error setting alt interface: %s (%d)\n",
   1561 				 usbd_errstr(err), err));
   1562 			return EIO;
   1563 		}
   1564 
   1565 		/* TODO: "packet" not same as frame */
   1566 		vframe_len = vs->vs_current_format.sample_size;
   1567 		uframe_len = alt->max_packet_size;
   1568 		nframes = (vframe_len + uframe_len - 1) / uframe_len;
   1569 		DPRINTF(("uvideo_stream_start_xfer: nframes=%d\n", nframes));
   1570 
   1571 		ix->ix_nframes = nframes;
   1572 		ix->ix_uframe_len = uframe_len;
   1573 		for (i = 0; i < UVIDEO_NXFERS; i++) {
   1574 			struct uvideo_isoc *isoc = &ix->ix_i[i];
   1575 			isoc->i_frlengths =
   1576 			    kmem_alloc(sizeof(isoc->i_frlengths[0]) * nframes,
   1577 				KM_SLEEP);
   1578 			if (isoc->i_frlengths == NULL) {
   1579 				DPRINTF(("uvideo: failed to alloc frlengths:"
   1580 				 "%s (%d)\n",
   1581 				 usbd_errstr(err), err));
   1582 				return ENOMEM;
   1583 			}
   1584 		}
   1585 
   1586 		err = usbd_open_pipe(vs->vs_iface, ix->ix_endpt,
   1587 				     USBD_EXCLUSIVE_USE, &ix->ix_pipe);
   1588 		if (err != USBD_NORMAL_COMPLETION) {
   1589 			DPRINTF(("uvideo: error opening pipe: %s (%d)\n",
   1590 				 usbd_errstr(err), err));
   1591 			return EIO;
   1592 		}
   1593 
   1594 		for (i = 0; i < UVIDEO_NXFERS; i++) {
   1595 			struct uvideo_isoc *isoc = &ix->ix_i[i];
   1596 			isoc->i_xfer = usbd_alloc_xfer(sc->sc_udev);
   1597 			if (isoc->i_xfer == NULL) {
   1598 				DPRINTF(("uvideo: failed to alloc xfer: %s"
   1599 				 " (%d)\n",
   1600 				 usbd_errstr(err), err));
   1601 				return ENOMEM;
   1602 			}
   1603 
   1604 			isoc->i_buf = usbd_alloc_buffer(isoc->i_xfer,
   1605 					       nframes * uframe_len);
   1606 
   1607 			if (isoc->i_xfer == NULL) {
   1608 				DPRINTF(("uvideo: failed to alloc buf: %s"
   1609 				 " (%d)\n",
   1610 				 usbd_errstr(err), err));
   1611 				return ENOMEM;
   1612 			}
   1613 		}
   1614 
   1615 		uvideo_stream_recv_isoc_start(vs);
   1616 
   1617 		return 0;
   1618 	default:
   1619 		/* should never get here */
   1620 		DPRINTF(("uvideo_stream_start_xfer: unknown xfer type 0x%x\n",
   1621 			 vs->vs_xfer_type));
   1622 		return EINVAL;
   1623 	}
   1624 }
   1625 
   1626 static int
   1627 uvideo_stream_stop_xfer(struct uvideo_stream *vs)
   1628 {
   1629 	struct uvideo_bulk_xfer *bx;
   1630 	struct uvideo_isoc_xfer *ix;
   1631 	usbd_status err;
   1632 	int i;
   1633 
   1634 	switch (vs->vs_xfer_type) {
   1635 	case UE_BULK:
   1636 		bx = &vs->vs_xfer.bulk;
   1637 
   1638 		DPRINTF(("uvideo_stream_stop_xfer: UE_BULK: "
   1639 			 "waiting for thread to complete\n"));
   1640 		mutex_enter(&bx->bx_lock);
   1641 		if (bx->bx_running == true) {
   1642 			bx->bx_running = false;
   1643 			cv_wait_sig(&bx->bx_cv, &bx->bx_lock);
   1644 		}
   1645 		mutex_exit(&bx->bx_lock);
   1646 
   1647 		DPRINTF(("uvideo_stream_stop_xfer: UE_BULK: cleaning up\n"));
   1648 
   1649 		if (bx->bx_pipe) {
   1650 			usbd_abort_pipe(bx->bx_pipe);
   1651 			usbd_close_pipe(bx->bx_pipe);
   1652 			bx->bx_pipe = NULL;
   1653 		}
   1654 
   1655 		if (bx->bx_xfer) {
   1656 			usbd_free_xfer(bx->bx_xfer);
   1657 			bx->bx_xfer = NULL;
   1658 		}
   1659 
   1660 		DPRINTF(("uvideo_stream_stop_xfer: UE_BULK: done\n"));
   1661 
   1662 		return 0;
   1663 	case UE_ISOCHRONOUS:
   1664 		ix = &vs->vs_xfer.isoc;
   1665 		if (ix->ix_pipe != NULL) {
   1666 			usbd_abort_pipe(ix->ix_pipe);
   1667 			usbd_close_pipe(ix->ix_pipe);
   1668 			ix->ix_pipe = NULL;
   1669 		}
   1670 
   1671 		for (i = 0; i < UVIDEO_NXFERS; i++) {
   1672 			struct uvideo_isoc *isoc = &ix->ix_i[i];
   1673 			if (isoc->i_xfer != NULL) {
   1674 				usbd_free_buffer(isoc->i_xfer);
   1675 				usbd_free_xfer(isoc->i_xfer);
   1676 				isoc->i_xfer = NULL;
   1677 			}
   1678 
   1679 			if (isoc->i_frlengths != NULL) {
   1680 				kmem_free(isoc->i_frlengths,
   1681 				  sizeof(isoc->i_frlengths[0]) *
   1682 				  ix->ix_nframes);
   1683 				isoc->i_frlengths = NULL;
   1684 			}
   1685 		}
   1686 
   1687 		/* Give it some time to settle */
   1688 		usbd_delay_ms(vs->vs_parent->sc_udev, 1000);
   1689 
   1690 		/* Set to zero bandwidth alternate interface zero */
   1691 		err = usbd_set_interface(vs->vs_iface, 0);
   1692 		if (err != USBD_NORMAL_COMPLETION) {
   1693 			DPRINTF(("uvideo_stream_stop_transfer: "
   1694 				 "error setting zero bandwidth interface: "
   1695 				 "%s (%d)\n",
   1696 				 usbd_errstr(err), err));
   1697 			return EIO;
   1698 		}
   1699 
   1700 		return 0;
   1701 	default:
   1702 		/* should never get here */
   1703 		DPRINTF(("uvideo_stream_stop_xfer: unknown xfer type 0x%x\n",
   1704 			 vs->vs_xfer_type));
   1705 		return EINVAL;
   1706 	}
   1707 }
   1708 
   1709 static usbd_status
   1710 uvideo_stream_recv_isoc_start(struct uvideo_stream *vs)
   1711 {
   1712 	int i;
   1713 
   1714 	for (i = 0; i < UVIDEO_NXFERS; i++)
   1715 		uvideo_stream_recv_isoc_start1(&vs->vs_xfer.isoc.ix_i[i]);
   1716 
   1717 	return USBD_NORMAL_COMPLETION;
   1718 }
   1719 
   1720 /* Initiate a usb transfer. */
   1721 static usbd_status
   1722 uvideo_stream_recv_isoc_start1(struct uvideo_isoc *isoc)
   1723 {
   1724 	struct uvideo_isoc_xfer *ix;
   1725 	usbd_status err;
   1726 	int i;
   1727 
   1728 	ix = isoc->i_ix;
   1729 
   1730 	for (i = 0; i < ix->ix_nframes; ++i)
   1731 		isoc->i_frlengths[i] = ix->ix_uframe_len;
   1732 
   1733 	usbd_setup_isoc_xfer(isoc->i_xfer,
   1734 			     ix->ix_pipe,
   1735 			     isoc,
   1736 			     isoc->i_frlengths,
   1737 			     ix->ix_nframes,
   1738 			     USBD_NO_COPY | USBD_SHORT_XFER_OK,
   1739 			     uvideo_stream_recv_isoc_complete);
   1740 
   1741 	err = usbd_transfer(isoc->i_xfer);
   1742 	if (err != USBD_IN_PROGRESS) {
   1743 		DPRINTF(("uvideo_stream_recv_start: "
   1744 			 "usbd_transfer status=%s (%d)\n",
   1745 			 usbd_errstr(err), err));
   1746 	}
   1747 	return err;
   1748 }
   1749 
   1750 static usbd_status
   1751 uvideo_stream_recv_process(struct uvideo_stream *vs, uint8_t *buf, uint32_t len)
   1752 {
   1753 	uvideo_payload_header_t *hdr;
   1754 	struct video_payload payload;
   1755 
   1756 	if (len < sizeof(uvideo_payload_header_t)) {
   1757 		DPRINTF(("uvideo_stream_recv_process: len %d < payload hdr\n",
   1758 			 len));
   1759 		return USBD_SHORT_XFER;
   1760 	}
   1761 
   1762 	hdr = (uvideo_payload_header_t *)buf;
   1763 
   1764 	if (hdr->bHeaderLength > UVIDEO_PAYLOAD_HEADER_SIZE ||
   1765 	    hdr->bHeaderLength < sizeof(uvideo_payload_header_t))
   1766 		return USBD_INVAL;
   1767 	if (hdr->bHeaderLength == len && !(hdr->bmHeaderInfo & UV_END_OF_FRAME))
   1768 		return USBD_INVAL;
   1769 	if (hdr->bmHeaderInfo & UV_ERROR)
   1770 		return USBD_IOERROR;
   1771 
   1772 	payload.data = buf + hdr->bHeaderLength;
   1773 	payload.size = len - hdr->bHeaderLength;
   1774 	payload.frameno = hdr->bmHeaderInfo & UV_FRAME_ID;
   1775 	payload.end_of_frame = hdr->bmHeaderInfo & UV_END_OF_FRAME;
   1776 
   1777 	video_submit_payload(vs->vs_parent->sc_videodev, &payload);
   1778 
   1779 	return USBD_NORMAL_COMPLETION;
   1780 }
   1781 
   1782 /* Callback on completion of usb isoc transfer */
   1783 static void
   1784 uvideo_stream_recv_isoc_complete(usbd_xfer_handle xfer,
   1785 				 usbd_private_handle priv,
   1786 				 usbd_status status)
   1787 {
   1788 	struct uvideo_stream *vs;
   1789 	struct uvideo_isoc_xfer *ix;
   1790 	struct uvideo_isoc *isoc;
   1791 	int i;
   1792 	uint32_t count;
   1793 	const uvideo_payload_header_t *hdr;
   1794 	uint8_t *buf;
   1795 
   1796 	isoc = priv;
   1797 	vs = isoc->i_vs;
   1798 	ix = isoc->i_ix;
   1799 
   1800 	if (status != USBD_NORMAL_COMPLETION) {
   1801 		DPRINTF(("uvideo_stream_recv_isoc_complete: status=%s (%d)\n",
   1802 			usbd_errstr(status), status));
   1803 
   1804 		if (status == USBD_STALLED)
   1805 			usbd_clear_endpoint_stall_async(ix->ix_pipe);
   1806 		else
   1807 			return;
   1808 	} else {
   1809 		usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1810 
   1811 		if (count == 0) {
   1812 			/* DPRINTF(("uvideo: zero length transfer\n")); */
   1813 			goto next;
   1814 		}
   1815 
   1816 		hdr = (const uvideo_payload_header_t *)isoc->i_buf;
   1817 
   1818 		for (i = 0, buf = isoc->i_buf;
   1819 		     i < ix->ix_nframes;
   1820 		     ++i, buf += ix->ix_uframe_len)
   1821 		{
   1822 			status = uvideo_stream_recv_process(vs, buf,
   1823 			    isoc->i_frlengths[i]);
   1824 			if (status == USBD_IOERROR)
   1825 				break;
   1826 		}
   1827 	}
   1828 
   1829 next:
   1830 	memset(isoc->i_buf, 0x41, ix->ix_nframes * ix->ix_uframe_len);
   1831 	uvideo_stream_recv_isoc_start1(isoc);
   1832 }
   1833 
   1834 static void
   1835 uvideo_stream_recv_bulk_transfer(void *addr)
   1836 {
   1837 	struct uvideo_stream *vs = addr;
   1838 	struct uvideo_bulk_xfer *bx = &vs->vs_xfer.bulk;
   1839 	usbd_status err;
   1840 	uint32_t len;
   1841 
   1842 	DPRINTF(("uvideo_stream_recv_bulk_transfer: "
   1843 		 "vs %p sc %p bx %p buffer %p\n", vs, vs->vs_parent, bx,
   1844 		 bx->bx_buffer));
   1845 
   1846 	while (bx->bx_running) {
   1847 		len = bx->bx_buflen;
   1848 		err = usbd_bulk_transfer(bx->bx_xfer, bx->bx_pipe,
   1849 		    USBD_SHORT_XFER_OK | USBD_NO_COPY,
   1850 		    USBD_NO_TIMEOUT,
   1851 		    bx->bx_buffer, &len, "uvideorb");
   1852 
   1853 		if (err == USBD_NORMAL_COMPLETION) {
   1854 			uvideo_stream_recv_process(vs, bx->bx_buffer, len);
   1855 		} else {
   1856 			DPRINTF(("uvideo_stream_recv_bulk_transfer: %s\n",
   1857 				 usbd_errstr(err)));
   1858 		}
   1859 	}
   1860 
   1861 	DPRINTF(("uvideo_stream_recv_bulk_transfer: notify complete\n"));
   1862 
   1863 	mutex_enter(&bx->bx_lock);
   1864 	cv_broadcast(&bx->bx_cv);
   1865 	mutex_exit(&bx->bx_lock);
   1866 
   1867 	DPRINTF(("uvideo_stream_recv_bulk_transfer: return\n"));
   1868 
   1869 	kthread_exit(0);
   1870 }
   1871 
   1872 /*
   1873  * uvideo_open - probe and commit video format and start receiving
   1874  * video data
   1875  */
   1876 static int
   1877 uvideo_open(void *addr, int flags)
   1878 {
   1879 	struct uvideo_softc *sc;
   1880 	struct uvideo_stream *vs;
   1881 	struct video_format fmt;
   1882 
   1883 	sc = addr;
   1884 	vs = sc->sc_stream_in;
   1885 
   1886 	DPRINTF(("uvideo_open: sc=%p\n", sc));
   1887 	if (sc->sc_dying)
   1888 		return EIO;
   1889 
   1890 	/* XXX select default format */
   1891 	fmt = *vs->vs_default_format;
   1892 	return uvideo_set_format(addr, &fmt);
   1893 }
   1894 
   1895 
   1896 static void
   1897 uvideo_close(void *addr)
   1898 {
   1899 	struct uvideo_softc *sc;
   1900 
   1901 	sc = addr;
   1902 
   1903 	if (sc->sc_state != UVIDEO_STATE_CLOSED) {
   1904 		sc->sc_state = UVIDEO_STATE_CLOSED;
   1905 	}
   1906 }
   1907 
   1908 static const char *
   1909 uvideo_get_devname(void *addr)
   1910 {
   1911 	struct uvideo_softc *sc = addr;
   1912 	return sc->sc_devname;
   1913 }
   1914 
   1915 static int
   1916 uvideo_enum_format(void *addr, uint32_t index, struct video_format *format)
   1917 {
   1918 	struct uvideo_softc *sc = addr;
   1919 	struct uvideo_stream *vs = sc->sc_stream_in;
   1920 	struct uvideo_pixel_format *pixel_format;
   1921 	int off;
   1922 
   1923 	if (sc->sc_dying)
   1924 		return EIO;
   1925 
   1926 	off = 0;
   1927 	SIMPLEQ_FOREACH(pixel_format, &vs->vs_pixel_formats, entries) {
   1928 		if (off++ != index)
   1929 			continue;
   1930 		format->pixel_format = pixel_format->pixel_format;
   1931 		return 0;
   1932 	}
   1933 
   1934 	return EINVAL;
   1935 }
   1936 
   1937 /*
   1938  * uvideo_get_format
   1939  */
   1940 static int
   1941 uvideo_get_format(void *addr, struct video_format *format)
   1942 {
   1943 	struct uvideo_softc *sc = addr;
   1944 	struct uvideo_stream *vs = sc->sc_stream_in;
   1945 
   1946 	if (sc->sc_dying)
   1947 		return EIO;
   1948 
   1949 	*format = vs->vs_current_format;
   1950 
   1951 	return 0;
   1952 }
   1953 
   1954 /*
   1955  * uvideo_set_format - TODO: this is boken and does nothing
   1956  */
   1957 static int
   1958 uvideo_set_format(void *addr, struct video_format *format)
   1959 {
   1960 	struct uvideo_softc *sc;
   1961 	struct uvideo_stream *vs;
   1962 	struct uvideo_format *uvfmt;
   1963 	uvideo_probe_and_commit_data_t probe, maxprobe;
   1964 	uint8_t ifaceno;
   1965 	usbd_status err;
   1966 
   1967 	sc = addr;
   1968 
   1969 	DPRINTF(("uvideo_set_format: sc=%p\n", sc));
   1970 	if (sc->sc_dying)
   1971 		return EIO;
   1972 
   1973 	vs = sc->sc_stream_in;
   1974 	ifaceno = vs->vs_ifaceno;
   1975 
   1976 	uvfmt =	uvideo_stream_guess_format(vs, format->pixel_format,
   1977 					   format->width, format->height);
   1978 	if (uvfmt == NULL) {
   1979 		DPRINTF(("uvideo: uvideo_stream_guess_format couldn't find "
   1980 			 "%dx%d format %d\n", format->width, format->height,
   1981 			 format->pixel_format));
   1982 		return EINVAL;
   1983 	}
   1984 
   1985 	uvideo_init_probe_data(&probe);
   1986 	probe.bFormatIndex = UVIDEO_FORMAT_GET_FORMAT_INDEX(uvfmt);
   1987 	probe.bFrameIndex = UVIDEO_FORMAT_GET_FRAME_INDEX(uvfmt);
   1988 	USETDW(probe.dwFrameInterval, vs->vs_frame_interval);	/* XXX */
   1989 
   1990 	maxprobe = probe;
   1991 	err = uvideo_stream_probe(vs, UR_GET_MAX, &maxprobe);
   1992 	if (err) {
   1993 		DPRINTF(("uvideo: error probe/GET_MAX: %s (%d)\n",
   1994 			 usbd_errstr(err), err));
   1995 	} else {
   1996 		USETW(probe.wCompQuality, UGETW(maxprobe.wCompQuality));
   1997 	}
   1998 
   1999 	err = uvideo_stream_probe(vs, UR_SET_CUR, &probe);
   2000 	if (err) {
   2001 		DPRINTF(("uvideo: error commit/SET_CUR: %s (%d)\n",
   2002 			 usbd_errstr(err), err));
   2003 		return EIO;
   2004 	}
   2005 
   2006 	uvideo_init_probe_data(&probe);
   2007 	err = uvideo_stream_probe(vs, UR_GET_CUR, &probe);
   2008 	if (err) {
   2009 		DPRINTF(("uvideo: error commit/SET_CUR: %s (%d)\n",
   2010 			 usbd_errstr(err), err));
   2011 		return EIO;
   2012 	}
   2013 
   2014 	if (probe.bFormatIndex != UVIDEO_FORMAT_GET_FORMAT_INDEX(uvfmt)) {
   2015 		DPRINTF(("uvideo: probe/GET_CUR returned format index %d "
   2016 			 "(expected %d)\n", probe.bFormatIndex,
   2017 			 UVIDEO_FORMAT_GET_FORMAT_INDEX(uvfmt)));
   2018 		probe.bFormatIndex = UVIDEO_FORMAT_GET_FORMAT_INDEX(uvfmt);
   2019 	}
   2020 	if (probe.bFrameIndex != UVIDEO_FORMAT_GET_FRAME_INDEX(uvfmt)) {
   2021 		DPRINTF(("uvideo: probe/GET_CUR returned frame index %d "
   2022 			 "(expected %d)\n", probe.bFrameIndex,
   2023 			 UVIDEO_FORMAT_GET_FRAME_INDEX(uvfmt)));
   2024 		probe.bFrameIndex = UVIDEO_FORMAT_GET_FRAME_INDEX(uvfmt);
   2025 	}
   2026 	USETDW(probe.dwFrameInterval, vs->vs_frame_interval);	/* XXX */
   2027 
   2028 	/* commit/SET_CUR. Fourth step is to set the alternate
   2029 	 * interface.  Currently the fourth step is in
   2030 	 * uvideo_start_transfer.  Maybe move it here? */
   2031 	err = uvideo_stream_commit(vs, UR_SET_CUR, &probe);
   2032 	if (err) {
   2033 		DPRINTF(("uvideo: error commit/SET_CUR: %s (%d)\n",
   2034 			 usbd_errstr(err), err));
   2035 		return EIO;
   2036 	}
   2037 
   2038 	DPRINTFN(15, ("uvideo_set_format: committing to format: "
   2039 		      "bmHint=0x%04x bFormatIndex=%d bFrameIndex=%d "
   2040 		      "dwFrameInterval=%u wKeyFrameRate=%d wPFrameRate=%d "
   2041 		      "wCompQuality=%d wCompWindowSize=%d wDelay=%d "
   2042 		      "dwMaxVideoFrameSize=%u dwMaxPayloadTransferSize=%u",
   2043 		      UGETW(probe.bmHint),
   2044 		      probe.bFormatIndex,
   2045 		      probe.bFrameIndex,
   2046 		      UGETDW(probe.dwFrameInterval),
   2047 		      UGETW(probe.wKeyFrameRate),
   2048 		      UGETW(probe.wPFrameRate),
   2049 		      UGETW(probe.wCompQuality),
   2050 		      UGETW(probe.wCompWindowSize),
   2051 		      UGETW(probe.wDelay),
   2052 		      UGETDW(probe.dwMaxVideoFrameSize),
   2053 		      UGETDW(probe.dwMaxPayloadTransferSize)));
   2054 	if (vs->vs_probelen == 34) {
   2055 		DPRINTFN(15, (" dwClockFrequency=%u bmFramingInfo=0x%02x "
   2056 			      "bPreferedVersion=%d bMinVersion=%d "
   2057 			      "bMaxVersion=%d",
   2058 			      UGETDW(probe.dwClockFrequency),
   2059 			      probe.bmFramingInfo,
   2060 			      probe.bPreferedVersion,
   2061 			      probe.bMinVersion,
   2062 			      probe.bMaxVersion));
   2063 	}
   2064 	DPRINTFN(15, ("\n"));
   2065 
   2066 	vs->vs_frame_interval = UGETDW(probe.dwFrameInterval);
   2067 	vs->vs_max_payload_size = UGETDW(probe.dwMaxPayloadTransferSize);
   2068 
   2069 	*format = uvfmt->format;
   2070 	vs->vs_current_format = *format;
   2071 	DPRINTF(("uvideo_set_format: pixeltype is %d\n", format->pixel_format));
   2072 
   2073 	return 0;
   2074 }
   2075 
   2076 static int
   2077 uvideo_try_format(void *addr, struct video_format *format)
   2078 {
   2079 	struct uvideo_softc *sc = addr;
   2080 	struct uvideo_stream *vs = sc->sc_stream_in;
   2081 	struct uvideo_format *uvfmt;
   2082 
   2083 	uvfmt =	uvideo_stream_guess_format(vs, format->pixel_format,
   2084 					   format->width, format->height);
   2085 	if (uvfmt == NULL)
   2086 		return EINVAL;
   2087 
   2088 	*format = uvfmt->format;
   2089 	return 0;
   2090 }
   2091 
   2092 static int
   2093 uvideo_start_transfer(void *addr)
   2094 {
   2095 	struct uvideo_softc *sc = addr;
   2096 	struct uvideo_stream *vs;
   2097 	int s, err;
   2098 
   2099 	/* FIXME: this functions should be stream specific */
   2100 	vs = SLIST_FIRST(&sc->sc_stream_list);
   2101 	s = splusb();
   2102 	err = uvideo_stream_start_xfer(vs);
   2103 	splx(s);
   2104 
   2105 	return err;
   2106 }
   2107 
   2108 static int
   2109 uvideo_stop_transfer(void *addr)
   2110 {
   2111 	struct uvideo_softc *sc;
   2112 	int err, s;
   2113 
   2114 	sc = addr;
   2115 
   2116 	s = splusb();
   2117 	err = uvideo_stream_stop_xfer(sc->sc_stream_in);
   2118 	splx(s);
   2119 
   2120 	return err;
   2121 }
   2122 
   2123 
   2124 static int
   2125 uvideo_get_control_group(void *addr, struct video_control_group *group)
   2126 {
   2127 	struct uvideo_softc *sc;
   2128 	usb_device_request_t req;
   2129 	usbd_status err;
   2130 	uint8_t control_id, ent_id, data[16];
   2131 	uint16_t len;
   2132 	int s;
   2133 
   2134 	sc = addr;
   2135 
   2136 	/* request setup */
   2137 	switch (group->group_id) {
   2138 	case VIDEO_CONTROL_PANTILT_RELATIVE:
   2139 		if (group->length != 4)
   2140 			return EINVAL;
   2141 
   2142 		return EINVAL;
   2143 	case VIDEO_CONTROL_SHARPNESS:
   2144 		if (group->length != 1)
   2145 			return EINVAL;
   2146 
   2147 		control_id = UVIDEO_PU_SHARPNESS_CONTROL;
   2148 		ent_id = 2; /* TODO: hardcoded logitech processing unit */
   2149 		len = 2;
   2150 		break;
   2151 	default:
   2152 		return EINVAL;
   2153 	}
   2154 
   2155 	/* do request */
   2156 	req.bmRequestType = UVIDEO_REQUEST_TYPE_INTERFACE |
   2157 	    UVIDEO_REQUEST_TYPE_CLASS_SPECIFIC |
   2158 	    UVIDEO_REQUEST_TYPE_GET;
   2159 	req.bRequest = UR_GET_CUR;
   2160 	USETW(req.wValue, control_id << 8);
   2161 	USETW(req.wIndex, (ent_id << 8) | sc->sc_ifaceno);
   2162 	USETW(req.wLength, len);
   2163 
   2164 	s = splusb();
   2165 	err = usbd_do_request(sc->sc_udev, &req, data);
   2166 	splx(s);
   2167 	if (err != USBD_NORMAL_COMPLETION) {
   2168 		DPRINTF(("uvideo_set_control: error %s (%d)\n",
   2169 			 usbd_errstr(err), err));
   2170 		return EIO;	/* TODO: more detail here? */
   2171 	}
   2172 
   2173 	/* extract request data */
   2174 	switch (group->group_id) {
   2175 	case VIDEO_CONTROL_SHARPNESS:
   2176 		group->control[0].value = UGETW(data);
   2177 		break;
   2178 	default:
   2179 		return EINVAL;
   2180 	}
   2181 
   2182 	return 0;
   2183 }
   2184 
   2185 
   2186 static int
   2187 uvideo_set_control_group(void *addr, const struct video_control_group *group)
   2188 {
   2189 	struct uvideo_softc *sc;
   2190 	usb_device_request_t req;
   2191 	usbd_status err;
   2192 	uint8_t control_id, ent_id, data[16]; /* long enough for all controls */
   2193 	uint16_t len;
   2194 	int s;
   2195 
   2196 	sc = addr;
   2197 
   2198 	switch (group->group_id) {
   2199 	case VIDEO_CONTROL_PANTILT_RELATIVE:
   2200 		if (group->length != 4)
   2201 			return EINVAL;
   2202 
   2203 		if (group->control[0].value != 0 ||
   2204 		    group->control[0].value != 1 ||
   2205 		    group->control[0].value != 0xff)
   2206 			return ERANGE;
   2207 
   2208 		if (group->control[2].value != 0 ||
   2209 		    group->control[2].value != 1 ||
   2210 		    group->control[2].value != 0xff)
   2211 			return ERANGE;
   2212 
   2213 		control_id = UVIDEO_CT_PANTILT_RELATIVE_CONTROL;
   2214 		ent_id = 1;	/* TODO: hardcoded logitech camera terminal  */
   2215 		len = 4;
   2216 		data[0] = group->control[0].value;
   2217 		data[1] = group->control[1].value;
   2218 		data[2] = group->control[2].value;
   2219 		data[3] = group->control[3].value;
   2220 		break;
   2221 	case VIDEO_CONTROL_BRIGHTNESS:
   2222 		if (group->length != 1)
   2223 			return EINVAL;
   2224 		control_id = UVIDEO_PU_BRIGHTNESS_CONTROL;
   2225 		ent_id = 2;
   2226 		len = 2;
   2227 		USETW(data, group->control[0].value);
   2228 		break;
   2229 	case VIDEO_CONTROL_GAIN:
   2230 		if (group->length != 1)
   2231 			return EINVAL;
   2232 		control_id = UVIDEO_PU_GAIN_CONTROL;
   2233 		ent_id = 2;
   2234 		len = 2;
   2235 		USETW(data, group->control[0].value);
   2236 		break;
   2237 	case VIDEO_CONTROL_SHARPNESS:
   2238 		if (group->length != 1)
   2239 			return EINVAL;
   2240 		control_id = UVIDEO_PU_SHARPNESS_CONTROL;
   2241 		ent_id = 2; /* TODO: hardcoded logitech processing unit */
   2242 		len = 2;
   2243 		USETW(data, group->control[0].value);
   2244 		break;
   2245 	default:
   2246 		return EINVAL;
   2247 	}
   2248 
   2249 	req.bmRequestType = UVIDEO_REQUEST_TYPE_INTERFACE |
   2250 	    UVIDEO_REQUEST_TYPE_CLASS_SPECIFIC |
   2251 	    UVIDEO_REQUEST_TYPE_SET;
   2252 	req.bRequest = UR_SET_CUR;
   2253 	USETW(req.wValue, control_id << 8);
   2254 	USETW(req.wIndex, (ent_id << 8) | sc->sc_ifaceno);
   2255 	USETW(req.wLength, len);
   2256 
   2257 	s = splusb();
   2258 	err = usbd_do_request(sc->sc_udev, &req, data);
   2259 	splx(s);
   2260 	if (err != USBD_NORMAL_COMPLETION) {
   2261 		DPRINTF(("uvideo_set_control: error %s (%d)\n",
   2262 			 usbd_errstr(err), err));
   2263 		return EIO;	/* TODO: more detail here? */
   2264 	}
   2265 
   2266 	return 0;
   2267 }
   2268 
   2269 static usbd_status
   2270 uvideo_stream_probe_and_commit(struct uvideo_stream *vs,
   2271 			       uint8_t action, uint8_t control,
   2272 			       void *data)
   2273 {
   2274 	usb_device_request_t req;
   2275 
   2276 	switch (action) {
   2277 	case UR_SET_CUR:
   2278 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   2279 		USETW(req.wLength, vs->vs_probelen);
   2280 		break;
   2281 	case UR_GET_CUR:
   2282 	case UR_GET_MIN:
   2283 	case UR_GET_MAX:
   2284 	case UR_GET_DEF:
   2285 		req.bmRequestType = UT_READ_CLASS_INTERFACE;
   2286 		USETW(req.wLength, vs->vs_probelen);
   2287 		break;
   2288 	case UR_GET_INFO:
   2289 		req.bmRequestType = UT_READ_CLASS_INTERFACE;
   2290 		USETW(req.wLength, sizeof(uByte));
   2291 		break;
   2292 	case UR_GET_LEN:
   2293 		req.bmRequestType = UT_READ_CLASS_INTERFACE;
   2294 		USETW(req.wLength, sizeof(uWord)); /* is this right? */
   2295 		break;
   2296 	default:
   2297 		DPRINTF(("uvideo_probe_and_commit: "
   2298 			 "unknown request action %d\n", action));
   2299 		return USBD_NOT_STARTED;
   2300 	}
   2301 
   2302 	req.bRequest = action;
   2303 	USETW2(req.wValue, control, 0);
   2304 	USETW2(req.wIndex, 0, vs->vs_ifaceno);
   2305 
   2306 	return (usbd_do_request_flags(vs->vs_parent->sc_udev, &req, data,
   2307 				      0, 0,
   2308 				      USBD_DEFAULT_TIMEOUT));
   2309 }
   2310 
   2311 static void
   2312 uvideo_init_probe_data(uvideo_probe_and_commit_data_t *probe)
   2313 {
   2314 	/* all zeroes tells camera to choose what it wants */
   2315 	memset(probe, 0, sizeof(*probe));
   2316 }
   2317 
   2318 
   2319 #ifdef _MODULE
   2320 
   2321 MODULE(MODULE_CLASS_DRIVER, uvideo, NULL);
   2322 static const struct cfiattrdata videobuscf_iattrdata = {
   2323         "videobus", 0, {
   2324 		{ NULL, NULL, 0 },
   2325 	}
   2326 };
   2327 static const struct cfiattrdata * const uvideo_attrs[] = {
   2328 	&videobuscf_iattrdata, NULL
   2329 };
   2330 CFDRIVER_DECL(uvideo, DV_DULL, uvideo_attrs);
   2331 extern struct cfattach uvideo_ca;
   2332 extern struct cfattach uvideo_ca;
   2333 static int uvideoloc[6] = { -1, -1, -1, -1, -1, -1 };
   2334 static struct cfparent uhubparent = {
   2335         "usbifif", NULL, DVUNIT_ANY
   2336 };
   2337 static struct cfdata uvideo_cfdata[] = {
   2338 	{
   2339 		.cf_name = "uvideo",
   2340 		.cf_atname = "uvideo",
   2341 		.cf_unit = 0,
   2342 		.cf_fstate = FSTATE_STAR,
   2343 		.cf_loc = uvideoloc,
   2344 		.cf_flags = 0,
   2345 		.cf_pspec = &uhubparent,
   2346 	},
   2347 	{ NULL }
   2348 };
   2349 
   2350 static int
   2351 uvideo_modcmd(modcmd_t cmd, void *arg)
   2352 {
   2353 	int err;
   2354 
   2355 
   2356 	switch (cmd) {
   2357 	case MODULE_CMD_INIT:
   2358 		DPRINTF(("uvideo: attempting to load\n"));
   2359 
   2360 		err = config_cfdriver_attach(&uvideo_cd);
   2361 		if (err)
   2362 			return err;
   2363 		err = config_cfattach_attach("uvideo", &uvideo_ca);
   2364 		if (err) {
   2365 			config_cfdriver_detach(&uvideo_cd);
   2366 			return err;
   2367 		}
   2368 		err = config_cfdata_attach(uvideo_cfdata, 1);
   2369 		if (err) {
   2370 			config_cfattach_detach("uvideo", &uvideo_ca);
   2371 			config_cfdriver_detach(&uvideo_cd);
   2372 			return err;
   2373 		}
   2374 		DPRINTF(("uvideo: loaded module\n"));
   2375 		return 0;
   2376 	case MODULE_CMD_FINI:
   2377 		DPRINTF(("uvideo: attempting to unload module\n"));
   2378 		err = config_cfdata_detach(uvideo_cfdata);
   2379 		if (err)
   2380 			return err;
   2381 		config_cfattach_detach("uvideo", &uvideo_ca);
   2382 		config_cfdriver_detach(&uvideo_cd);
   2383 		DPRINTF(("uvideo: module unload\n"));
   2384 		return 0;
   2385 	default:
   2386 		return ENOTTY;
   2387 	}
   2388 }
   2389 
   2390 #endif	/* _MODULE */
   2391 
   2392 
   2393 #ifdef UVIDEO_DEBUG
   2394 /* Some functions to print out descriptors.  Mostly useless other than
   2395  * debugging/exploration purposes. */
   2396 
   2397 
   2398 static void
   2399 print_bitmap(const uByte *start, uByte nbytes)
   2400 {
   2401 	int byte, bit;
   2402 
   2403 	/* most significant first */
   2404 	for (byte = nbytes-1; byte >= 0; --byte) {
   2405 		if (byte < nbytes-1) printf("-");
   2406 		for (bit = 7; bit >= 0; --bit)
   2407 			printf("%01d", (start[byte] >> bit) &1);
   2408 	}
   2409 }
   2410 
   2411 static void
   2412 print_descriptor(const usb_descriptor_t *desc)
   2413 {
   2414 	static int current_class = -1;
   2415 	static int current_subclass = -1;
   2416 
   2417 	if (desc->bDescriptorType == UDESC_INTERFACE) {
   2418 		const usb_interface_descriptor_t *id;
   2419 		id = (const usb_interface_descriptor_t *)desc;
   2420 		current_class = id->bInterfaceClass;
   2421 		current_subclass = id->bInterfaceSubClass;
   2422 		print_interface_descriptor(id);
   2423 		printf("\n");
   2424 		return;
   2425 	}
   2426 
   2427 	printf("  ");		/* indent */
   2428 
   2429 	if (current_class == UICLASS_VIDEO) {
   2430 		switch (current_subclass) {
   2431 		case UISUBCLASS_VIDEOCONTROL:
   2432 			print_vc_descriptor(desc);
   2433 			break;
   2434 		case UISUBCLASS_VIDEOSTREAMING:
   2435 			print_vs_descriptor(desc);
   2436 			break;
   2437 		case UISUBCLASS_VIDEOCOLLECTION:
   2438 			printf("uvc collection: len=%d type=0x%02x",
   2439 			    desc->bLength, desc->bDescriptorType);
   2440 			break;
   2441 		}
   2442 	} else {
   2443 		printf("non uvc descriptor len=%d type=0x%02x",
   2444 		    desc->bLength, desc->bDescriptorType);
   2445 	}
   2446 
   2447 	printf("\n");
   2448 }
   2449 
   2450 static void
   2451 print_vc_descriptor(const usb_descriptor_t *desc)
   2452 {
   2453 	const uvideo_descriptor_t *vcdesc;
   2454 
   2455 	printf("VC ");
   2456 
   2457 	switch (desc->bDescriptorType) {
   2458 	case UDESC_ENDPOINT:
   2459 		print_endpoint_descriptor(
   2460 			(const usb_endpoint_descriptor_t *)desc);
   2461 		break;
   2462 	case UDESC_CS_INTERFACE:
   2463 		vcdesc = (const uvideo_descriptor_t *)desc;
   2464 		switch (vcdesc->bDescriptorSubtype) {
   2465 		case UDESC_VC_HEADER:
   2466 			print_vc_header_descriptor(
   2467 			  (const uvideo_vc_header_descriptor_t *)
   2468 				vcdesc);
   2469 			break;
   2470 		case UDESC_INPUT_TERMINAL:
   2471 			switch (UGETW(
   2472 			   ((const uvideo_input_terminal_descriptor_t *)
   2473 				    vcdesc)->wTerminalType)) {
   2474 			case UVIDEO_ITT_CAMERA:
   2475 				print_camera_terminal_descriptor(
   2476 			  (const uvideo_camera_terminal_descriptor_t *)vcdesc);
   2477 				break;
   2478 			default:
   2479 				print_input_terminal_descriptor(
   2480 			  (const uvideo_input_terminal_descriptor_t *)vcdesc);
   2481 				break;
   2482 			}
   2483 			break;
   2484 		case UDESC_OUTPUT_TERMINAL:
   2485 			print_output_terminal_descriptor(
   2486 				(const uvideo_output_terminal_descriptor_t *)
   2487 				vcdesc);
   2488 			break;
   2489 		case UDESC_SELECTOR_UNIT:
   2490 			print_selector_unit_descriptor(
   2491 				(const uvideo_selector_unit_descriptor_t *)
   2492 				vcdesc);
   2493 			break;
   2494 		case UDESC_PROCESSING_UNIT:
   2495 			print_processing_unit_descriptor(
   2496 				(const uvideo_processing_unit_descriptor_t *)
   2497 				vcdesc);
   2498 			break;
   2499 		case UDESC_EXTENSION_UNIT:
   2500 			print_extension_unit_descriptor(
   2501 				(const uvideo_extension_unit_descriptor_t *)
   2502 				vcdesc);
   2503 			break;
   2504 		default:
   2505 			printf("class specific interface "
   2506 			    "len=%d type=0x%02x subtype=0x%02x",
   2507 			    vcdesc->bLength,
   2508 			    vcdesc->bDescriptorType,
   2509 			    vcdesc->bDescriptorSubtype);
   2510 			break;
   2511 		}
   2512 		break;
   2513 	case UDESC_CS_ENDPOINT:
   2514 		vcdesc = (const uvideo_descriptor_t *)desc;
   2515 		switch (vcdesc->bDescriptorSubtype) {
   2516 		case UDESC_VC_INTERRUPT_ENDPOINT:
   2517 			print_interrupt_endpoint_descriptor(
   2518 			    (const uvideo_vc_interrupt_endpoint_descriptor_t *)
   2519 				vcdesc);
   2520 			break;
   2521 		default:
   2522 			printf("class specific endpoint "
   2523 			    "len=%d type=0x%02x subtype=0x%02x",
   2524 			    vcdesc->bLength,
   2525 			    vcdesc->bDescriptorType,
   2526 			    vcdesc->bDescriptorSubtype);
   2527 			break;
   2528 		}
   2529 		break;
   2530 	default:
   2531 		printf("unknown: len=%d type=0x%02x",
   2532 		    desc->bLength, desc->bDescriptorType);
   2533 		break;
   2534 	}
   2535 }
   2536 
   2537 static void
   2538 print_vs_descriptor(const usb_descriptor_t *desc)
   2539 {
   2540 	const uvideo_descriptor_t * vsdesc;
   2541 	printf("VS ");
   2542 
   2543 	switch (desc->bDescriptorType) {
   2544 	case UDESC_ENDPOINT:
   2545 		print_endpoint_descriptor(
   2546 			(const usb_endpoint_descriptor_t *)desc);
   2547 		break;
   2548 	case UDESC_CS_INTERFACE:
   2549 		vsdesc = (const uvideo_descriptor_t *)desc;
   2550 		switch (vsdesc->bDescriptorSubtype) {
   2551 		case UDESC_VS_INPUT_HEADER:
   2552 			print_vs_input_header_descriptor(
   2553 			 (const uvideo_vs_input_header_descriptor_t *)
   2554 				vsdesc);
   2555 			break;
   2556 		case UDESC_VS_OUTPUT_HEADER:
   2557 			print_vs_output_header_descriptor(
   2558 			(const uvideo_vs_output_header_descriptor_t *)
   2559 				vsdesc);
   2560 			break;
   2561 		case UDESC_VS_FORMAT_UNCOMPRESSED:
   2562 			print_vs_format_uncompressed_descriptor(
   2563 			   (const uvideo_vs_format_uncompressed_descriptor_t *)
   2564 				vsdesc);
   2565 			break;
   2566 		case UDESC_VS_FRAME_UNCOMPRESSED:
   2567 			print_vs_frame_uncompressed_descriptor(
   2568 			    (const uvideo_vs_frame_uncompressed_descriptor_t *)
   2569 				vsdesc);
   2570 			break;
   2571 		case UDESC_VS_FORMAT_MJPEG:
   2572 			print_vs_format_mjpeg_descriptor(
   2573 				(const uvideo_vs_format_mjpeg_descriptor_t *)
   2574 				vsdesc);
   2575 			break;
   2576 		case UDESC_VS_FRAME_MJPEG:
   2577 			print_vs_frame_mjpeg_descriptor(
   2578 				(const uvideo_vs_frame_mjpeg_descriptor_t *)
   2579 				vsdesc);
   2580 			break;
   2581 		case UDESC_VS_FORMAT_DV:
   2582 			print_vs_format_dv_descriptor(
   2583 				(const uvideo_vs_format_dv_descriptor_t *)
   2584 				vsdesc);
   2585 			break;
   2586 		default:
   2587 			printf("unknown cs interface: len=%d type=0x%02x "
   2588 			    "subtype=0x%02x",
   2589 			    vsdesc->bLength, vsdesc->bDescriptorType,
   2590 			    vsdesc->bDescriptorSubtype);
   2591 		}
   2592 		break;
   2593 	default:
   2594 		printf("unknown: len=%d type=0x%02x",
   2595 		    desc->bLength, desc->bDescriptorType);
   2596 		break;
   2597 	}
   2598 }
   2599 
   2600 static void
   2601 print_interface_descriptor(const usb_interface_descriptor_t *id)
   2602 {
   2603 	printf("Interface: Len=%d Type=0x%02x "
   2604 	    "bInterfaceNumber=0x%02x "
   2605 	    "bAlternateSetting=0x%02x bNumEndpoints=0x%02x "
   2606 	    "bInterfaceClass=0x%02x bInterfaceSubClass=0x%02x "
   2607 	    "bInterfaceProtocol=0x%02x iInterface=0x%02x",
   2608 	    id->bLength,
   2609 	    id->bDescriptorType,
   2610 	    id->bInterfaceNumber,
   2611 	    id->bAlternateSetting,
   2612 	    id->bNumEndpoints,
   2613 	    id->bInterfaceClass,
   2614 	    id->bInterfaceSubClass,
   2615 	    id->bInterfaceProtocol,
   2616 	    id->iInterface);
   2617 }
   2618 
   2619 static void
   2620 print_endpoint_descriptor(const usb_endpoint_descriptor_t *desc)
   2621 {
   2622 	printf("Endpoint: Len=%d Type=0x%02x "
   2623 	    "bEndpointAddress=0x%02x ",
   2624 	    desc->bLength,
   2625 	    desc->bDescriptorType,
   2626 	    desc->bEndpointAddress);
   2627 	printf("bmAttributes=");
   2628 	print_bitmap(&desc->bmAttributes, 1);
   2629 	printf(" wMaxPacketSize=%d bInterval=%d",
   2630 	    UGETW(desc->wMaxPacketSize),
   2631 	    desc->bInterval);
   2632 }
   2633 
   2634 static void
   2635 print_vc_header_descriptor(
   2636 	const uvideo_vc_header_descriptor_t *desc)
   2637 {
   2638 	printf("Interface Header: "
   2639 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2640 	    "bcdUVC=%d wTotalLength=%d "
   2641 	    "dwClockFrequency=%u bInCollection=%d",
   2642 	    desc->bLength,
   2643 	    desc->bDescriptorType,
   2644 	    desc->bDescriptorSubtype,
   2645 	    UGETW(desc->bcdUVC),
   2646 	    UGETW(desc->wTotalLength),
   2647 	    UGETDW(desc->dwClockFrequency),
   2648 	    desc->bInCollection);
   2649 }
   2650 
   2651 static void
   2652 print_input_terminal_descriptor(
   2653 	const uvideo_input_terminal_descriptor_t *desc)
   2654 {
   2655 	printf("Input Terminal: "
   2656 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2657 	    "bTerminalID=%d wTerminalType=%x bAssocTerminal=%d "
   2658 	    "iTerminal=%d",
   2659 	    desc->bLength,
   2660 	    desc->bDescriptorType,
   2661 	    desc->bDescriptorSubtype,
   2662 	    desc->bTerminalID,
   2663 	    UGETW(desc->wTerminalType),
   2664 	    desc->bAssocTerminal,
   2665 	    desc->iTerminal);
   2666 }
   2667 
   2668 static void
   2669 print_output_terminal_descriptor(
   2670 	const uvideo_output_terminal_descriptor_t *desc)
   2671 {
   2672 	printf("Output Terminal: "
   2673 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2674 	    "bTerminalID=%d wTerminalType=%x bAssocTerminal=%d "
   2675 	    "bSourceID=%d iTerminal=%d",
   2676 	    desc->bLength,
   2677 	    desc->bDescriptorType,
   2678 	    desc->bDescriptorSubtype,
   2679 	    desc->bTerminalID,
   2680 	    UGETW(desc->wTerminalType),
   2681 	    desc->bAssocTerminal,
   2682 	    desc->bSourceID,
   2683 	    desc->iTerminal);
   2684 }
   2685 
   2686 static void
   2687 print_camera_terminal_descriptor(
   2688 	const uvideo_camera_terminal_descriptor_t *desc)
   2689 {
   2690 	printf("Camera Terminal: "
   2691 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2692 	    "bTerminalID=%d wTerminalType=%x bAssocTerminal=%d "
   2693 	    "iTerminal=%d "
   2694 	    "wObjectiveFocalLengthMin/Max=%d/%d "
   2695 	    "wOcularFocalLength=%d "
   2696 	    "bControlSize=%d ",
   2697 	    desc->bLength,
   2698 	    desc->bDescriptorType,
   2699 	    desc->bDescriptorSubtype,
   2700 	    desc->bTerminalID,
   2701 	    UGETW(desc->wTerminalType),
   2702 	    desc->bAssocTerminal,
   2703 	    desc->iTerminal,
   2704 	    UGETW(desc->wObjectiveFocalLengthMin),
   2705 	    UGETW(desc->wObjectiveFocalLengthMax),
   2706 	    UGETW(desc->wOcularFocalLength),
   2707 	    desc->bControlSize);
   2708 	printf("bmControls=");
   2709 	print_bitmap(desc->bmControls, desc->bControlSize);
   2710 }
   2711 
   2712 static void
   2713 print_selector_unit_descriptor(
   2714 	const uvideo_selector_unit_descriptor_t *desc)
   2715 {
   2716 	int i;
   2717 	const uByte *b;
   2718 	printf("Selector Unit: "
   2719 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2720 	    "bUnitID=%d bNrInPins=%d ",
   2721 	    desc->bLength,
   2722 	    desc->bDescriptorType,
   2723 	    desc->bDescriptorSubtype,
   2724 	    desc->bUnitID,
   2725 	    desc->bNrInPins);
   2726 	printf("baSourceIDs=");
   2727 	b = &desc->baSourceID[0];
   2728 	for (i = 0; i < desc->bNrInPins; ++i)
   2729 		printf("%d ", *b++);
   2730 	printf("iSelector=%d", *b);
   2731 }
   2732 
   2733 static void
   2734 print_processing_unit_descriptor(
   2735 	const uvideo_processing_unit_descriptor_t *desc)
   2736 {
   2737 	const uByte *b;
   2738 
   2739 	printf("Processing Unit: "
   2740 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2741 	    "bUnitID=%d bSourceID=%d wMaxMultiplier=%d bControlSize=%d ",
   2742 	    desc->bLength,
   2743 	    desc->bDescriptorType,
   2744 	    desc->bDescriptorSubtype,
   2745 	    desc->bUnitID,
   2746 	    desc->bSourceID,
   2747 	    UGETW(desc->wMaxMultiplier),
   2748 	    desc->bControlSize);
   2749 	printf("bmControls=");
   2750 	print_bitmap(desc->bmControls, desc->bControlSize);
   2751 	b = &desc->bControlSize + desc->bControlSize + 1;
   2752 	printf(" iProcessing=%d bmVideoStandards=", *b);
   2753 	b += 1;
   2754 	print_bitmap(b, 1);
   2755 }
   2756 
   2757 static void
   2758 print_extension_unit_descriptor(
   2759 	const uvideo_extension_unit_descriptor_t *desc)
   2760 {
   2761 	const uByte * byte;
   2762 	uByte controlbytes;
   2763 	int i;
   2764 
   2765 	printf("Extension Unit: "
   2766 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2767 	    "bUnitID=%d ",
   2768 	    desc->bLength,
   2769 	    desc->bDescriptorType,
   2770 	    desc->bDescriptorSubtype,
   2771 	    desc->bUnitID);
   2772 
   2773 	printf("guidExtensionCode=");
   2774 	usb_guid_print(&desc->guidExtensionCode);
   2775 	printf(" ");
   2776 
   2777 	printf("bNumControls=%d bNrInPins=%d ",
   2778 	    desc->bNumControls,
   2779 	    desc->bNrInPins);
   2780 
   2781 	printf("baSourceIDs=");
   2782 	byte = &desc->baSourceID[0];
   2783 	for (i = 0; i < desc->bNrInPins; ++i)
   2784 		printf("%d ", *byte++);
   2785 
   2786 	controlbytes = *byte++;
   2787 	printf("bControlSize=%d ", controlbytes);
   2788 	printf("bmControls=");
   2789 	print_bitmap(byte, controlbytes);
   2790 
   2791 	byte += controlbytes;
   2792 	printf(" iExtension=%d", *byte);
   2793 }
   2794 
   2795 static void
   2796 print_interrupt_endpoint_descriptor(
   2797 	const uvideo_vc_interrupt_endpoint_descriptor_t *desc)
   2798 {
   2799 	printf("Interrupt Endpoint: "
   2800 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2801 	    "wMaxTransferSize=%d ",
   2802 	    desc->bLength,
   2803 	    desc->bDescriptorType,
   2804 	    desc->bDescriptorSubtype,
   2805 	    UGETW(desc->wMaxTransferSize));
   2806 }
   2807 
   2808 
   2809 static void
   2810 print_vs_output_header_descriptor(
   2811 	const uvideo_vs_output_header_descriptor_t *desc)
   2812 {
   2813 	printf("Interface Output Header: "
   2814 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2815 	    "bNumFormats=%d wTotalLength=%d bEndpointAddress=%d "
   2816 	    "bTerminalLink=%d bControlSize=%d",
   2817 	    desc->bLength,
   2818 	    desc->bDescriptorType,
   2819 	    desc->bDescriptorSubtype,
   2820 	    desc->bNumFormats,
   2821 	    UGETW(desc->wTotalLength),
   2822 	    desc->bEndpointAddress,
   2823 	    desc->bTerminalLink,
   2824 	    desc->bControlSize);
   2825 }
   2826 
   2827 static void
   2828 print_vs_input_header_descriptor(
   2829 	const uvideo_vs_input_header_descriptor_t *desc)
   2830 {
   2831 	printf("Interface Input Header: "
   2832 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2833 	    "bNumFormats=%d wTotalLength=%d bEndpointAddress=%d "
   2834 	    "bmInfo=%x bTerminalLink=%d bStillCaptureMethod=%d "
   2835 	    "bTriggerSupport=%d bTriggerUsage=%d bControlSize=%d ",
   2836 	    desc->bLength,
   2837 	    desc->bDescriptorType,
   2838 	    desc->bDescriptorSubtype,
   2839 	    desc->bNumFormats,
   2840 	    UGETW(desc->wTotalLength),
   2841 	    desc->bEndpointAddress,
   2842 	    desc->bmInfo,
   2843 	    desc->bTerminalLink,
   2844 	    desc->bStillCaptureMethod,
   2845 	    desc->bTriggerSupport,
   2846 	    desc->bTriggerUsage,
   2847 	    desc->bControlSize);
   2848 	print_bitmap(desc->bmaControls, desc->bControlSize);
   2849 }
   2850 
   2851 static void
   2852 print_vs_format_uncompressed_descriptor(
   2853 	const uvideo_vs_format_uncompressed_descriptor_t *desc)
   2854 {
   2855 	printf("Format Uncompressed: "
   2856 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2857 	    "bFormatIndex=%d bNumFrameDescriptors=%d ",
   2858 	    desc->bLength,
   2859 	    desc->bDescriptorType,
   2860 	    desc->bDescriptorSubtype,
   2861 	    desc->bFormatIndex,
   2862 	    desc->bNumFrameDescriptors);
   2863 	usb_guid_print(&desc->guidFormat);
   2864 	printf(" bBitsPerPixel=%d bDefaultFrameIndex=%d "
   2865 	    "bAspectRatioX=%d bAspectRatioY=%d "
   2866 	    "bmInterlaceFlags=0x%02x bCopyProtect=%d",
   2867 	    desc->bBitsPerPixel,
   2868 	    desc->bDefaultFrameIndex,
   2869 	    desc->bAspectRatioX,
   2870 	    desc->bAspectRatioY,
   2871 	    desc->bmInterlaceFlags,
   2872 	    desc->bCopyProtect);
   2873 }
   2874 
   2875 static void
   2876 print_vs_frame_uncompressed_descriptor(
   2877 	const uvideo_vs_frame_uncompressed_descriptor_t *desc)
   2878 {
   2879 	printf("Frame Uncompressed: "
   2880 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2881 	    "bFrameIndex=%d bmCapabilities=0x%02x "
   2882 	    "wWidth=%d wHeight=%d dwMinBitRate=%u dwMaxBitRate=%u "
   2883 	    "dwMaxVideoFrameBufferSize=%u dwDefaultFrameInterval=%u "
   2884 	    "bFrameIntervalType=%d",
   2885 	    desc->bLength,
   2886 	    desc->bDescriptorType,
   2887 	    desc->bDescriptorSubtype,
   2888 	    desc->bFrameIndex,
   2889 	    desc->bmCapabilities,
   2890 	    UGETW(desc->wWidth),
   2891 	    UGETW(desc->wHeight),
   2892 	    UGETDW(desc->dwMinBitRate),
   2893 	    UGETDW(desc->dwMaxBitRate),
   2894 	    UGETDW(desc->dwMaxVideoFrameBufferSize),
   2895 	    UGETDW(desc->dwDefaultFrameInterval),
   2896 	    desc->bFrameIntervalType);
   2897 }
   2898 
   2899 static void
   2900 print_vs_format_mjpeg_descriptor(
   2901 	const uvideo_vs_format_mjpeg_descriptor_t *desc)
   2902 {
   2903 	printf("MJPEG format: "
   2904 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2905 	    "bFormatIndex=%d bNumFrameDescriptors=%d bmFlags=0x%02x "
   2906 	    "bDefaultFrameIndex=%d bAspectRatioX=%d bAspectRatioY=%d "
   2907 	    "bmInterlaceFlags=0x%02x bCopyProtect=%d",
   2908 	    desc->bLength,
   2909 	    desc->bDescriptorType,
   2910 	    desc->bDescriptorSubtype,
   2911 	    desc->bFormatIndex,
   2912 	    desc->bNumFrameDescriptors,
   2913 	    desc->bmFlags,
   2914 	    desc->bDefaultFrameIndex,
   2915 	    desc->bAspectRatioX,
   2916 	    desc->bAspectRatioY,
   2917 	    desc->bmInterlaceFlags,
   2918 	    desc->bCopyProtect);
   2919 }
   2920 
   2921 static void
   2922 print_vs_frame_mjpeg_descriptor(
   2923 	const uvideo_vs_frame_mjpeg_descriptor_t *desc)
   2924 {
   2925 	printf("MJPEG frame: "
   2926 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2927 	    "bFrameIndex=%d bmCapabilities=0x%02x "
   2928 	    "wWidth=%d wHeight=%d dwMinBitRate=%u dwMaxBitRate=%u "
   2929 	    "dwMaxVideoFrameBufferSize=%u dwDefaultFrameInterval=%u "
   2930 	    "bFrameIntervalType=%d",
   2931 	    desc->bLength,
   2932 	    desc->bDescriptorType,
   2933 	    desc->bDescriptorSubtype,
   2934 	    desc->bFrameIndex,
   2935 	    desc->bmCapabilities,
   2936 	    UGETW(desc->wWidth),
   2937 	    UGETW(desc->wHeight),
   2938 	    UGETDW(desc->dwMinBitRate),
   2939 	    UGETDW(desc->dwMaxBitRate),
   2940 	    UGETDW(desc->dwMaxVideoFrameBufferSize),
   2941 	    UGETDW(desc->dwDefaultFrameInterval),
   2942 	    desc->bFrameIntervalType);
   2943 }
   2944 
   2945 static void
   2946 print_vs_format_dv_descriptor(
   2947 	const uvideo_vs_format_dv_descriptor_t *desc)
   2948 {
   2949 	printf("MJPEG format: "
   2950 	    "Len=%d Type=0x%02x Subtype=0x%02x "
   2951 	    "bFormatIndex=%d dwMaxVideoFrameBufferSize=%u "
   2952 	    "bFormatType/Rate=%d bFormatType/Format=%d",
   2953 	    desc->bLength,
   2954 	    desc->bDescriptorType,
   2955 	    desc->bDescriptorSubtype,
   2956 	    desc->bFormatIndex,
   2957 	    UGETDW(desc->dwMaxVideoFrameBufferSize),
   2958 	    UVIDEO_GET_DV_FREQ(desc->bFormatType),
   2959 	    UVIDEO_GET_DV_FORMAT(desc->bFormatType));
   2960 }
   2961 
   2962 #endif /* !UVIDEO_DEBUG */
   2963 
   2964 static const usb_descriptor_t *
   2965 usb_desc_iter_peek_next(usbd_desc_iter_t *iter)
   2966 {
   2967         const usb_descriptor_t *desc;
   2968 
   2969         if (iter->cur + sizeof(usb_descriptor_t) >= iter->end) {
   2970                 if (iter->cur != iter->end)
   2971                         printf("usb_desc_iter_peek_next: bad descriptor\n");
   2972                 return NULL;
   2973         }
   2974         desc = (const usb_descriptor_t *)iter->cur;
   2975         if (desc->bLength == 0) {
   2976                 printf("usb_desc_iter_peek_next: descriptor length = 0\n");
   2977                 return NULL;
   2978         }
   2979         if (iter->cur + desc->bLength > iter->end) {
   2980                 printf("usb_desc_iter_peek_next: descriptor length too large\n");
   2981                 return NULL;
   2982         }
   2983         return desc;
   2984 }
   2985 
   2986 /* Return the next interface descriptor, skipping over any other
   2987  * descriptors.  Returns NULL at the end or on error. */
   2988 static const usb_interface_descriptor_t *
   2989 usb_desc_iter_next_interface(usbd_desc_iter_t *iter)
   2990 {
   2991 	const usb_descriptor_t *desc;
   2992 
   2993 	while ((desc = usb_desc_iter_peek_next(iter)) != NULL &&
   2994 	       desc->bDescriptorType != UDESC_INTERFACE)
   2995 	{
   2996 		usb_desc_iter_next(iter);
   2997 	}
   2998 
   2999 	return (const usb_interface_descriptor_t *)usb_desc_iter_next(iter);
   3000 }
   3001 
   3002 /* Returns the next non-interface descriptor, returning NULL when the
   3003  * next descriptor would be an interface descriptor. */
   3004 static const usb_descriptor_t *
   3005 usb_desc_iter_next_non_interface(usbd_desc_iter_t *iter)
   3006 {
   3007 	const usb_descriptor_t *desc;
   3008 
   3009 	if ((desc = usb_desc_iter_peek_next(iter)) != NULL &&
   3010 	    desc->bDescriptorType != UDESC_INTERFACE)
   3011 	{
   3012 		return (usb_desc_iter_next(iter));
   3013 	} else {
   3014 		return NULL;
   3015 	}
   3016 }
   3017 
   3018 #ifdef UVIDEO_DEBUG
   3019 static void
   3020 usb_guid_print(const usb_guid_t *guid)
   3021 {
   3022 	printf("%04X-%02X-%02X-",
   3023 	       UGETDW(guid->data1),
   3024 	       UGETW(guid->data2),
   3025 	       UGETW(guid->data3));
   3026 	printf("%02X%02X-",
   3027 	       guid->data4[0],
   3028 	       guid->data4[1]);
   3029 	printf("%02X%02X%02X%02X%02X%02X",
   3030 	       guid->data4[2],
   3031 	       guid->data4[3],
   3032 	       guid->data4[4],
   3033 	       guid->data4[5],
   3034 	       guid->data4[6],
   3035 	       guid->data4[7]);
   3036 }
   3037 #endif /* !UVIDEO_DEBUG */
   3038 
   3039 /* Returns less than zero, zero, or greater than zero if uguid is less
   3040  * than, equal to, or greater than guid. */
   3041 static int
   3042 usb_guid_cmp(const usb_guid_t *uguid, const guid_t *guid)
   3043 {
   3044 	if (guid->data1 > UGETDW(uguid->data1))
   3045 		return 1;
   3046 	else if (guid->data1 < UGETDW(uguid->data1))
   3047 		return -1;
   3048 
   3049 	if (guid->data2 > UGETW(uguid->data2))
   3050 		return 1;
   3051 	else if (guid->data2 < UGETW(uguid->data2))
   3052 		return -1;
   3053 
   3054 	if (guid->data3 > UGETW(uguid->data3))
   3055 		return 1;
   3056 	else if (guid->data3 < UGETW(uguid->data3))
   3057 		return -1;
   3058 
   3059 	return (memcmp(guid->data4, uguid->data4, 8));
   3060 }
   3061