Home | History | Annotate | Line # | Download | only in dev
video.c revision 1.46
      1 /* $NetBSD: video.c,v 1.46 2025/02/16 21:09:00 mlelstv Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2008 Patrick Mahoney <pat (at) polycrystal.org>
      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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * This ia a Video4Linux 2 compatible /dev/video driver for NetBSD
     34  *
     35  * See http://v4l2spec.bytesex.org/ for Video4Linux 2 specifications
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 __KERNEL_RCSID(0, "$NetBSD: video.c,v 1.46 2025/02/16 21:09:00 mlelstv Exp $");
     40 
     41 #include "video.h"
     42 #if NVIDEO > 0
     43 
     44 #include <sys/param.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/fcntl.h>
     47 #include <sys/vnode.h>
     48 #include <sys/poll.h>
     49 #include <sys/select.h>
     50 #include <sys/kmem.h>
     51 #include <sys/pool.h>
     52 #include <sys/conf.h>
     53 #include <sys/types.h>
     54 #include <sys/device.h>
     55 #include <sys/condvar.h>
     56 #include <sys/queue.h>
     57 #include <sys/videoio.h>
     58 
     59 #include <dev/video_if.h>
     60 
     61 #include "ioconf.h"
     62 
     63 /* #define VIDEO_DEBUG 1 */
     64 
     65 #ifdef VIDEO_DEBUG
     66 #define	DPRINTF(x)	do { if (videodebug) printf x; } while (0)
     67 #define	DPRINTFN(n,x)	do { if (videodebug>(n)) printf x; } while (0)
     68 int	videodebug = VIDEO_DEBUG;
     69 #else
     70 #define DPRINTF(x)
     71 #define DPRINTFN(n,x)
     72 #endif
     73 
     74 #define PAGE_ALIGN(a)		(((a) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))
     75 
     76 #define VIDEO_DRIVER_VERSION				\
     77 	(((__NetBSD_Version__ / 100000000) << 16) |	\
     78 	 ((__NetBSD_Version__ / 1000000 % 100) << 8) |	\
     79 	 (__NetBSD_Version__ / 100 % 100))
     80 
     81 /* TODO: move to sys/intr.h */
     82 #define IPL_VIDEO	IPL_VM
     83 #define splvideo()	splvm()
     84 
     85 #define VIDEO_MIN_BUFS 2
     86 #define VIDEO_MAX_BUFS 32
     87 #define VIDEO_NUM_BUFS 4
     88 
     89 /* Scatter Buffer - an array of fixed size (PAGE_SIZE) chunks
     90  * allocated non-contiguously and functions to get data into and out
     91  * of the scatter buffer. */
     92 struct scatter_buf {
     93 	pool_cache_t	sb_pool;
     94 	size_t		sb_size;    /* size in bytes */
     95 	size_t		sb_npages;  /* number of pages */
     96 	uint8_t		**sb_page_ary; /* array of page pointers */
     97 };
     98 
     99 struct scatter_io {
    100 	struct scatter_buf *sio_buf;
    101 	off_t		sio_offset;
    102 	size_t		sio_resid;
    103 };
    104 
    105 static void	scatter_buf_init(struct scatter_buf *);
    106 static void	scatter_buf_destroy(struct scatter_buf *);
    107 static int	scatter_buf_set_size(struct scatter_buf *, size_t);
    108 static paddr_t	scatter_buf_map(struct scatter_buf *, off_t);
    109 
    110 static bool	scatter_io_init(struct scatter_buf *, off_t, size_t, struct scatter_io *);
    111 static bool	scatter_io_next(struct scatter_io *, void **, size_t *);
    112 static void	scatter_io_undo(struct scatter_io *, size_t);
    113 static void	scatter_io_copyin(struct scatter_io *, const void *);
    114 /* static void	scatter_io_copyout(struct scatter_io *, void *); */
    115 static int	scatter_io_uiomove(struct scatter_io *, struct uio *);
    116 
    117 
    118 enum video_stream_method {
    119 	VIDEO_STREAM_METHOD_NONE,
    120 	VIDEO_STREAM_METHOD_READ,
    121 	VIDEO_STREAM_METHOD_MMAP,
    122 	VIDEO_STREAM_METHOD_USERPTR
    123 };
    124 
    125 struct video_buffer {
    126 	struct v4l2_buffer		*vb_buf;
    127 	SIMPLEQ_ENTRY(video_buffer)	entries;
    128 	u_int				busy;
    129 };
    130 
    131 SIMPLEQ_HEAD(sample_queue, video_buffer);
    132 
    133 struct video_stream {
    134 	int			vs_flags; /* flags given to open() */
    135 
    136 	struct video_format	vs_format;
    137 
    138 	int			vs_frameno; /* toggles between 0 and 1,
    139 					     * or -1 if new */
    140 	uint32_t		vs_sequence; /* absolute frame/sample number in
    141 					      * sequence, wraps around */
    142 	bool			vs_drop; /* drop payloads from current
    143 					  * frameno? */
    144 
    145 	enum v4l2_buf_type	vs_type;
    146 	uint8_t			vs_nbufs;
    147 	struct video_buffer	**vs_buf;
    148 
    149 	struct scatter_buf	vs_data; /* stores video data for MMAP
    150 					  * and READ */
    151 
    152 	/* Video samples may exist in different locations.  Initially,
    153 	 * samples are queued into the ingress queue.  The driver
    154 	 * grabs these in turn and fills them with video data.  Once
    155 	 * filled, they are moved to the egress queue.  Samples are
    156 	 * dequeued either by user with MMAP method or, with READ
    157 	 * method, videoread() works from the first sample in the
    158 	 * ingress queue without dequeing.  In the first case, the
    159 	 * user re-queues the buffer when finished, and videoread()
    160 	 * does the same when all data has been read.  The sample now
    161 	 * returns to the ingress queue. */
    162 	struct sample_queue	vs_ingress; /* samples under driver control */
    163 	struct sample_queue	vs_egress; /* samples headed for userspace */
    164 
    165 	bool			vs_streaming;
    166 	enum video_stream_method vs_method; /* method by which
    167 					     * userspace will read
    168 					     * samples */
    169 
    170 	kmutex_t		vs_lock; /* Lock to manipulate queues.
    171 					  * Should also be held when
    172 					  * changing number of
    173 					  * buffers. */
    174 	kcondvar_t		vs_sample_cv; /* signaled on new
    175 					       * ingress sample */
    176 	struct selinfo		vs_sel;
    177 
    178 	uint32_t		vs_bytesread; /* bytes read() from current
    179 					       * sample thus far */
    180 };
    181 
    182 struct video_softc {
    183 	device_t	sc_dev;
    184 	device_t	hw_dev;	  	 /* Hardware (parent) device */
    185 	void *		hw_softc;	 /* Hardware device private softc */
    186 	const struct video_hw_if *hw_if; /* Hardware interface */
    187 
    188 	u_int		sc_open;
    189 	int		sc_refcnt;
    190 	int		sc_opencnt;
    191 	bool		sc_dying;
    192 
    193 	struct video_stream sc_stream_in;
    194 };
    195 static int	video_print(void *, const char *);
    196 
    197 static int	video_match(device_t, cfdata_t, void *);
    198 static void	video_attach(device_t, device_t, void *);
    199 static int	video_detach(device_t, int);
    200 static int	video_activate(device_t, enum devact);
    201 
    202 dev_type_open(videoopen);
    203 dev_type_close(videoclose);
    204 dev_type_read(videoread);
    205 dev_type_write(videowrite);
    206 dev_type_ioctl(videoioctl);
    207 dev_type_poll(videopoll);
    208 dev_type_mmap(videommap);
    209 
    210 const struct cdevsw video_cdevsw = {
    211 	.d_open = videoopen,
    212 	.d_close = videoclose,
    213 	.d_read = videoread,
    214 	.d_write = videowrite,
    215 	.d_ioctl = videoioctl,
    216 	.d_stop = nostop,
    217 	.d_tty = notty,
    218 	.d_poll = videopoll,
    219 	.d_mmap = videommap,
    220 	.d_kqfilter = nokqfilter,
    221 	.d_discard = nodiscard,
    222 	.d_flag = D_OTHER
    223 };
    224 
    225 #define VIDEOUNIT(n)	(minor(n))
    226 
    227 CFATTACH_DECL_NEW(video, sizeof(struct video_softc),
    228 		  video_match, video_attach, video_detach, video_activate);
    229 
    230 static const char *	video_pixel_format_str(enum video_pixel_format);
    231 
    232 /* convert various values from V4L2 to native values of this driver */
    233 static uint16_t	v4l2id_to_control_id(uint32_t);
    234 static uint32_t control_flags_to_v4l2flags(uint32_t);
    235 static enum v4l2_ctrl_type control_type_to_v4l2type(enum video_control_type);
    236 
    237 static void	v4l2_format_to_video_format(const struct v4l2_format *,
    238 					    struct video_format *);
    239 static void	video_format_to_v4l2_format(const struct video_format *,
    240 					    struct v4l2_format *);
    241 static void	v4l2_standard_to_video_standard(v4l2_std_id,
    242 						enum video_standard *);
    243 static void	video_standard_to_v4l2_standard(enum video_standard,
    244 						struct v4l2_standard *);
    245 static void	v4l2_input_to_video_input(const struct v4l2_input *,
    246 					  struct video_input *);
    247 static void	video_input_to_v4l2_input(const struct video_input *,
    248 					  struct v4l2_input *);
    249 static void	v4l2_audio_to_video_audio(const struct v4l2_audio *,
    250 					  struct video_audio *);
    251 static void	video_audio_to_v4l2_audio(const struct video_audio *,
    252 					  struct v4l2_audio *);
    253 static void	v4l2_tuner_to_video_tuner(const struct v4l2_tuner *,
    254 					  struct video_tuner *);
    255 static void	video_tuner_to_v4l2_tuner(const struct video_tuner *,
    256 					  struct v4l2_tuner *);
    257 
    258 /* V4L2 api functions, typically called from videoioctl() */
    259 static int	video_enum_format(struct video_softc *, struct v4l2_fmtdesc *);
    260 static int	video_get_format(struct video_softc *,
    261 				 struct v4l2_format *);
    262 static int	video_set_format(struct video_softc *,
    263 				 struct v4l2_format *);
    264 static int	video_try_format(struct video_softc *,
    265 				 struct v4l2_format *);
    266 static int	video_get_parm(struct video_softc *,
    267 			       struct v4l2_streamparm *);
    268 static int	video_set_parm(struct video_softc *,
    269 			       struct v4l2_streamparm *);
    270 static int	video_enum_standard(struct video_softc *,
    271 				    struct v4l2_standard *);
    272 static int	video_get_standard(struct video_softc *, v4l2_std_id *);
    273 static int	video_set_standard(struct video_softc *, v4l2_std_id);
    274 static int	video_enum_input(struct video_softc *, struct v4l2_input *);
    275 static int	video_get_input(struct video_softc *, int *);
    276 static int	video_set_input(struct video_softc *, int);
    277 static int	video_enum_audio(struct video_softc *, struct v4l2_audio *);
    278 static int	video_get_audio(struct video_softc *, struct v4l2_audio *);
    279 static int	video_set_audio(struct video_softc *, struct v4l2_audio *);
    280 static int	video_get_tuner(struct video_softc *, struct v4l2_tuner *);
    281 static int	video_set_tuner(struct video_softc *, struct v4l2_tuner *);
    282 static int	video_get_frequency(struct video_softc *,
    283 				    struct v4l2_frequency *);
    284 static int	video_set_frequency(struct video_softc *,
    285 				    struct v4l2_frequency *);
    286 static int	video_query_control(struct video_softc *,
    287 				    struct v4l2_queryctrl *);
    288 static int	video_get_control(struct video_softc *,
    289 				  struct v4l2_control *);
    290 static int	video_set_control(struct video_softc *,
    291 				  const struct v4l2_control *);
    292 static int	video_request_bufs(struct video_softc *,
    293 				   struct v4l2_requestbuffers *);
    294 static int	video_query_buf(struct video_softc *, struct v4l2_buffer *);
    295 static int	video_queue_buf(struct video_softc *, struct v4l2_buffer *);
    296 static int	video_dequeue_buf(struct video_softc *, struct v4l2_buffer *);
    297 static int	video_stream_on(struct video_softc *, enum v4l2_buf_type);
    298 static int	video_stream_off(struct video_softc *, enum v4l2_buf_type);
    299 
    300 static struct video_buffer *	video_buffer_alloc(void);
    301 static void			video_buffer_free(struct video_buffer *);
    302 
    303 
    304 /* functions for video_stream */
    305 static void	video_stream_init(struct video_stream *);
    306 static void	video_stream_fini(struct video_stream *);
    307 
    308 static int	video_stream_setup_bufs(struct video_stream *,
    309 					enum video_stream_method,
    310 					uint8_t);
    311 static void	video_stream_teardown_bufs(struct video_stream *);
    312 
    313 static int	video_stream_realloc_bufs(struct video_stream *, uint8_t);
    314 #define		video_stream_free_bufs(vs) \
    315 	video_stream_realloc_bufs((vs), 0)
    316 
    317 static void	video_stream_enqueue(struct video_stream *,
    318 				     struct video_buffer *);
    319 static struct video_buffer * video_stream_dequeue(struct video_stream *);
    320 static void	video_stream_write(struct video_stream *,
    321 				   const struct video_payload *);
    322 static void	video_stream_sample_done(struct video_stream *);
    323 
    324 #ifdef VIDEO_DEBUG
    325 /* debugging */
    326 static const char *	video_ioctl_str(u_long);
    327 #endif
    328 
    329 
    330 static int
    331 video_match(device_t parent, cfdata_t match, void *aux)
    332 {
    333 #ifdef VIDEO_DEBUG
    334 	struct video_attach_args *args;
    335 
    336 	args = aux;
    337 	DPRINTF(("video_match: hw=%p\n", args->hw_if));
    338 #endif
    339 	return 1;
    340 }
    341 
    342 
    343 static void
    344 video_attach(device_t parent, device_t self, void *aux)
    345 {
    346 	struct video_softc *sc;
    347 	struct video_attach_args *args;
    348 
    349 	sc = device_private(self);
    350 	args = aux;
    351 
    352 	sc->sc_dev = self;
    353 	sc->hw_dev = parent;
    354 	sc->hw_if = args->hw_if;
    355 	sc->hw_softc = args->hw_softc;
    356 
    357 	sc->sc_open = 0;
    358 	sc->sc_refcnt = 0;
    359 	sc->sc_opencnt = 0;
    360 	sc->sc_dying = false;
    361 
    362 	video_stream_init(&sc->sc_stream_in);
    363 
    364 	aprint_naive("\n");
    365 	aprint_normal(": %s\n", sc->hw_if->get_devname(sc->hw_softc));
    366 
    367 	DPRINTF(("video_attach: sc=%p hwif=%p\n", sc, sc->hw_if));
    368 
    369 	if (!pmf_device_register(self, NULL, NULL))
    370 		aprint_error_dev(self, "couldn't establish power handler\n");
    371 }
    372 
    373 
    374 static int
    375 video_activate(device_t self, enum devact act)
    376 {
    377 	struct video_softc *sc = device_private(self);
    378 
    379 	DPRINTF(("video_activate: sc=%p\n", sc));
    380 	switch (act) {
    381 	case DVACT_DEACTIVATE:
    382 		sc->sc_dying = true;
    383 		return 0;
    384 	default:
    385 		return EOPNOTSUPP;
    386 	}
    387 }
    388 
    389 
    390 static int
    391 video_detach(device_t self, int flags)
    392 {
    393 	struct video_softc *sc;
    394 	int maj, mn;
    395 
    396 	sc = device_private(self);
    397 	DPRINTF(("video_detach: sc=%p flags=%d\n", sc, flags));
    398 
    399 	sc->sc_dying = true;
    400 
    401 	pmf_device_deregister(self);
    402 
    403 	maj = cdevsw_lookup_major(&video_cdevsw);
    404 	mn = device_unit(self);
    405 	/* close open instances */
    406 	vdevgone(maj, mn, mn, VCHR);
    407 
    408 	video_stream_fini(&sc->sc_stream_in);
    409 
    410 	return 0;
    411 }
    412 
    413 
    414 static int
    415 video_print(void *aux, const char *pnp)
    416 {
    417 	if (pnp != NULL) {
    418 		DPRINTF(("video_print: have pnp\n"));
    419 		aprint_normal("%s at %s\n", "video", pnp);
    420 	} else {
    421 		DPRINTF(("video_print: pnp is NULL\n"));
    422 	}
    423 	return UNCONF;
    424 }
    425 
    426 
    427 /*
    428  * Called from hardware driver.  This is where the MI audio driver
    429  * gets probed/attached to the hardware driver.
    430  */
    431 device_t
    432 video_attach_mi(const struct video_hw_if *hw_if, device_t parent, void *sc)
    433 {
    434 	struct video_attach_args args;
    435 
    436 	args.hw_if = hw_if;
    437 	args.hw_softc = sc;
    438 	return config_found(parent, &args, video_print,
    439 	    CFARGS(.iattr = "videobus"));
    440 }
    441 
    442 /* video_submit_payload - called by hardware driver to submit payload data */
    443 void
    444 video_submit_payload(device_t self, const struct video_payload *payload)
    445 {
    446 	struct video_softc *sc;
    447 
    448 	sc = device_private(self);
    449 
    450 	if (sc == NULL)
    451 		return;
    452 
    453 	video_stream_write(&sc->sc_stream_in, payload);
    454 }
    455 
    456 static const char *
    457 video_pixel_format_str(enum video_pixel_format px)
    458 {
    459 	switch (px) {
    460 	case VIDEO_FORMAT_UYVY:		return "UYVY";
    461 	case VIDEO_FORMAT_YUV420:	return "YUV420";
    462 	case VIDEO_FORMAT_YUY2: 	return "YUYV";
    463 	case VIDEO_FORMAT_NV12:		return "NV12";
    464 	case VIDEO_FORMAT_RGB24:	return "RGB24";
    465 	case VIDEO_FORMAT_RGB555:	return "RGB555";
    466 	case VIDEO_FORMAT_RGB565:	return "RGB565";
    467 	case VIDEO_FORMAT_SBGGR8:	return "SBGGR8";
    468 	case VIDEO_FORMAT_MJPEG:	return "MJPEG";
    469 	case VIDEO_FORMAT_DV:		return "DV";
    470 	case VIDEO_FORMAT_MPEG:		return "MPEG";
    471 	default:			return "Unknown";
    472 	}
    473 }
    474 
    475 /* Takes a V4L2 id and returns a "native" video driver control id.
    476  * TODO: is there a better way to do this?  some kind of array? */
    477 static uint16_t
    478 v4l2id_to_control_id(uint32_t v4l2id)
    479 {
    480 	/* mask includes class bits and control id bits */
    481 	switch (v4l2id & 0xffffff) {
    482 	case V4L2_CID_BRIGHTNESS:	return VIDEO_CONTROL_BRIGHTNESS;
    483 	case V4L2_CID_CONTRAST:		return VIDEO_CONTROL_CONTRAST;
    484 	case V4L2_CID_SATURATION:	return VIDEO_CONTROL_SATURATION;
    485 	case V4L2_CID_HUE:		return VIDEO_CONTROL_HUE;
    486 	case V4L2_CID_HUE_AUTO:		return VIDEO_CONTROL_HUE_AUTO;
    487 	case V4L2_CID_SHARPNESS:	return VIDEO_CONTROL_SHARPNESS;
    488 	case V4L2_CID_GAMMA:		return VIDEO_CONTROL_GAMMA;
    489 
    490 	/* "black level" means the same as "brightness", but V4L2
    491 	 * defines two separate controls that are not identical.
    492 	 * V4L2_CID_BLACK_LEVEL is deprecated however in V4L2. */
    493 	case V4L2_CID_BLACK_LEVEL:	return VIDEO_CONTROL_BRIGHTNESS;
    494 
    495 	case V4L2_CID_AUDIO_VOLUME:	return VIDEO_CONTROL_UNDEFINED;
    496 	case V4L2_CID_AUDIO_BALANCE:	return VIDEO_CONTROL_UNDEFINED;
    497 	case V4L2_CID_AUDIO_BASS:	return VIDEO_CONTROL_UNDEFINED;
    498 	case V4L2_CID_AUDIO_TREBLE:	return VIDEO_CONTROL_UNDEFINED;
    499 	case V4L2_CID_AUDIO_MUTE:	return VIDEO_CONTROL_UNDEFINED;
    500 	case V4L2_CID_AUDIO_LOUDNESS:	return VIDEO_CONTROL_UNDEFINED;
    501 
    502 	case V4L2_CID_AUTO_WHITE_BALANCE:
    503 		return VIDEO_CONTROL_WHITE_BALANCE_AUTO;
    504 	case V4L2_CID_DO_WHITE_BALANCE:
    505 		return VIDEO_CONTROL_WHITE_BALANCE_ACTION;
    506 	case V4L2_CID_RED_BALANCE:
    507 	case V4L2_CID_BLUE_BALANCE:
    508 		/* This might not fit in with the control_id/value_id scheme */
    509 		return VIDEO_CONTROL_WHITE_BALANCE_COMPONENT;
    510 	case V4L2_CID_WHITE_BALANCE_TEMPERATURE:
    511 		return VIDEO_CONTROL_WHITE_BALANCE_TEMPERATURE;
    512 	case V4L2_CID_EXPOSURE:
    513 		return VIDEO_CONTROL_EXPOSURE_TIME_ABSOLUTE;
    514 	case V4L2_CID_GAIN:		return VIDEO_CONTROL_GAIN;
    515 	case V4L2_CID_AUTOGAIN:		return VIDEO_CONTROL_GAIN_AUTO;
    516 	case V4L2_CID_HFLIP:		return VIDEO_CONTROL_HFLIP;
    517 	case V4L2_CID_VFLIP:		return VIDEO_CONTROL_VFLIP;
    518 	case V4L2_CID_HCENTER_DEPRECATED:
    519 	case V4L2_CID_VCENTER_DEPRECATED:
    520 		return VIDEO_CONTROL_UNDEFINED;
    521 	case V4L2_CID_POWER_LINE_FREQUENCY:
    522 		return VIDEO_CONTROL_POWER_LINE_FREQUENCY;
    523 	case V4L2_CID_BACKLIGHT_COMPENSATION:
    524 		return VIDEO_CONTROL_BACKLIGHT_COMPENSATION;
    525 	default:			return V4L2_CTRL_ID2CID(v4l2id);
    526 	}
    527 }
    528 
    529 
    530 static uint32_t
    531 control_flags_to_v4l2flags(uint32_t flags)
    532 {
    533 	uint32_t v4l2flags = 0;
    534 
    535 	if (flags & VIDEO_CONTROL_FLAG_DISABLED)
    536 		v4l2flags |= V4L2_CTRL_FLAG_INACTIVE;
    537 
    538 	if (!(flags & VIDEO_CONTROL_FLAG_WRITE))
    539 		v4l2flags |= V4L2_CTRL_FLAG_READ_ONLY;
    540 
    541 	if (flags & VIDEO_CONTROL_FLAG_AUTOUPDATE)
    542 		v4l2flags |= V4L2_CTRL_FLAG_GRABBED;
    543 
    544 	return v4l2flags;
    545 }
    546 
    547 
    548 static enum v4l2_ctrl_type
    549 control_type_to_v4l2type(enum video_control_type type) {
    550 	switch (type) {
    551 	case VIDEO_CONTROL_TYPE_INT:	return V4L2_CTRL_TYPE_INTEGER;
    552 	case VIDEO_CONTROL_TYPE_BOOL:	return V4L2_CTRL_TYPE_BOOLEAN;
    553 	case VIDEO_CONTROL_TYPE_LIST:	return V4L2_CTRL_TYPE_MENU;
    554 	case VIDEO_CONTROL_TYPE_ACTION:	return V4L2_CTRL_TYPE_BUTTON;
    555 	default:			return V4L2_CTRL_TYPE_INTEGER; /* err? */
    556 	}
    557 }
    558 
    559 
    560 static int
    561 video_query_control(struct video_softc *sc,
    562 		    struct v4l2_queryctrl *query)
    563 {
    564 	const struct video_hw_if *hw;
    565 	struct video_control_desc_group desc_group;
    566 	struct video_control_desc desc;
    567 	int err;
    568 
    569 	hw = sc->hw_if;
    570 	if (hw->get_control_desc_group) {
    571 		desc.group_id = desc.control_id =
    572 		    v4l2id_to_control_id(query->id);
    573 
    574 		desc_group.group_id = desc.group_id;
    575 		desc_group.length = 1;
    576 		desc_group.desc = &desc;
    577 
    578 		err = hw->get_control_desc_group(sc->hw_softc, &desc_group);
    579 		if (err != 0)
    580 			return err;
    581 
    582 		query->type = control_type_to_v4l2type(desc.type);
    583 		memcpy(query->name, desc.name, 32);
    584 		query->minimum = desc.min;
    585 		query->maximum = desc.max;
    586 		query->step = desc.step;
    587 		query->default_value = desc.def;
    588 		query->flags = control_flags_to_v4l2flags(desc.flags);
    589 
    590 		return 0;
    591 	} else {
    592 		return EINVAL;
    593 	}
    594 }
    595 
    596 
    597 /* Takes a single Video4Linux2 control and queries the driver for the
    598  * current value. */
    599 static int
    600 video_get_control(struct video_softc *sc,
    601 		  struct v4l2_control *vcontrol)
    602 {
    603 	const struct video_hw_if *hw;
    604 	struct video_control_group group;
    605 	struct video_control control;
    606 	int err;
    607 
    608 	hw = sc->hw_if;
    609 	if (hw->get_control_group) {
    610 		control.group_id = control.control_id =
    611 		    v4l2id_to_control_id(vcontrol->id);
    612 		/* ?? if "control_id" is arbitrarily defined by the
    613 		 * driver, then we need some way to store it...  Maybe
    614 		 * it doesn't matter for single value controls. */
    615 		control.value = 0;
    616 
    617 		group.group_id = control.group_id;
    618 		group.length = 1;
    619 		group.control = &control;
    620 
    621 		err = hw->get_control_group(sc->hw_softc, &group);
    622 		if (err != 0)
    623 			return err;
    624 
    625 		vcontrol->value = control.value;
    626 		return 0;
    627 	} else {
    628 		return EINVAL;
    629 	}
    630 }
    631 
    632 static void
    633 video_format_to_v4l2_format(const struct video_format *src,
    634 			    struct v4l2_format *dest)
    635 {
    636 	/* TODO: what about win and vbi formats? */
    637 	dest->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    638 	dest->fmt.pix.width = src->width;
    639 	dest->fmt.pix.height = src->height;
    640 	if (VIDEO_INTERLACED(src->interlace_flags))
    641 		dest->fmt.pix.field = V4L2_FIELD_INTERLACED;
    642 	else
    643 		dest->fmt.pix.field = V4L2_FIELD_NONE;
    644 	dest->fmt.pix.bytesperline = src->stride;
    645 	dest->fmt.pix.sizeimage = src->sample_size;
    646 	dest->fmt.pix.priv = src->priv;
    647 
    648 	switch (src->color.primaries) {
    649 	case VIDEO_COLOR_PRIMARIES_SMPTE_170M:
    650 		dest->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
    651 		break;
    652 	/* XXX */
    653 	case VIDEO_COLOR_PRIMARIES_UNSPECIFIED:
    654 	default:
    655 		dest->fmt.pix.colorspace = 0;
    656 		break;
    657 	}
    658 
    659 	switch (src->pixel_format) {
    660 	case VIDEO_FORMAT_UYVY:
    661 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
    662 		break;
    663 	case VIDEO_FORMAT_YUV420:
    664 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;
    665 		break;
    666 	case VIDEO_FORMAT_YUY2:
    667 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
    668 		break;
    669 	case VIDEO_FORMAT_NV12:
    670 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_NV12;
    671 		break;
    672 	case VIDEO_FORMAT_RGB24:
    673 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    674 		break;
    675 	case VIDEO_FORMAT_RGB555:
    676 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_RGB555;
    677 		break;
    678 	case VIDEO_FORMAT_RGB565:
    679 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_RGB565;
    680 		break;
    681 	case VIDEO_FORMAT_SBGGR8:
    682 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_SBGGR8;
    683 		break;
    684 	case VIDEO_FORMAT_MJPEG:
    685 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    686 		break;
    687 	case VIDEO_FORMAT_DV:
    688 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_DV;
    689 		break;
    690 	case VIDEO_FORMAT_MPEG:
    691 		dest->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
    692 		break;
    693 	case VIDEO_FORMAT_UNDEFINED:
    694 	default:
    695 		DPRINTF(("video_get_format: unknown pixel format %d\n",
    696 			 src->pixel_format));
    697 		dest->fmt.pix.pixelformat = 0; /* V4L2 doesn't define
    698 					       * and "undefined"
    699 					       * format? */
    700 		break;
    701 	}
    702 
    703 }
    704 
    705 static void
    706 v4l2_format_to_video_format(const struct v4l2_format *src,
    707 			    struct video_format *dest)
    708 {
    709 	switch (src->type) {
    710 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
    711 		dest->width = src->fmt.pix.width;
    712 		dest->height = src->fmt.pix.height;
    713 
    714 		dest->stride = src->fmt.pix.bytesperline;
    715 		dest->sample_size = src->fmt.pix.sizeimage;
    716 
    717 		if (src->fmt.pix.field == V4L2_FIELD_INTERLACED)
    718 			dest->interlace_flags = VIDEO_INTERLACE_ON;
    719 		else
    720 			dest->interlace_flags = VIDEO_INTERLACE_OFF;
    721 
    722 		switch (src->fmt.pix.colorspace) {
    723 		case V4L2_COLORSPACE_SMPTE170M:
    724 			dest->color.primaries =
    725 			    VIDEO_COLOR_PRIMARIES_SMPTE_170M;
    726 			break;
    727 		/* XXX */
    728 		default:
    729 			dest->color.primaries =
    730 			    VIDEO_COLOR_PRIMARIES_UNSPECIFIED;
    731 			break;
    732 		}
    733 
    734 		switch (src->fmt.pix.pixelformat) {
    735 		case V4L2_PIX_FMT_UYVY:
    736 			dest->pixel_format = VIDEO_FORMAT_UYVY;
    737 			break;
    738 		case V4L2_PIX_FMT_YUV420:
    739 			dest->pixel_format = VIDEO_FORMAT_YUV420;
    740 			break;
    741 		case V4L2_PIX_FMT_YUYV:
    742 			dest->pixel_format = VIDEO_FORMAT_YUY2;
    743 			break;
    744 		case V4L2_PIX_FMT_NV12:
    745 			dest->pixel_format = VIDEO_FORMAT_NV12;
    746 			break;
    747 		case V4L2_PIX_FMT_RGB24:
    748 			dest->pixel_format = VIDEO_FORMAT_RGB24;
    749 			break;
    750 		case V4L2_PIX_FMT_RGB555:
    751 			dest->pixel_format = VIDEO_FORMAT_RGB555;
    752 			break;
    753 		case V4L2_PIX_FMT_RGB565:
    754 			dest->pixel_format = VIDEO_FORMAT_RGB565;
    755 			break;
    756 		case V4L2_PIX_FMT_SBGGR8:
    757 			dest->pixel_format = VIDEO_FORMAT_SBGGR8;
    758 			break;
    759 		case V4L2_PIX_FMT_MJPEG:
    760 			dest->pixel_format = VIDEO_FORMAT_MJPEG;
    761 			break;
    762 		case V4L2_PIX_FMT_DV:
    763 			dest->pixel_format = VIDEO_FORMAT_DV;
    764 			break;
    765 		case V4L2_PIX_FMT_MPEG:
    766 			dest->pixel_format = VIDEO_FORMAT_MPEG;
    767 			break;
    768 		default:
    769 			DPRINTF(("video: unknown v4l2 pixel format %d\n",
    770 				 src->fmt.pix.pixelformat));
    771 			dest->pixel_format = VIDEO_FORMAT_UNDEFINED;
    772 			break;
    773 		}
    774 		break;
    775 	default:
    776 		/* TODO: other v4l2 format types */
    777 		DPRINTF(("video: unsupported v4l2 format type %d\n",
    778 			 src->type));
    779 		break;
    780 	}
    781 }
    782 
    783 static int
    784 video_enum_format(struct video_softc *sc, struct v4l2_fmtdesc *fmtdesc)
    785 {
    786 	const struct video_hw_if *hw;
    787 	struct video_format vfmt;
    788 	struct v4l2_format fmt;
    789 	int err;
    790 
    791 	hw = sc->hw_if;
    792 	if (hw->enum_format == NULL)
    793 		return ENOTTY;
    794 
    795 	err = hw->enum_format(sc->hw_softc, fmtdesc->index, &vfmt);
    796 	if (err != 0)
    797 		return err;
    798 
    799 	video_format_to_v4l2_format(&vfmt, &fmt);
    800 
    801 	fmtdesc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; /* TODO: only one type for now */
    802 	fmtdesc->flags = 0;
    803 	if (vfmt.pixel_format >= VIDEO_FORMAT_MJPEG)
    804 		fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
    805 	strlcpy(fmtdesc->description,
    806 		video_pixel_format_str(vfmt.pixel_format),
    807 		sizeof(fmtdesc->description));
    808 	fmtdesc->pixelformat = fmt.fmt.pix.pixelformat;
    809 
    810 	return 0;
    811 }
    812 
    813 static int
    814 video_enum_framesizes(struct video_softc *sc, struct v4l2_frmsizeenum *frmdesc)
    815 {
    816 	const struct video_hw_if *hw;
    817 	struct video_format vfmt;
    818 	struct v4l2_format fmt;
    819 	int err;
    820 
    821 	hw = sc->hw_if;
    822 	if (hw->enum_format == NULL)
    823 		return ENOTTY;
    824 
    825 	err = hw->enum_format(sc->hw_softc, frmdesc->index, &vfmt);
    826 	if (err != 0)
    827 		return err;
    828 
    829 	video_format_to_v4l2_format(&vfmt, &fmt);
    830 	if (fmt.fmt.pix.pixelformat != frmdesc->pixel_format) {
    831 		printf("video_enum_framesizes: type mismatch %x %x\n",
    832 		    fmt.fmt.pix.pixelformat, frmdesc->pixel_format);
    833 	}
    834 
    835 	frmdesc->type = V4L2_FRMSIZE_TYPE_DISCRETE; /* TODO: only one type for now */
    836 	frmdesc->discrete.width = vfmt.width;
    837 	frmdesc->discrete.height = vfmt.height;
    838 	return 0;
    839 }
    840 
    841 static int
    842 video_enum_frameival(struct video_softc *sc, struct v4l2_frmivalenum *frmdesc)
    843 {
    844 	const struct video_hw_if *hw;
    845 
    846 	hw = sc->hw_if;
    847 	if (hw->enum_format == NULL)
    848 		return ENOTTY;
    849 
    850 	frmdesc->type = V4L2_FRMSIZE_TYPE_DISCRETE;
    851 	frmdesc->discrete.numerator = 1;
    852 	frmdesc->discrete.denominator = 15;
    853 	return 0;
    854 }
    855 
    856 static int
    857 video_get_format(struct video_softc *sc,
    858 		      struct v4l2_format *format)
    859 {
    860 	const struct video_hw_if *hw;
    861 	struct video_format vfmt;
    862 	int err;
    863 
    864 	hw = sc->hw_if;
    865 	if (hw->get_format == NULL)
    866 		return ENOTTY;
    867 
    868 	err = hw->get_format(sc->hw_softc, &vfmt);
    869 	if (err != 0)
    870 		return err;
    871 
    872 	video_format_to_v4l2_format(&vfmt, format);
    873 
    874 	return 0;
    875 }
    876 
    877 static int
    878 video_set_format(struct video_softc *sc, struct v4l2_format *fmt)
    879 {
    880 	const struct video_hw_if *hw;
    881 	struct video_format vfmt;
    882 	int err;
    883 
    884 	hw = sc->hw_if;
    885 	if (hw->set_format == NULL)
    886 		return ENOTTY;
    887 
    888 	v4l2_format_to_video_format(fmt, &vfmt);
    889 
    890 	err = hw->set_format(sc->hw_softc, &vfmt);
    891 	if (err != 0)
    892 		return err;
    893 
    894 	video_format_to_v4l2_format(&vfmt, fmt);
    895 	sc->sc_stream_in.vs_format = vfmt;
    896 
    897 	return 0;
    898 }
    899 
    900 
    901 static int
    902 video_try_format(struct video_softc *sc,
    903 		      struct v4l2_format *format)
    904 {
    905 	const struct video_hw_if *hw;
    906 	struct video_format vfmt;
    907 	int err;
    908 
    909 	hw = sc->hw_if;
    910 	if (hw->try_format == NULL)
    911 		return ENOTTY;
    912 
    913 	v4l2_format_to_video_format(format, &vfmt);
    914 
    915 	err = hw->try_format(sc->hw_softc, &vfmt);
    916 	if (err != 0)
    917 		return err;
    918 
    919 	video_format_to_v4l2_format(&vfmt, format);
    920 
    921 	return 0;
    922 }
    923 
    924 static int
    925 video_get_parm(struct video_softc *sc, struct v4l2_streamparm *parm)
    926 {
    927 	struct video_fract fract;
    928 	const struct video_hw_if *hw;
    929 	int error;
    930 
    931 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
    932 		return EINVAL;
    933 
    934 	hw = sc->hw_if;
    935 	if (hw == NULL)
    936 		return ENXIO;
    937 
    938 	memset(&parm->parm, 0, sizeof(parm->parm));
    939 	if (hw->get_framerate != NULL) {
    940 		error = hw->get_framerate(sc->hw_softc, &fract);
    941 		if (error != 0)
    942 			return error;
    943 		parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
    944 		parm->parm.capture.timeperframe.numerator = fract.numerator;
    945 		parm->parm.capture.timeperframe.denominator = fract.denominator;
    946 	}
    947 
    948 	return 0;
    949 }
    950 
    951 static int
    952 video_set_parm(struct video_softc *sc, struct v4l2_streamparm *parm)
    953 {
    954 	struct video_fract fract;
    955 	const struct video_hw_if *hw;
    956 	int error;
    957 
    958 	if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
    959 		return EINVAL;
    960 
    961 	hw = sc->hw_if;
    962 	if (hw == NULL || hw->set_framerate == NULL)
    963 		return ENXIO;
    964 
    965 	error = hw->set_framerate(sc->hw_softc, &fract);
    966 	if (error != 0)
    967 		return error;
    968 
    969 	parm->parm.capture.timeperframe.numerator = fract.numerator;
    970 	parm->parm.capture.timeperframe.denominator = fract.denominator;
    971 
    972 	return 0;
    973 }
    974 
    975 static void
    976 v4l2_standard_to_video_standard(v4l2_std_id stdid,
    977     enum video_standard *vstd)
    978 {
    979 #define VSTD(id, vid)	case (id):	*vstd = (vid); break;
    980 	switch (stdid) {
    981 	VSTD(V4L2_STD_NTSC_M, VIDEO_STANDARD_NTSC_M)
    982 	default:
    983 		*vstd = VIDEO_STANDARD_UNKNOWN;
    984 		break;
    985 	}
    986 #undef VSTD
    987 }
    988 
    989 static void
    990 video_standard_to_v4l2_standard(enum video_standard vstd,
    991     struct v4l2_standard *std)
    992 {
    993 	switch (vstd) {
    994 	case VIDEO_STANDARD_NTSC_M:
    995 		std->id = V4L2_STD_NTSC_M;
    996 		strlcpy(std->name, "NTSC-M", sizeof(std->name));
    997 		std->frameperiod.numerator = 1001;
    998 		std->frameperiod.denominator = 30000;
    999 		std->framelines = 525;
   1000 		break;
   1001 	default:
   1002 		std->id = V4L2_STD_UNKNOWN;
   1003 		strlcpy(std->name, "Unknown", sizeof(std->name));
   1004 		break;
   1005 	}
   1006 }
   1007 
   1008 static int
   1009 video_enum_standard(struct video_softc *sc, struct v4l2_standard *std)
   1010 {
   1011 	const struct video_hw_if *hw = sc->hw_if;
   1012 	enum video_standard vstd;
   1013 	int err;
   1014 
   1015 	/* simple webcam drivers don't need to implement this callback */
   1016 	if (hw->enum_standard == NULL) {
   1017 		if (std->index != 0)
   1018 			return EINVAL;
   1019 		std->id = V4L2_STD_UNKNOWN;
   1020 		strlcpy(std->name, "webcam", sizeof(std->name));
   1021 		return 0;
   1022 	}
   1023 
   1024 	v4l2_standard_to_video_standard(std->id, &vstd);
   1025 
   1026 	err = hw->enum_standard(sc->hw_softc, std->index, &vstd);
   1027 	if (err != 0)
   1028 		return err;
   1029 
   1030 	video_standard_to_v4l2_standard(vstd, std);
   1031 
   1032 	return 0;
   1033 }
   1034 
   1035 static int
   1036 video_get_standard(struct video_softc *sc, v4l2_std_id *stdid)
   1037 {
   1038 	const struct video_hw_if *hw = sc->hw_if;
   1039 	struct v4l2_standard std;
   1040 	enum video_standard vstd;
   1041 	int err;
   1042 
   1043 	/* simple webcam drivers don't need to implement this callback */
   1044 	if (hw->get_standard == NULL) {
   1045 		*stdid = V4L2_STD_UNKNOWN;
   1046 		return 0;
   1047 	}
   1048 
   1049 	err = hw->get_standard(sc->hw_softc, &vstd);
   1050 	if (err != 0)
   1051 		return err;
   1052 
   1053 	video_standard_to_v4l2_standard(vstd, &std);
   1054 	*stdid = std.id;
   1055 
   1056 	return 0;
   1057 }
   1058 
   1059 static int
   1060 video_set_standard(struct video_softc *sc, v4l2_std_id stdid)
   1061 {
   1062 	const struct video_hw_if *hw = sc->hw_if;
   1063 	enum video_standard vstd;
   1064 
   1065 	/* simple webcam drivers don't need to implement this callback */
   1066 	if (hw->set_standard == NULL) {
   1067 		if (stdid != V4L2_STD_UNKNOWN)
   1068 			return EINVAL;
   1069 		return 0;
   1070 	}
   1071 
   1072 	v4l2_standard_to_video_standard(stdid, &vstd);
   1073 
   1074 	return hw->set_standard(sc->hw_softc, vstd);
   1075 }
   1076 
   1077 static void
   1078 v4l2_input_to_video_input(const struct v4l2_input *input,
   1079     struct video_input *vi)
   1080 {
   1081 	vi->index = input->index;
   1082 	strlcpy(vi->name, input->name, sizeof(vi->name));
   1083 	switch (input->type) {
   1084 	case V4L2_INPUT_TYPE_TUNER:
   1085 		vi->type = VIDEO_INPUT_TYPE_TUNER;
   1086 		break;
   1087 	case V4L2_INPUT_TYPE_CAMERA:
   1088 		vi->type = VIDEO_INPUT_TYPE_CAMERA;
   1089 		break;
   1090 	}
   1091 	vi->audiomask = input->audioset;
   1092 	vi->tuner_index = input->tuner;
   1093 	vi->standards = input->std;	/* ... values are the same */
   1094 	vi->status = 0;
   1095 	if (input->status & V4L2_IN_ST_NO_POWER)
   1096 		vi->status |= VIDEO_STATUS_NO_POWER;
   1097 	if (input->status & V4L2_IN_ST_NO_SIGNAL)
   1098 		vi->status |= VIDEO_STATUS_NO_SIGNAL;
   1099 	if (input->status & V4L2_IN_ST_NO_COLOR)
   1100 		vi->status |= VIDEO_STATUS_NO_COLOR;
   1101 	if (input->status & V4L2_IN_ST_NO_H_LOCK)
   1102 		vi->status |= VIDEO_STATUS_NO_HLOCK;
   1103 	if (input->status & V4L2_IN_ST_MACROVISION)
   1104 		vi->status |= VIDEO_STATUS_MACROVISION;
   1105 }
   1106 
   1107 static void
   1108 video_input_to_v4l2_input(const struct video_input *vi,
   1109     struct v4l2_input *input)
   1110 {
   1111 	input->index = vi->index;
   1112 	strlcpy(input->name, vi->name, sizeof(input->name));
   1113 	switch (vi->type) {
   1114 	case VIDEO_INPUT_TYPE_TUNER:
   1115 		input->type = V4L2_INPUT_TYPE_TUNER;
   1116 		break;
   1117 	case VIDEO_INPUT_TYPE_CAMERA:
   1118 		input->type = V4L2_INPUT_TYPE_CAMERA;
   1119 		break;
   1120 	}
   1121 	input->audioset = vi->audiomask;
   1122 	input->tuner = vi->tuner_index;
   1123 	input->std = vi->standards;	/* ... values are the same */
   1124 	input->status = 0;
   1125 	if (vi->status & VIDEO_STATUS_NO_POWER)
   1126 		input->status |= V4L2_IN_ST_NO_POWER;
   1127 	if (vi->status & VIDEO_STATUS_NO_SIGNAL)
   1128 		input->status |= V4L2_IN_ST_NO_SIGNAL;
   1129 	if (vi->status & VIDEO_STATUS_NO_COLOR)
   1130 		input->status |= V4L2_IN_ST_NO_COLOR;
   1131 	if (vi->status & VIDEO_STATUS_NO_HLOCK)
   1132 		input->status |= V4L2_IN_ST_NO_H_LOCK;
   1133 	if (vi->status & VIDEO_STATUS_MACROVISION)
   1134 		input->status |= V4L2_IN_ST_MACROVISION;
   1135 }
   1136 
   1137 static int
   1138 video_enum_input(struct video_softc *sc, struct v4l2_input *input)
   1139 {
   1140 	const struct video_hw_if *hw = sc->hw_if;
   1141 	struct video_input vi;
   1142 	int err;
   1143 
   1144 	/* simple webcam drivers don't need to implement this callback */
   1145 	if (hw->enum_input == NULL) {
   1146 		if (input->index != 0)
   1147 			return EINVAL;
   1148 		memset(input, 0, sizeof(*input));
   1149 		input->index = 0;
   1150 		strlcpy(input->name, "Camera", sizeof(input->name));
   1151 		input->type = V4L2_INPUT_TYPE_CAMERA;
   1152 		return 0;
   1153 	}
   1154 
   1155 	v4l2_input_to_video_input(input, &vi);
   1156 
   1157 	err = hw->enum_input(sc->hw_softc, input->index, &vi);
   1158 	if (err != 0)
   1159 		return err;
   1160 
   1161 	video_input_to_v4l2_input(&vi, input);
   1162 
   1163 	return 0;
   1164 }
   1165 
   1166 static int
   1167 video_get_input(struct video_softc *sc, int *index)
   1168 {
   1169 	const struct video_hw_if *hw = sc->hw_if;
   1170 	struct video_input vi;
   1171 	struct v4l2_input input;
   1172 	int err;
   1173 
   1174 	/* simple webcam drivers don't need to implement this callback */
   1175 	if (hw->get_input == NULL) {
   1176 		*index = 0;
   1177 		return 0;
   1178 	}
   1179 
   1180 	input.index = *index;
   1181 	v4l2_input_to_video_input(&input, &vi);
   1182 
   1183 	err = hw->get_input(sc->hw_softc, &vi);
   1184 	if (err != 0)
   1185 		return err;
   1186 
   1187 	video_input_to_v4l2_input(&vi, &input);
   1188 	*index = input.index;
   1189 
   1190 	return 0;
   1191 }
   1192 
   1193 static int
   1194 video_set_input(struct video_softc *sc, int index)
   1195 {
   1196 	const struct video_hw_if *hw = sc->hw_if;
   1197 	struct video_input vi;
   1198 	struct v4l2_input input;
   1199 
   1200 	/* simple webcam drivers don't need to implement this callback */
   1201 	if (hw->set_input == NULL) {
   1202 		if (index != 0)
   1203 			return EINVAL;
   1204 		return 0;
   1205 	}
   1206 
   1207 	input.index = index;
   1208 	v4l2_input_to_video_input(&input, &vi);
   1209 
   1210 	return hw->set_input(sc->hw_softc, &vi);
   1211 }
   1212 
   1213 static void
   1214 v4l2_audio_to_video_audio(const struct v4l2_audio *audio,
   1215     struct video_audio *va)
   1216 {
   1217 	va->index = audio->index;
   1218 	strlcpy(va->name, audio->name, sizeof(va->name));
   1219 	va->caps = va->mode = 0;
   1220 	if (audio->capability & V4L2_AUDCAP_STEREO)
   1221 		va->caps |= VIDEO_AUDIO_F_STEREO;
   1222 	if (audio->capability & V4L2_AUDCAP_AVL)
   1223 		va->caps |= VIDEO_AUDIO_F_AVL;
   1224 	if (audio->mode & V4L2_AUDMODE_AVL)
   1225 		va->mode |= VIDEO_AUDIO_F_AVL;
   1226 }
   1227 
   1228 static void
   1229 video_audio_to_v4l2_audio(const struct video_audio *va,
   1230     struct v4l2_audio *audio)
   1231 {
   1232 	audio->index = va->index;
   1233 	strlcpy(audio->name, va->name, sizeof(audio->name));
   1234 	audio->capability = audio->mode = 0;
   1235 	if (va->caps & VIDEO_AUDIO_F_STEREO)
   1236 		audio->capability |= V4L2_AUDCAP_STEREO;
   1237 	if (va->caps & VIDEO_AUDIO_F_AVL)
   1238 		audio->capability |= V4L2_AUDCAP_AVL;
   1239 	if (va->mode & VIDEO_AUDIO_F_AVL)
   1240 		audio->mode |= V4L2_AUDMODE_AVL;
   1241 }
   1242 
   1243 static int
   1244 video_enum_audio(struct video_softc *sc, struct v4l2_audio *audio)
   1245 {
   1246 	const struct video_hw_if *hw = sc->hw_if;
   1247 	struct video_audio va;
   1248 	int err;
   1249 
   1250 	if (hw->enum_audio == NULL)
   1251 		return ENOTTY;
   1252 
   1253 	v4l2_audio_to_video_audio(audio, &va);
   1254 
   1255 	err = hw->enum_audio(sc->hw_softc, audio->index, &va);
   1256 	if (err != 0)
   1257 		return err;
   1258 
   1259 	video_audio_to_v4l2_audio(&va, audio);
   1260 
   1261 	return 0;
   1262 }
   1263 
   1264 static int
   1265 video_get_audio(struct video_softc *sc, struct v4l2_audio *audio)
   1266 {
   1267 	const struct video_hw_if *hw = sc->hw_if;
   1268 	struct video_audio va;
   1269 	int err;
   1270 
   1271 	if (hw->get_audio == NULL)
   1272 		return ENOTTY;
   1273 
   1274 	v4l2_audio_to_video_audio(audio, &va);
   1275 
   1276 	err = hw->get_audio(sc->hw_softc, &va);
   1277 	if (err != 0)
   1278 		return err;
   1279 
   1280 	video_audio_to_v4l2_audio(&va, audio);
   1281 
   1282 	return 0;
   1283 }
   1284 
   1285 static int
   1286 video_set_audio(struct video_softc *sc, struct v4l2_audio *audio)
   1287 {
   1288 	const struct video_hw_if *hw = sc->hw_if;
   1289 	struct video_audio va;
   1290 
   1291 	if (hw->set_audio == NULL)
   1292 		return ENOTTY;
   1293 
   1294 	v4l2_audio_to_video_audio(audio, &va);
   1295 
   1296 	return hw->set_audio(sc->hw_softc, &va);
   1297 }
   1298 
   1299 static void
   1300 v4l2_tuner_to_video_tuner(const struct v4l2_tuner *tuner,
   1301     struct video_tuner *vt)
   1302 {
   1303 	vt->index = tuner->index;
   1304 	strlcpy(vt->name, tuner->name, sizeof(vt->name));
   1305 	vt->freq_lo = tuner->rangelow;
   1306 	vt->freq_hi = tuner->rangehigh;
   1307 	vt->signal = tuner->signal;
   1308 	vt->afc = tuner->afc;
   1309 	vt->caps = 0;
   1310 	if (tuner->capability & V4L2_TUNER_CAP_STEREO)
   1311 		vt->caps |= VIDEO_TUNER_F_STEREO;
   1312 	if (tuner->capability & V4L2_TUNER_CAP_LANG1)
   1313 		vt->caps |= VIDEO_TUNER_F_LANG1;
   1314 	if (tuner->capability & V4L2_TUNER_CAP_LANG2)
   1315 		vt->caps |= VIDEO_TUNER_F_LANG2;
   1316 	switch (tuner->audmode) {
   1317 	case V4L2_TUNER_MODE_MONO:
   1318 		vt->mode = VIDEO_TUNER_F_MONO;
   1319 		break;
   1320 	case V4L2_TUNER_MODE_STEREO:
   1321 		vt->mode = VIDEO_TUNER_F_STEREO;
   1322 		break;
   1323 	case V4L2_TUNER_MODE_LANG1:
   1324 		vt->mode = VIDEO_TUNER_F_LANG1;
   1325 		break;
   1326 	case V4L2_TUNER_MODE_LANG2:
   1327 		vt->mode = VIDEO_TUNER_F_LANG2;
   1328 		break;
   1329 	case V4L2_TUNER_MODE_LANG1_LANG2:
   1330 		vt->mode = VIDEO_TUNER_F_LANG1 | VIDEO_TUNER_F_LANG2;
   1331 		break;
   1332 	}
   1333 }
   1334 
   1335 static void
   1336 video_tuner_to_v4l2_tuner(const struct video_tuner *vt,
   1337     struct v4l2_tuner *tuner)
   1338 {
   1339 	tuner->index = vt->index;
   1340 	strlcpy(tuner->name, vt->name, sizeof(tuner->name));
   1341 	tuner->rangelow = vt->freq_lo;
   1342 	tuner->rangehigh = vt->freq_hi;
   1343 	tuner->signal = vt->signal;
   1344 	tuner->afc = vt->afc;
   1345 	tuner->capability = 0;
   1346 	if (vt->caps & VIDEO_TUNER_F_STEREO)
   1347 		tuner->capability |= V4L2_TUNER_CAP_STEREO;
   1348 	if (vt->caps & VIDEO_TUNER_F_LANG1)
   1349 		tuner->capability |= V4L2_TUNER_CAP_LANG1;
   1350 	if (vt->caps & VIDEO_TUNER_F_LANG2)
   1351 		tuner->capability |= V4L2_TUNER_CAP_LANG2;
   1352 	switch (vt->mode) {
   1353 	case VIDEO_TUNER_F_MONO:
   1354 		tuner->audmode = V4L2_TUNER_MODE_MONO;
   1355 		break;
   1356 	case VIDEO_TUNER_F_STEREO:
   1357 		tuner->audmode = V4L2_TUNER_MODE_STEREO;
   1358 		break;
   1359 	case VIDEO_TUNER_F_LANG1:
   1360 		tuner->audmode = V4L2_TUNER_MODE_LANG1;
   1361 		break;
   1362 	case VIDEO_TUNER_F_LANG2:
   1363 		tuner->audmode = V4L2_TUNER_MODE_LANG2;
   1364 		break;
   1365 	case VIDEO_TUNER_F_LANG1|VIDEO_TUNER_F_LANG2:
   1366 		tuner->audmode = V4L2_TUNER_MODE_LANG1_LANG2;
   1367 		break;
   1368 	}
   1369 }
   1370 
   1371 static int
   1372 video_get_tuner(struct video_softc *sc, struct v4l2_tuner *tuner)
   1373 {
   1374 	const struct video_hw_if *hw = sc->hw_if;
   1375 	struct video_tuner vt;
   1376 	int err;
   1377 
   1378 	if (hw->get_tuner == NULL)
   1379 		return ENOTTY;
   1380 
   1381 	v4l2_tuner_to_video_tuner(tuner, &vt);
   1382 
   1383 	err = hw->get_tuner(sc->hw_softc, &vt);
   1384 	if (err != 0)
   1385 		return err;
   1386 
   1387 	video_tuner_to_v4l2_tuner(&vt, tuner);
   1388 
   1389 	return 0;
   1390 }
   1391 
   1392 static int
   1393 video_set_tuner(struct video_softc *sc, struct v4l2_tuner *tuner)
   1394 {
   1395 	const struct video_hw_if *hw = sc->hw_if;
   1396 	struct video_tuner vt;
   1397 
   1398 	if (hw->set_tuner == NULL)
   1399 		return ENOTTY;
   1400 
   1401 	v4l2_tuner_to_video_tuner(tuner, &vt);
   1402 
   1403 	return hw->set_tuner(sc->hw_softc, &vt);
   1404 }
   1405 
   1406 static int
   1407 video_get_frequency(struct video_softc *sc, struct v4l2_frequency *freq)
   1408 {
   1409 	const struct video_hw_if *hw = sc->hw_if;
   1410 	struct video_frequency vfreq;
   1411 	int err;
   1412 
   1413 	if (hw->get_frequency == NULL)
   1414 		return ENOTTY;
   1415 
   1416 	err = hw->get_frequency(sc->hw_softc, &vfreq);
   1417 	if (err)
   1418 		return err;
   1419 
   1420 	freq->tuner = vfreq.tuner_index;
   1421 	freq->type = V4L2_TUNER_ANALOG_TV;
   1422 	freq->frequency = vfreq.frequency;
   1423 
   1424 	return 0;
   1425 }
   1426 
   1427 static int
   1428 video_set_frequency(struct video_softc *sc, struct v4l2_frequency *freq)
   1429 {
   1430 	const struct video_hw_if *hw = sc->hw_if;
   1431 	struct video_frequency vfreq;
   1432 	struct video_tuner vt;
   1433 	int error;
   1434 
   1435 	if (hw->set_frequency == NULL || hw->get_tuner == NULL)
   1436 		return ENOTTY;
   1437 	if (freq->type != V4L2_TUNER_ANALOG_TV)
   1438 		return EINVAL;
   1439 
   1440 	vt.index = freq->tuner;
   1441 	error = hw->get_tuner(sc->hw_softc, &vt);
   1442 	if (error)
   1443 		return error;
   1444 
   1445 	if (freq->frequency < vt.freq_lo)
   1446 		freq->frequency = vt.freq_lo;
   1447 	else if (freq->frequency > vt.freq_hi)
   1448 		freq->frequency = vt.freq_hi;
   1449 
   1450 	vfreq.tuner_index = freq->tuner;
   1451 	vfreq.frequency = freq->frequency;
   1452 
   1453 	return hw->set_frequency(sc->hw_softc, &vfreq);
   1454 }
   1455 
   1456 /* Takes a single Video4Linux2 control, converts it to a struct
   1457  * video_control, and calls the hardware driver. */
   1458 static int
   1459 video_set_control(struct video_softc *sc,
   1460 		       const struct v4l2_control *vcontrol)
   1461 {
   1462 	const struct video_hw_if *hw;
   1463 	struct video_control_group group;
   1464 	struct video_control control;
   1465 
   1466 	hw = sc->hw_if;
   1467 	if (hw->set_control_group) {
   1468 		control.group_id = control.control_id =
   1469 		    v4l2id_to_control_id(vcontrol->id);
   1470 		/* ?? if "control_id" is arbitrarily defined by the
   1471 		 * driver, then we need some way to store it...  Maybe
   1472 		 * it doesn't matter for single value controls. */
   1473 		control.value = vcontrol->value;
   1474 
   1475 		group.group_id = control.group_id;
   1476 		group.length = 1;
   1477 		group.control = &control;
   1478 
   1479 		return (hw->set_control_group(sc->hw_softc, &group));
   1480 	} else {
   1481 		return EINVAL;
   1482 	}
   1483 }
   1484 
   1485 static int
   1486 video_request_bufs(struct video_softc *sc,
   1487 		   struct v4l2_requestbuffers *req)
   1488 {
   1489 	struct video_stream *vs = &sc->sc_stream_in;
   1490 	struct v4l2_buffer *buf;
   1491 	int i, err;
   1492 
   1493 	if (req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
   1494 		return EINVAL;
   1495 
   1496 	vs->vs_type = req->type;
   1497 
   1498 	switch (req->memory) {
   1499 	case V4L2_MEMORY_MMAP:
   1500 		if (req->count < VIDEO_MIN_BUFS)
   1501 			req->count = VIDEO_MIN_BUFS;
   1502 		else if (req->count > VIDEO_MAX_BUFS)
   1503 			req->count = VIDEO_MAX_BUFS;
   1504 
   1505 		err = video_stream_setup_bufs(vs,
   1506 					      VIDEO_STREAM_METHOD_MMAP,
   1507 					      req->count);
   1508 		if (err != 0)
   1509 			return err;
   1510 
   1511 		for (i = 0; i < req->count; ++i) {
   1512 			buf = vs->vs_buf[i]->vb_buf;
   1513 			buf->memory = V4L2_MEMORY_MMAP;
   1514 			buf->flags |= V4L2_BUF_FLAG_MAPPED;
   1515 		}
   1516 		break;
   1517 	case V4L2_MEMORY_USERPTR:
   1518 	default:
   1519 		return EINVAL;
   1520 	}
   1521 
   1522 	return 0;
   1523 }
   1524 
   1525 static int
   1526 video_query_buf(struct video_softc *sc,
   1527 		struct v4l2_buffer *buf)
   1528 {
   1529 	struct video_stream *vs = &sc->sc_stream_in;
   1530 
   1531 	if (buf->type != vs->vs_type)
   1532 		return EINVAL;
   1533 	if (buf->index >= vs->vs_nbufs)
   1534 		return EINVAL;
   1535 
   1536 	memcpy(buf, vs->vs_buf[buf->index]->vb_buf, sizeof(*buf));
   1537 
   1538 	return 0;
   1539 }
   1540 
   1541 /* Accept a buffer descriptor from userspace and return the indicated
   1542  * buffer to the driver's queue. */
   1543 static int
   1544 video_queue_buf(struct video_softc *sc, struct v4l2_buffer *userbuf)
   1545 {
   1546 	struct video_stream *vs = &sc->sc_stream_in;
   1547 	struct video_buffer *vb;
   1548 	struct v4l2_buffer *driverbuf;
   1549 
   1550 	if (userbuf->type != vs->vs_type) {
   1551 		DPRINTF(("video_queue_buf: expected type=%d got type=%d\n",
   1552 			 userbuf->type, vs->vs_type));
   1553 		return EINVAL;
   1554 	}
   1555 	if (userbuf->index >= vs->vs_nbufs) {
   1556 		DPRINTF(("video_queue_buf: invalid index %d >= %d\n",
   1557 			 userbuf->index, vs->vs_nbufs));
   1558 		return EINVAL;
   1559 	}
   1560 
   1561 	switch (vs->vs_method) {
   1562 	case VIDEO_STREAM_METHOD_MMAP:
   1563 		if (userbuf->memory != V4L2_MEMORY_MMAP) {
   1564 			DPRINTF(("video_queue_buf: invalid memory=%d\n",
   1565 				 userbuf->memory));
   1566 			return EINVAL;
   1567 		}
   1568 
   1569 		mutex_enter(&vs->vs_lock);
   1570 
   1571 		vb = vs->vs_buf[userbuf->index];
   1572 		driverbuf = vb->vb_buf;
   1573 		if (driverbuf->flags & V4L2_BUF_FLAG_QUEUED) {
   1574 			DPRINTF(("video_queue_buf: buf already queued; "
   1575 				 "flags=0x%x\n", driverbuf->flags));
   1576 			mutex_exit(&vs->vs_lock);
   1577 			return EINVAL;
   1578 		}
   1579 		video_stream_enqueue(vs, vb);
   1580 		memcpy(userbuf, driverbuf, sizeof(*driverbuf));
   1581 
   1582 		mutex_exit(&vs->vs_lock);
   1583 		break;
   1584 	default:
   1585 		return EINVAL;
   1586 	}
   1587 
   1588 	return 0;
   1589 }
   1590 
   1591 /* Dequeue the described buffer from the driver queue, making it
   1592  * available for reading via mmap. */
   1593 static int
   1594 video_dequeue_buf(struct video_softc *sc, struct v4l2_buffer *buf)
   1595 {
   1596 	struct video_stream *vs = &sc->sc_stream_in;
   1597 	struct video_buffer *vb;
   1598 	int err;
   1599 
   1600 	if (buf->type != vs->vs_type) {
   1601 		aprint_debug_dev(sc->sc_dev,
   1602 		    "requested type %d (expected %d)\n",
   1603 		    buf->type, vs->vs_type);
   1604 		return EINVAL;
   1605 	}
   1606 
   1607 	switch (vs->vs_method) {
   1608 	case VIDEO_STREAM_METHOD_MMAP:
   1609 		if (buf->memory != V4L2_MEMORY_MMAP) {
   1610 			aprint_debug_dev(sc->sc_dev,
   1611 			    "requested memory %d (expected %d)\n",
   1612 			    buf->memory, V4L2_MEMORY_MMAP);
   1613 			return EINVAL;
   1614 		}
   1615 
   1616 		mutex_enter(&vs->vs_lock);
   1617 
   1618 		if (vs->vs_flags & O_NONBLOCK) {
   1619 			vb = video_stream_dequeue(vs);
   1620 			if (vb == NULL) {
   1621 				mutex_exit(&vs->vs_lock);
   1622 				return EAGAIN;
   1623 			}
   1624 		} else {
   1625 			/* Block until we have sample */
   1626 			while ((vb = video_stream_dequeue(vs)) == NULL) {
   1627 				if (!vs->vs_streaming) {
   1628 					mutex_exit(&vs->vs_lock);
   1629 					return EINVAL;
   1630 				}
   1631 				err = cv_wait_sig(&vs->vs_sample_cv,
   1632 						  &vs->vs_lock);
   1633 				if (err != 0) {
   1634 					mutex_exit(&vs->vs_lock);
   1635 					return EINTR;
   1636 				}
   1637 			}
   1638 		}
   1639 
   1640 		memcpy(buf, vb->vb_buf, sizeof(*buf));
   1641 
   1642 		mutex_exit(&vs->vs_lock);
   1643 		break;
   1644 	default:
   1645 		aprint_debug_dev(sc->sc_dev, "unknown vs_method %d\n",
   1646 		    vs->vs_method);
   1647 		return EINVAL;
   1648 	}
   1649 
   1650 	return 0;
   1651 }
   1652 
   1653 static int
   1654 video_stream_on(struct video_softc *sc, enum v4l2_buf_type type)
   1655 {
   1656 	int err;
   1657 	struct video_stream *vs = &sc->sc_stream_in;
   1658 	const struct video_hw_if *hw;
   1659 
   1660 	if (vs->vs_streaming)
   1661 		return 0;
   1662 	if (type != vs->vs_type)
   1663 		return EINVAL;
   1664 
   1665 	hw = sc->hw_if;
   1666 	if (hw == NULL)
   1667 		return ENXIO;
   1668 
   1669 
   1670 	err = hw->start_transfer(sc->hw_softc);
   1671 	if (err != 0)
   1672 		return err;
   1673 
   1674 	vs->vs_streaming = true;
   1675 	return 0;
   1676 }
   1677 
   1678 static int
   1679 video_stream_off(struct video_softc *sc, enum v4l2_buf_type type)
   1680 {
   1681 	int err;
   1682 	struct video_stream *vs = &sc->sc_stream_in;
   1683 	const struct video_hw_if *hw;
   1684 
   1685 	if (!vs->vs_streaming)
   1686 		return 0;
   1687 	if (type != vs->vs_type)
   1688 		return EINVAL;
   1689 
   1690 	hw = sc->hw_if;
   1691 	if (hw == NULL)
   1692 		return ENXIO;
   1693 
   1694 	err = hw->stop_transfer(sc->hw_softc);
   1695 	if (err != 0)
   1696 		return err;
   1697 
   1698 	vs->vs_frameno = -1;
   1699 	vs->vs_sequence = 0;
   1700 	vs->vs_streaming = false;
   1701 
   1702 	return 0;
   1703 }
   1704 
   1705 int
   1706 videoopen(dev_t dev, int flags, int ifmt, struct lwp *l)
   1707 {
   1708 	struct video_softc *sc;
   1709 	const struct video_hw_if *hw;
   1710 	struct video_stream *vs;
   1711 	int err;
   1712 
   1713 	DPRINTF(("videoopen\n"));
   1714 
   1715 	sc = device_private(device_lookup(&video_cd, VIDEOUNIT(dev)));
   1716 	if (sc == NULL) {
   1717 		DPRINTF(("videoopen: failed to get softc for unit %d\n",
   1718 			VIDEOUNIT(dev)));
   1719 		return ENXIO;
   1720 	}
   1721 
   1722 	if (sc->sc_dying) {
   1723 		DPRINTF(("videoopen: dying\n"));
   1724 		return EIO;
   1725 	}
   1726 
   1727 	sc->sc_stream_in.vs_flags = flags;
   1728 
   1729 	DPRINTF(("videoopen: flags=0x%x sc=%p parent=%p\n",
   1730 		 flags, sc, sc->hw_dev));
   1731 
   1732 	hw = sc->hw_if;
   1733 	if (hw == NULL)
   1734 		return ENXIO;
   1735 
   1736 	device_active(sc->sc_dev, DVA_SYSTEM);
   1737 
   1738 	sc->sc_opencnt++;
   1739 
   1740 	if (hw->open != NULL) {
   1741 		err = hw->open(sc->hw_softc, flags);
   1742 		if (err)
   1743 			return err;
   1744 	}
   1745 
   1746 	/* set up input stream.  TODO: check flags to determine if
   1747 	 * "read" is desired? */
   1748 	vs = &sc->sc_stream_in;
   1749 
   1750 	if (hw->get_format != NULL) {
   1751 		err = hw->get_format(sc->hw_softc, &vs->vs_format);
   1752 		if (err != 0)
   1753 			return err;
   1754 	}
   1755 	return 0;
   1756 }
   1757 
   1758 
   1759 int
   1760 videoclose(dev_t dev, int flags, int ifmt, struct lwp *l)
   1761 {
   1762 	struct video_softc *sc;
   1763 	const struct video_hw_if *hw;
   1764 
   1765 	sc = device_private(device_lookup(&video_cd, VIDEOUNIT(dev)));
   1766 	if (sc == NULL)
   1767 		return ENXIO;
   1768 
   1769 	DPRINTF(("videoclose: sc=%p\n", sc));
   1770 
   1771 	hw = sc->hw_if;
   1772 	if (hw == NULL)
   1773 		return ENXIO;
   1774 
   1775 	device_active(sc->sc_dev, DVA_SYSTEM);
   1776 
   1777 	video_stream_off(sc, sc->sc_stream_in.vs_type);
   1778 
   1779 	/* ignore error */
   1780 	if (hw->close != NULL)
   1781 		hw->close(sc->hw_softc);
   1782 
   1783 	video_stream_teardown_bufs(&sc->sc_stream_in);
   1784 
   1785 	sc->sc_open = 0;
   1786 	sc->sc_opencnt--;
   1787 
   1788 	return 0;
   1789 }
   1790 
   1791 
   1792 int
   1793 videoread(dev_t dev, struct uio *uio, int ioflag)
   1794 {
   1795 	struct video_softc *sc;
   1796 	struct video_stream *vs;
   1797 	struct video_buffer *vb;
   1798 	struct scatter_io sio;
   1799 	int err;
   1800 	size_t len, done;
   1801 	off_t offset;
   1802 
   1803 	sc = device_private(device_lookup(&video_cd, VIDEOUNIT(dev)));
   1804 	if (sc == NULL)
   1805 		return ENXIO;
   1806 
   1807 	if (sc->sc_dying)
   1808 		return EIO;
   1809 
   1810 	vs = &sc->sc_stream_in;
   1811 
   1812 	/* userspace has chosen read() method */
   1813 	if (vs->vs_method == VIDEO_STREAM_METHOD_NONE) {
   1814 		err = video_stream_setup_bufs(vs,
   1815 					      VIDEO_STREAM_METHOD_READ,
   1816 					      VIDEO_NUM_BUFS);
   1817 		if (err != 0)
   1818 			return err;
   1819 
   1820 		err = video_stream_on(sc, vs->vs_type);
   1821 		if (err != 0)
   1822 			return err;
   1823 	} else if (vs->vs_method != VIDEO_STREAM_METHOD_READ) {
   1824 		return EBUSY;
   1825 	}
   1826 
   1827 	mutex_enter(&vs->vs_lock);
   1828 
   1829 retry:
   1830 	if (SIMPLEQ_EMPTY(&vs->vs_egress)) {
   1831 		if (vs->vs_flags & O_NONBLOCK) {
   1832 			mutex_exit(&vs->vs_lock);
   1833 			return EAGAIN;
   1834 		}
   1835 
   1836 		/* Block until we have a sample */
   1837 		while (SIMPLEQ_EMPTY(&vs->vs_egress)) {
   1838 			err = cv_wait_sig(&vs->vs_sample_cv,
   1839 					  &vs->vs_lock);
   1840 			if (err != 0) {
   1841 				mutex_exit(&vs->vs_lock);
   1842 				return EINTR;
   1843 			}
   1844 		}
   1845 
   1846 		vb = SIMPLEQ_FIRST(&vs->vs_egress);
   1847 	} else {
   1848 	        vb = SIMPLEQ_FIRST(&vs->vs_egress);
   1849 	}
   1850 
   1851 	/* Oops, empty sample buffer. */
   1852 	if (vb->vb_buf->bytesused == 0) {
   1853 		vb = video_stream_dequeue(vs);
   1854 		video_stream_enqueue(vs, vb);
   1855 		vs->vs_bytesread = 0;
   1856 		goto retry;
   1857 	}
   1858 
   1859 	if (vb->busy) {
   1860 		if (vs->vs_flags & O_NONBLOCK) {
   1861 			mutex_exit(&vs->vs_lock);
   1862 			return EAGAIN;
   1863 		}
   1864 
   1865 		while (vb->busy > 0) {
   1866 			err = cv_wait_sig(&vs->vs_sample_cv, &vs->vs_lock);
   1867 			if (err != 0) {
   1868 				mutex_exit(&vs->vs_lock);
   1869 				return EINTR;
   1870 			}
   1871 		}
   1872 	}
   1873 
   1874 	vb->busy++;
   1875 
   1876 	len = uimin(uio->uio_resid, vb->vb_buf->bytesused - vs->vs_bytesread);
   1877 	offset = vb->vb_buf->m.offset + vs->vs_bytesread;
   1878 
   1879 	mutex_exit(&vs->vs_lock);
   1880 
   1881 	done = 0;
   1882 	if (scatter_io_init(&vs->vs_data, offset, len, &sio)) {
   1883 		err = scatter_io_uiomove(&sio, uio);
   1884 		if (err == EFAULT)
   1885 			return EFAULT;
   1886 		done = len - sio.sio_resid;
   1887 	} else {
   1888 		DPRINTF(("video: invalid read\n"));
   1889 	}
   1890 
   1891 	/* Move the sample to the ingress queue if everything has
   1892 	 * been read */
   1893 	mutex_enter(&vs->vs_lock);
   1894 
   1895 	if (--vb->busy <= 0)
   1896 		cv_signal(&vs->vs_sample_cv);
   1897 
   1898 	vs->vs_bytesread += done;
   1899 	if (vs->vs_bytesread >= vb->vb_buf->bytesused) {
   1900 		vb = video_stream_dequeue(vs);
   1901 		video_stream_enqueue(vs, vb);
   1902 		vs->vs_bytesread = 0;
   1903 	}
   1904 
   1905 	mutex_exit(&vs->vs_lock);
   1906 
   1907 	return 0;
   1908 }
   1909 
   1910 
   1911 int
   1912 videowrite(dev_t dev, struct uio *uio, int ioflag)
   1913 {
   1914 	return ENXIO;
   1915 }
   1916 
   1917 
   1918 /*
   1919  * Before 64-bit time_t, timeval's tv_sec was 'long'.  Thus on LP64 ports
   1920  * v4l2_buffer is the same size and layout as before.  However it did change
   1921  * on LP32 ports, and we thus handle this difference here for "COMPAT_50".
   1922  */
   1923 
   1924 #ifndef _LP64
   1925 static void
   1926 buf50tobuf(const void *data, struct v4l2_buffer *buf)
   1927 {
   1928 	const struct v4l2_buffer50 *b50 = data;
   1929 
   1930 	buf->index = b50->index;
   1931 	buf->type = b50->type;
   1932 	buf->bytesused = b50->bytesused;
   1933 	buf->flags = b50->flags;
   1934 	buf->field = b50->field;
   1935 	timeval50_to_timeval(&b50->timestamp, &buf->timestamp);
   1936 	buf->timecode = b50->timecode;
   1937 	buf->sequence = b50->sequence;
   1938 	buf->memory = b50->memory;
   1939 	buf->m.offset = b50->m.offset;
   1940 	/* XXX: Handle userptr */
   1941 	buf->length = b50->length;
   1942 	buf->reserved2 = b50->reserved2;
   1943 	buf->reserved = b50->reserved;
   1944 }
   1945 
   1946 static void
   1947 buftobuf50(void *data, const struct v4l2_buffer *buf)
   1948 {
   1949 	struct v4l2_buffer50 *b50 = data;
   1950 
   1951 	b50->index = buf->index;
   1952 	b50->type = buf->type;
   1953 	b50->bytesused = buf->bytesused;
   1954 	b50->flags = buf->flags;
   1955 	b50->field = buf->field;
   1956 	timeval_to_timeval50(&buf->timestamp, &b50->timestamp);
   1957 	b50->timecode = buf->timecode;
   1958 	b50->sequence = buf->sequence;
   1959 	b50->memory = buf->memory;
   1960 	b50->m.offset = buf->m.offset;
   1961 	/* XXX: Handle userptr */
   1962 	b50->length = buf->length;
   1963 	b50->reserved2 = buf->reserved2;
   1964 	b50->reserved = buf->reserved;
   1965 }
   1966 #endif
   1967 
   1968 int
   1969 videoioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
   1970 {
   1971 	struct video_softc *sc;
   1972 	const struct video_hw_if *hw;
   1973 	struct v4l2_capability *cap;
   1974 	struct v4l2_fmtdesc *fmtdesc;
   1975 	struct v4l2_format *fmt;
   1976 	struct v4l2_standard *std;
   1977 	struct v4l2_input *input;
   1978 	struct v4l2_audio *audio;
   1979 	struct v4l2_tuner *tuner;
   1980 	struct v4l2_frequency *freq;
   1981 	struct v4l2_control *control;
   1982 	struct v4l2_queryctrl *query;
   1983 	struct v4l2_requestbuffers *reqbufs;
   1984 	struct v4l2_buffer *buf;
   1985 	struct v4l2_streamparm *parm;
   1986 	struct v4l2_frmsizeenum *size;
   1987 	struct v4l2_frmivalenum *ival;
   1988 	v4l2_std_id *stdid;
   1989 	enum v4l2_buf_type *typep;
   1990 	int *ip;
   1991 #ifndef _LP64
   1992 	struct v4l2_buffer bufspace;
   1993 	int error;
   1994 #endif
   1995 
   1996 	sc = device_private(device_lookup(&video_cd, VIDEOUNIT(dev)));
   1997 
   1998 	if (sc->sc_dying)
   1999 		return EIO;
   2000 
   2001 	hw = sc->hw_if;
   2002 	if (hw == NULL)
   2003 		return ENXIO;
   2004 
   2005 	switch (cmd) {
   2006 	case VIDIOC_QUERYCAP:
   2007 		cap = data;
   2008 		memset(cap, 0, sizeof(*cap));
   2009 		strlcpy(cap->driver,
   2010 			device_cfdriver(sc->hw_dev)->cd_name,
   2011 			sizeof(cap->driver));
   2012 		strlcpy(cap->card, hw->get_devname(sc->hw_softc),
   2013 			sizeof(cap->card));
   2014 		strlcpy(cap->bus_info, hw->get_businfo(sc->hw_softc),
   2015 			sizeof(cap->bus_info));
   2016 		cap->version = VIDEO_DRIVER_VERSION;
   2017 		cap->capabilities = 0;
   2018 		if (hw->start_transfer != NULL && hw->stop_transfer != NULL)
   2019 			cap->capabilities |= V4L2_CAP_VIDEO_CAPTURE |
   2020 			    V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
   2021 		if (hw->set_tuner != NULL && hw->get_tuner != NULL)
   2022 			cap->capabilities |= V4L2_CAP_TUNER;
   2023 		if (hw->set_audio != NULL && hw->get_audio != NULL &&
   2024 		    hw->enum_audio != NULL)
   2025 			cap->capabilities |= V4L2_CAP_AUDIO;
   2026 		return 0;
   2027 	case VIDIOC_ENUM_FMT:
   2028 		/* TODO: for now, just enumerate one default format */
   2029 		fmtdesc = data;
   2030 		if (fmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
   2031 			return EINVAL;
   2032 		return video_enum_format(sc, fmtdesc);
   2033 	case VIDIOC_G_FMT:
   2034 		fmt = data;
   2035 		return video_get_format(sc, fmt);
   2036 	case VIDIOC_S_FMT:
   2037 		fmt = data;
   2038 		if ((flag & FWRITE) == 0)
   2039 			return EPERM;
   2040 		return video_set_format(sc, fmt);
   2041 	case VIDIOC_TRY_FMT:
   2042 		fmt = data;
   2043 		return video_try_format(sc, fmt);
   2044 	case VIDIOC_G_PARM:
   2045 		parm = data;
   2046 		return video_get_parm(sc, parm);
   2047 	case VIDIOC_S_PARM:
   2048 		parm = data;
   2049 		if ((flag & FWRITE) == 0)
   2050 			return EPERM;
   2051 		return video_set_parm(sc, parm);
   2052 	case VIDIOC_ENUMSTD:
   2053 		std = data;
   2054 		return video_enum_standard(sc, std);
   2055 	case VIDIOC_G_STD:
   2056 		stdid = data;
   2057 		return video_get_standard(sc, stdid);
   2058 	case VIDIOC_S_STD:
   2059 		stdid = data;
   2060 		if ((flag & FWRITE) == 0)
   2061 			return EPERM;
   2062 		return video_set_standard(sc, *stdid);
   2063 	case VIDIOC_ENUMINPUT:
   2064 		input = data;
   2065 		return video_enum_input(sc, input);
   2066 	case VIDIOC_G_INPUT:
   2067 		ip = data;
   2068 		return video_get_input(sc, ip);
   2069 	case VIDIOC_S_INPUT:
   2070 		ip = data;
   2071 		if ((flag & FWRITE) == 0)
   2072 			return EPERM;
   2073 		return video_set_input(sc, *ip);
   2074 	case VIDIOC_ENUMAUDIO:
   2075 		audio = data;
   2076 		return video_enum_audio(sc, audio);
   2077 	case VIDIOC_G_AUDIO:
   2078 		audio = data;
   2079 		return video_get_audio(sc, audio);
   2080 	case VIDIOC_S_AUDIO:
   2081 		audio = data;
   2082 		if ((flag & FWRITE) == 0)
   2083 			return EPERM;
   2084 		return video_set_audio(sc, audio);
   2085 	case VIDIOC_G_TUNER:
   2086 		tuner = data;
   2087 		return video_get_tuner(sc, tuner);
   2088 	case VIDIOC_S_TUNER:
   2089 		tuner = data;
   2090 		if ((flag & FWRITE) == 0)
   2091 			return EPERM;
   2092 		return video_set_tuner(sc, tuner);
   2093 	case VIDIOC_G_FREQUENCY:
   2094 		freq = data;
   2095 		return video_get_frequency(sc, freq);
   2096 	case VIDIOC_S_FREQUENCY:
   2097 		freq = data;
   2098 		if ((flag & FWRITE) == 0)
   2099 			return EPERM;
   2100 		return video_set_frequency(sc, freq);
   2101 	case VIDIOC_QUERYCTRL:
   2102 		query = data;
   2103 		return (video_query_control(sc, query));
   2104 	case VIDIOC_G_CTRL:
   2105 		control = data;
   2106 		return (video_get_control(sc, control));
   2107 	case VIDIOC_S_CTRL:
   2108 		control = data;
   2109 		if ((flag & FWRITE) == 0)
   2110 			return EPERM;
   2111 		return (video_set_control(sc, control));
   2112 	case VIDIOC_REQBUFS:
   2113 		reqbufs = data;
   2114 		return (video_request_bufs(sc, reqbufs));
   2115 	case VIDIOC_QUERYBUF:
   2116 		buf = data;
   2117 		return video_query_buf(sc, buf);
   2118 #ifndef _LP64
   2119 	case VIDIOC_QUERYBUF50:
   2120 		buf50tobuf(data, buf = &bufspace);
   2121 		if ((error = video_query_buf(sc, buf)) != 0)
   2122 			return error;
   2123 		buftobuf50(data, buf);
   2124 		return 0;
   2125 #endif
   2126 	case VIDIOC_QBUF:
   2127 		buf = data;
   2128 		return video_queue_buf(sc, buf);
   2129 #ifndef _LP64
   2130 	case VIDIOC_QBUF50:
   2131 		buf50tobuf(data, buf = &bufspace);
   2132 		return video_queue_buf(sc, buf);
   2133 #endif
   2134 	case VIDIOC_DQBUF:
   2135 		buf = data;
   2136 		return video_dequeue_buf(sc, buf);
   2137 #ifndef _LP64
   2138 	case VIDIOC_DQBUF50:
   2139 		buf50tobuf(data, buf = &bufspace);
   2140 		if ((error = video_dequeue_buf(sc, buf)) != 0)
   2141 			return error;
   2142 		buftobuf50(data, buf);
   2143 		return 0;
   2144 #endif
   2145 	case VIDIOC_STREAMON:
   2146 		typep = data;
   2147 		return video_stream_on(sc, *typep);
   2148 	case VIDIOC_STREAMOFF:
   2149 		typep = data;
   2150 		return video_stream_off(sc, *typep);
   2151 	case VIDIOC_ENUM_FRAMESIZES:
   2152 		size = data;
   2153 		return video_enum_framesizes(sc, size);
   2154 	case VIDIOC_ENUM_FRAMEINTERVALS:
   2155 		ival = data;
   2156 		return video_enum_frameival(sc, ival);
   2157 	default:
   2158 		DPRINTF(("videoioctl: invalid cmd %s (%lx)\n",
   2159 			 video_ioctl_str(cmd), cmd));
   2160 		return EINVAL;
   2161 	}
   2162 }
   2163 
   2164 #ifdef VIDEO_DEBUG
   2165 static const char *
   2166 video_ioctl_str(u_long cmd)
   2167 {
   2168 	const char *str;
   2169 
   2170 	switch (cmd) {
   2171 	case VIDIOC_QUERYCAP:
   2172 		str = "VIDIOC_QUERYCAP";
   2173 		break;
   2174 	case VIDIOC_RESERVED:
   2175 		str = "VIDIOC_RESERVED";
   2176 		break;
   2177 	case VIDIOC_ENUM_FMT:
   2178 		str = "VIDIOC_ENUM_FMT";
   2179 		break;
   2180 	case VIDIOC_G_FMT:
   2181 		str = "VIDIOC_G_FMT";
   2182 		break;
   2183 	case VIDIOC_S_FMT:
   2184 		str = "VIDIOC_S_FMT";
   2185 		break;
   2186 /* 6 and 7 are VIDIOC_[SG]_COMP, which are unsupported */
   2187 	case VIDIOC_REQBUFS:
   2188 		str = "VIDIOC_REQBUFS";
   2189 		break;
   2190 	case VIDIOC_QUERYBUF:
   2191 		str = "VIDIOC_QUERYBUF";
   2192 		break;
   2193 #ifndef _LP64
   2194 	case VIDIOC_QUERYBUF50:
   2195 		str = "VIDIOC_QUERYBUF50";
   2196 		break;
   2197 #endif
   2198 	case VIDIOC_G_FBUF:
   2199 		str = "VIDIOC_G_FBUF";
   2200 		break;
   2201 	case VIDIOC_S_FBUF:
   2202 		str = "VIDIOC_S_FBUF";
   2203 		break;
   2204 	case VIDIOC_OVERLAY:
   2205 		str = "VIDIOC_OVERLAY";
   2206 		break;
   2207 	case VIDIOC_QBUF:
   2208 		str = "VIDIOC_QBUF";
   2209 		break;
   2210 #ifndef _LP64
   2211 	case VIDIOC_QBUF50:
   2212 		str = "VIDIOC_QBUF50";
   2213 		break;
   2214 #endif
   2215 	case VIDIOC_DQBUF:
   2216 		str = "VIDIOC_DQBUF";
   2217 		break;
   2218 #ifndef _LP64
   2219 	case VIDIOC_DQBUF50:
   2220 		str = "VIDIOC_DQBUF50";
   2221 		break;
   2222 #endif
   2223 	case VIDIOC_STREAMON:
   2224 		str = "VIDIOC_STREAMON";
   2225 		break;
   2226 	case VIDIOC_STREAMOFF:
   2227 		str = "VIDIOC_STREAMOFF";
   2228 		break;
   2229 	case VIDIOC_G_PARM:
   2230 		str = "VIDIOC_G_PARM";
   2231 		break;
   2232 	case VIDIOC_S_PARM:
   2233 		str = "VIDIOC_S_PARM";
   2234 		break;
   2235 	case VIDIOC_G_STD:
   2236 		str = "VIDIOC_G_STD";
   2237 		break;
   2238 	case VIDIOC_S_STD:
   2239 		str = "VIDIOC_S_STD";
   2240 		break;
   2241 	case VIDIOC_ENUMSTD:
   2242 		str = "VIDIOC_ENUMSTD";
   2243 		break;
   2244 	case VIDIOC_ENUMINPUT:
   2245 		str = "VIDIOC_ENUMINPUT";
   2246 		break;
   2247 	case VIDIOC_G_CTRL:
   2248 		str = "VIDIOC_G_CTRL";
   2249 		break;
   2250 	case VIDIOC_S_CTRL:
   2251 		str = "VIDIOC_S_CTRL";
   2252 		break;
   2253 	case VIDIOC_G_TUNER:
   2254 		str = "VIDIOC_G_TUNER";
   2255 		break;
   2256 	case VIDIOC_S_TUNER:
   2257 		str = "VIDIOC_S_TUNER";
   2258 		break;
   2259 	case VIDIOC_G_AUDIO:
   2260 		str = "VIDIOC_G_AUDIO";
   2261 		break;
   2262 	case VIDIOC_S_AUDIO:
   2263 		str = "VIDIOC_S_AUDIO";
   2264 		break;
   2265 	case VIDIOC_QUERYCTRL:
   2266 		str = "VIDIOC_QUERYCTRL";
   2267 		break;
   2268 	case VIDIOC_QUERYMENU:
   2269 		str = "VIDIOC_QUERYMENU";
   2270 		break;
   2271 	case VIDIOC_G_INPUT:
   2272 		str = "VIDIOC_G_INPUT";
   2273 		break;
   2274 	case VIDIOC_S_INPUT:
   2275 		str = "VIDIOC_S_INPUT";
   2276 		break;
   2277 	case VIDIOC_G_OUTPUT:
   2278 		str = "VIDIOC_G_OUTPUT";
   2279 		break;
   2280 	case VIDIOC_S_OUTPUT:
   2281 		str = "VIDIOC_S_OUTPUT";
   2282 		break;
   2283 	case VIDIOC_ENUMOUTPUT:
   2284 		str = "VIDIOC_ENUMOUTPUT";
   2285 		break;
   2286 	case VIDIOC_G_AUDOUT:
   2287 		str = "VIDIOC_G_AUDOUT";
   2288 		break;
   2289 	case VIDIOC_S_AUDOUT:
   2290 		str = "VIDIOC_S_AUDOUT";
   2291 		break;
   2292 	case VIDIOC_G_MODULATOR:
   2293 		str = "VIDIOC_G_MODULATOR";
   2294 		break;
   2295 	case VIDIOC_S_MODULATOR:
   2296 		str = "VIDIOC_S_MODULATOR";
   2297 		break;
   2298 	case VIDIOC_G_FREQUENCY:
   2299 		str = "VIDIOC_G_FREQUENCY";
   2300 		break;
   2301 	case VIDIOC_S_FREQUENCY:
   2302 		str = "VIDIOC_S_FREQUENCY";
   2303 		break;
   2304 	case VIDIOC_CROPCAP:
   2305 		str = "VIDIOC_CROPCAP";
   2306 		break;
   2307 	case VIDIOC_G_CROP:
   2308 		str = "VIDIOC_G_CROP";
   2309 		break;
   2310 	case VIDIOC_S_CROP:
   2311 		str = "VIDIOC_S_CROP";
   2312 		break;
   2313 	case VIDIOC_G_JPEGCOMP:
   2314 		str = "VIDIOC_G_JPEGCOMP";
   2315 		break;
   2316 	case VIDIOC_S_JPEGCOMP:
   2317 		str = "VIDIOC_S_JPEGCOMP";
   2318 		break;
   2319 	case VIDIOC_QUERYSTD:
   2320 		str = "VIDIOC_QUERYSTD";
   2321 		break;
   2322 	case VIDIOC_TRY_FMT:
   2323 		str = "VIDIOC_TRY_FMT";
   2324 		break;
   2325 	case VIDIOC_ENUMAUDIO:
   2326 		str = "VIDIOC_ENUMAUDIO";
   2327 		break;
   2328 	case VIDIOC_ENUMAUDOUT:
   2329 		str = "VIDIOC_ENUMAUDOUT";
   2330 		break;
   2331 	case VIDIOC_G_PRIORITY:
   2332 		str = "VIDIOC_G_PRIORITY";
   2333 		break;
   2334 	case VIDIOC_S_PRIORITY:
   2335 		str = "VIDIOC_S_PRIORITY";
   2336 		break;
   2337 	case VIDIOC_ENUM_FRAMESIZES:
   2338 		str = "VIDIOC_ENUM_FRAMESIZES";
   2339 		break;
   2340 	case VIDIOC_ENUM_FRAMEINTERVALS:
   2341 		str = "VIDIOC_FRAMEINTERVALS";
   2342 		break;
   2343 	default:
   2344 		str = "unknown";
   2345 		break;
   2346 	}
   2347 	return str;
   2348 }
   2349 #endif
   2350 
   2351 
   2352 int
   2353 videopoll(dev_t dev, int events, struct lwp *l)
   2354 {
   2355 	struct video_softc *sc;
   2356 	struct video_stream *vs;
   2357 	int err, revents = 0;
   2358 
   2359 	sc = device_private(device_lookup(&video_cd, VIDEOUNIT(dev)));
   2360 	vs = &sc->sc_stream_in;
   2361 
   2362 	if (sc->sc_dying)
   2363 		return (POLLHUP);
   2364 
   2365 	/* userspace has chosen read() method */
   2366 	if (vs->vs_method == VIDEO_STREAM_METHOD_NONE) {
   2367 		err = video_stream_setup_bufs(vs,
   2368 					      VIDEO_STREAM_METHOD_READ,
   2369 					      VIDEO_NUM_BUFS);
   2370 		if (err != 0)
   2371 			return POLLERR;
   2372 
   2373 		err = video_stream_on(sc, vs->vs_type);
   2374 		if (err != 0)
   2375 			return POLLERR;
   2376 	}
   2377 
   2378 	mutex_enter(&vs->vs_lock);
   2379 	if (!SIMPLEQ_EMPTY(&sc->sc_stream_in.vs_egress))
   2380 		revents |= events & (POLLIN | POLLRDNORM);
   2381 	else
   2382 		selrecord(l, &vs->vs_sel);
   2383 	mutex_exit(&vs->vs_lock);
   2384 
   2385 	return (revents);
   2386 }
   2387 
   2388 
   2389 paddr_t
   2390 videommap(dev_t dev, off_t off, int prot)
   2391 {
   2392 	struct video_softc *sc;
   2393 	struct video_stream *vs;
   2394 	/* paddr_t pa; */
   2395 
   2396 	sc = device_lookup_private(&video_cd, VIDEOUNIT(dev));
   2397 	if (sc->sc_dying)
   2398 		return -1;
   2399 
   2400 	vs = &sc->sc_stream_in;
   2401 
   2402 	return scatter_buf_map(&vs->vs_data, off);
   2403 }
   2404 
   2405 
   2406 /* Allocates buffers and initializes some fields.  The format field
   2407  * must already have been initialized. */
   2408 void
   2409 video_stream_init(struct video_stream *vs)
   2410 {
   2411 	vs->vs_method = VIDEO_STREAM_METHOD_NONE;
   2412 	vs->vs_flags = 0;
   2413 	vs->vs_frameno = -1;
   2414 	vs->vs_sequence = 0;
   2415 	vs->vs_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
   2416 	vs->vs_nbufs = 0;
   2417 	vs->vs_buf = NULL;
   2418 	vs->vs_streaming = false;
   2419 
   2420 	memset(&vs->vs_format, 0, sizeof(vs->vs_format));
   2421 
   2422 	SIMPLEQ_INIT(&vs->vs_ingress);
   2423 	SIMPLEQ_INIT(&vs->vs_egress);
   2424 
   2425 	mutex_init(&vs->vs_lock, MUTEX_DEFAULT, IPL_NONE);
   2426 	cv_init(&vs->vs_sample_cv, "video");
   2427 	selinit(&vs->vs_sel);
   2428 
   2429 	scatter_buf_init(&vs->vs_data);
   2430 }
   2431 
   2432 void
   2433 video_stream_fini(struct video_stream *vs)
   2434 {
   2435 	/* Sample data in queues has already been freed */
   2436 	/* while (SIMPLEQ_FIRST(&vs->vs_ingress) != NULL)
   2437 		SIMPLEQ_REMOVE_HEAD(&vs->vs_ingress, entries);
   2438 	while (SIMPLEQ_FIRST(&vs->vs_egress) != NULL)
   2439 	SIMPLEQ_REMOVE_HEAD(&vs->vs_egress, entries); */
   2440 
   2441 	mutex_destroy(&vs->vs_lock);
   2442 	cv_destroy(&vs->vs_sample_cv);
   2443 	seldestroy(&vs->vs_sel);
   2444 
   2445 	scatter_buf_destroy(&vs->vs_data);
   2446 }
   2447 
   2448 static int
   2449 video_stream_setup_bufs(struct video_stream *vs,
   2450 			enum video_stream_method method,
   2451 			uint8_t nbufs)
   2452 {
   2453 	int i, err;
   2454 
   2455 	mutex_enter(&vs->vs_lock);
   2456 
   2457 	/* Ensure that all allocated buffers are queued and not under
   2458 	 * userspace control. */
   2459 	for (i = 0; i < vs->vs_nbufs; ++i) {
   2460 		if (!(vs->vs_buf[i]->vb_buf->flags & V4L2_BUF_FLAG_QUEUED)) {
   2461 			mutex_exit(&vs->vs_lock);
   2462 			return EBUSY;
   2463 		}
   2464 	}
   2465 
   2466 	/* Allocate the buffers */
   2467 	err = video_stream_realloc_bufs(vs, nbufs);
   2468 	if (err != 0) {
   2469 		mutex_exit(&vs->vs_lock);
   2470 		return err;
   2471 	}
   2472 
   2473 	/* Queue up buffers for read method.  Other methods are queued
   2474 	 * by VIDIOC_QBUF ioctl. */
   2475 	if (method == VIDEO_STREAM_METHOD_READ) {
   2476 		for (i = 0; i < nbufs; ++i)
   2477 			if (!(vs->vs_buf[i]->vb_buf->flags & V4L2_BUF_FLAG_QUEUED))
   2478 				video_stream_enqueue(vs, vs->vs_buf[i]);
   2479 	}
   2480 
   2481 	vs->vs_method = method;
   2482 	mutex_exit(&vs->vs_lock);
   2483 
   2484 	return 0;
   2485 }
   2486 
   2487 /* Free all buffer memory in preparation for close().  This should
   2488  * free buffers regardless of errors.  Use video_stream_setup_bufs if
   2489  * you need to check for errors. Streaming should be off before
   2490  * calling this function. */
   2491 static void
   2492 video_stream_teardown_bufs(struct video_stream *vs)
   2493 {
   2494 	int err;
   2495 
   2496 	mutex_enter(&vs->vs_lock);
   2497 
   2498 	if (vs->vs_streaming) {
   2499 		DPRINTF(("video_stream_teardown_bufs: "
   2500 			 "tearing down bufs while streaming\n"));
   2501 	}
   2502 
   2503 	/* dequeue all buffers */
   2504 	while (SIMPLEQ_FIRST(&vs->vs_ingress) != NULL)
   2505 		SIMPLEQ_REMOVE_HEAD(&vs->vs_ingress, entries);
   2506 	while (SIMPLEQ_FIRST(&vs->vs_egress) != NULL)
   2507 		SIMPLEQ_REMOVE_HEAD(&vs->vs_egress, entries);
   2508 
   2509 	err = video_stream_free_bufs(vs);
   2510 	if (err != 0) {
   2511 		DPRINTF(("video_stream_teardown_bufs: "
   2512 			 "error releasing buffers: %d\n",
   2513 			 err));
   2514 	}
   2515 	vs->vs_method = VIDEO_STREAM_METHOD_NONE;
   2516 
   2517 	mutex_exit(&vs->vs_lock);
   2518 }
   2519 
   2520 static struct video_buffer *
   2521 video_buffer_alloc(void)
   2522 {
   2523 	struct video_buffer *vb;
   2524 
   2525 	vb = kmem_alloc(sizeof(*vb), KM_SLEEP);
   2526 	vb->vb_buf = kmem_alloc(sizeof(*vb->vb_buf), KM_SLEEP);
   2527 	return vb;
   2528 }
   2529 
   2530 static void
   2531 video_buffer_free(struct video_buffer *vb)
   2532 {
   2533 	kmem_free(vb->vb_buf, sizeof(*vb->vb_buf));
   2534 	vb->vb_buf = NULL;
   2535 	kmem_free(vb, sizeof(*vb));
   2536 }
   2537 
   2538 /* TODO: for userptr method
   2539 struct video_buffer *
   2540 video_buf_alloc_with_ubuf(struct v4l2_buffer *buf)
   2541 {
   2542 }
   2543 
   2544 void
   2545 video_buffer_free_with_ubuf(struct video_buffer *vb)
   2546 {
   2547 }
   2548 */
   2549 
   2550 static int
   2551 video_stream_realloc_bufs(struct video_stream *vs, uint8_t nbufs)
   2552 {
   2553 	int i, err;
   2554 	uint8_t minnbufs, oldnbufs;
   2555 	size_t size;
   2556 	off_t offset;
   2557 	struct video_buffer **oldbuf;
   2558 	struct v4l2_buffer *buf;
   2559 
   2560 	size = PAGE_ALIGN(vs->vs_format.sample_size) * nbufs;
   2561 	err = scatter_buf_set_size(&vs->vs_data, size);
   2562 	if (err != 0)
   2563 		return err;
   2564 
   2565 	oldnbufs = vs->vs_nbufs;
   2566 	oldbuf = vs->vs_buf;
   2567 
   2568 	vs->vs_nbufs = nbufs;
   2569 	if (nbufs > 0) {
   2570 		vs->vs_buf =
   2571 		    kmem_alloc(sizeof(struct video_buffer *) * nbufs, KM_SLEEP);
   2572 	} else {
   2573 		vs->vs_buf = NULL;
   2574 	}
   2575 
   2576 	minnbufs = uimin(vs->vs_nbufs, oldnbufs);
   2577 	/* copy any bufs that will be reused */
   2578 	for (i = 0; i < minnbufs; ++i)
   2579 		vs->vs_buf[i] = oldbuf[i];
   2580 	/* allocate any necessary new bufs */
   2581 	for (; i < vs->vs_nbufs; ++i)
   2582 		vs->vs_buf[i] = video_buffer_alloc();
   2583 	/* free any bufs no longer used */
   2584 	for (; i < oldnbufs; ++i) {
   2585 		video_buffer_free(oldbuf[i]);
   2586 		oldbuf[i] = NULL;
   2587 	}
   2588 
   2589 	/* Free old buffer metadata */
   2590 	if (oldbuf != NULL)
   2591 		kmem_free(oldbuf, sizeof(struct video_buffer *) * oldnbufs);
   2592 
   2593 	/* initialize bufs */
   2594 	offset = 0;
   2595 	for (i = 0; i < vs->vs_nbufs; ++i) {
   2596 		buf = vs->vs_buf[i]->vb_buf;
   2597 		buf->index = i;
   2598 		buf->type = vs->vs_type;
   2599 		buf->bytesused = 0;
   2600 		buf->flags = 0;
   2601 		buf->field = 0;
   2602 		buf->sequence = 0;
   2603 		buf->memory = V4L2_MEMORY_MMAP;
   2604 		buf->m.offset = offset;
   2605 		buf->length = PAGE_ALIGN(vs->vs_format.sample_size);
   2606 		buf->reserved2 = 0;
   2607 		buf->reserved = 0;
   2608 
   2609 		offset += buf->length;
   2610 	}
   2611 
   2612 	return 0;
   2613 }
   2614 
   2615 /* Accepts a video_sample into the ingress queue.  Caller must hold
   2616  * the stream lock. */
   2617 void
   2618 video_stream_enqueue(struct video_stream *vs, struct video_buffer *vb)
   2619 {
   2620 	if (vb->vb_buf->flags & V4L2_BUF_FLAG_QUEUED) {
   2621 		DPRINTF(("video_stream_enqueue: sample already queued\n"));
   2622 		return;
   2623 	}
   2624 
   2625 	vb->vb_buf->flags |= V4L2_BUF_FLAG_QUEUED;
   2626 	vb->vb_buf->flags &= ~V4L2_BUF_FLAG_DONE;
   2627 
   2628 	vb->vb_buf->bytesused = 0;
   2629 
   2630 	SIMPLEQ_INSERT_TAIL(&vs->vs_ingress, vb, entries);
   2631 }
   2632 
   2633 
   2634 /* Removes the head of the egress queue for use by userspace.  Caller
   2635  * must hold the stream lock. */
   2636 struct video_buffer *
   2637 video_stream_dequeue(struct video_stream *vs)
   2638 {
   2639 	struct video_buffer *vb;
   2640 
   2641 	if (!SIMPLEQ_EMPTY(&vs->vs_egress)) {
   2642 		vb = SIMPLEQ_FIRST(&vs->vs_egress);
   2643 		SIMPLEQ_REMOVE_HEAD(&vs->vs_egress, entries);
   2644 		vb->vb_buf->flags &= ~V4L2_BUF_FLAG_QUEUED;
   2645 		vb->vb_buf->flags |= V4L2_BUF_FLAG_DONE;
   2646 		return vb;
   2647 	} else {
   2648 		return NULL;
   2649 	}
   2650 }
   2651 
   2652 static void
   2653 v4l2buf_set_timestamp(struct v4l2_buffer *buf)
   2654 {
   2655 
   2656 	getmicrotime(&buf->timestamp);
   2657 }
   2658 
   2659 /*
   2660  * write payload data to the appropriate video sample, possibly moving
   2661  * the sample from ingress to egress queues
   2662  */
   2663 void
   2664 video_stream_write(struct video_stream *vs,
   2665 		   const struct video_payload *payload)
   2666 {
   2667 	struct video_buffer *vb;
   2668 	struct v4l2_buffer *buf;
   2669 	struct scatter_io sio;
   2670 
   2671 	mutex_enter(&vs->vs_lock);
   2672 
   2673 	/* change of frameno implies end of current frame */
   2674 	if (vs->vs_frameno >= 0 && vs->vs_frameno != payload->frameno)
   2675 		video_stream_sample_done(vs);
   2676 
   2677 	vs->vs_frameno = payload->frameno;
   2678 
   2679 	if (vs->vs_drop || SIMPLEQ_EMPTY(&vs->vs_ingress)) {
   2680 		/* DPRINTF(("video_stream_write: dropping sample %d\n",
   2681 		   vs->vs_sequence)); */
   2682 		vs->vs_drop = true;
   2683 	} else if (payload->size > 0) {
   2684 		vb = SIMPLEQ_FIRST(&vs->vs_ingress);
   2685 		buf = vb->vb_buf;
   2686 		if (!buf->bytesused)
   2687 			v4l2buf_set_timestamp(buf);
   2688 		if (payload->size > buf->length - buf->bytesused) {
   2689 			DPRINTF(("video_stream_write: "
   2690 				 "payload would overflow\n"));
   2691 		} else if (scatter_io_init(&vs->vs_data,
   2692 					   buf->m.offset + buf->bytesused,
   2693 					   payload->size,
   2694 					   &sio))
   2695 		{
   2696 			scatter_io_copyin(&sio, payload->data);
   2697 			buf->bytesused += (payload->size - sio.sio_resid);
   2698 		} else {
   2699 			DPRINTF(("video_stream_write: failed to init scatter io "
   2700 				 "vb=%p buf=%p "
   2701 				 "buf->m.offset=%d buf->bytesused=%u "
   2702 				 "payload->size=%zu\n",
   2703 				 vb, buf,
   2704 				 buf->m.offset, buf->bytesused, payload->size));
   2705 		}
   2706 	}
   2707 
   2708 	/* if the payload marks it, we can do sample_done() early */
   2709 	if (payload->end_of_frame)
   2710 		video_stream_sample_done(vs);
   2711 
   2712 	mutex_exit(&vs->vs_lock);
   2713 }
   2714 
   2715 
   2716 /* Moves the head of the ingress queue to the tail of the egress
   2717  * queue, or resets drop status if we were dropping this sample.
   2718  * Caller should hold the stream queue lock. */
   2719 void
   2720 video_stream_sample_done(struct video_stream *vs)
   2721 {
   2722 	struct video_buffer *vb;
   2723 
   2724 	if (vs->vs_drop) {
   2725 		vs->vs_drop = false;
   2726 	} else if (!SIMPLEQ_EMPTY(&vs->vs_ingress)) {
   2727 		vb = SIMPLEQ_FIRST(&vs->vs_ingress);
   2728 		vb->vb_buf->sequence = vs->vs_sequence;
   2729 		SIMPLEQ_REMOVE_HEAD(&vs->vs_ingress, entries);
   2730 
   2731 		SIMPLEQ_INSERT_TAIL(&vs->vs_egress, vb, entries);
   2732 		cv_signal(&vs->vs_sample_cv);
   2733 		selnotify(&vs->vs_sel, 0, 0);
   2734 	} else {
   2735 		DPRINTF(("video_stream_sample_done: no sample\n"));
   2736 	}
   2737 
   2738 	vs->vs_frameno ^= 1;
   2739 	vs->vs_sequence++;
   2740 }
   2741 
   2742 /* Check if all buffers are queued, i.e. none are under control of
   2743  * userspace. */
   2744 /*
   2745 static bool
   2746 video_stream_all_queued(struct video_stream *vs)
   2747 {
   2748 }
   2749 */
   2750 
   2751 
   2752 static void
   2753 scatter_buf_init(struct scatter_buf *sb)
   2754 {
   2755 	sb->sb_pool = pool_cache_init(PAGE_SIZE, 0, 0, 0,
   2756 				      "video", NULL, IPL_VIDEO,
   2757 				      NULL, NULL, NULL);
   2758 	sb->sb_size = 0;
   2759 	sb->sb_npages = 0;
   2760 	sb->sb_page_ary = NULL;
   2761 }
   2762 
   2763 static void
   2764 scatter_buf_destroy(struct scatter_buf *sb)
   2765 {
   2766 	/* Do we need to return everything to the pool first? */
   2767 	scatter_buf_set_size(sb, 0);
   2768 	pool_cache_destroy(sb->sb_pool);
   2769 	sb->sb_pool = 0;
   2770 	sb->sb_npages = 0;
   2771 	sb->sb_page_ary = NULL;
   2772 }
   2773 
   2774 /* Increase or decrease the size of the buffer */
   2775 static int
   2776 scatter_buf_set_size(struct scatter_buf *sb, size_t sz)
   2777 {
   2778 	int i;
   2779 	size_t npages, minpages, oldnpages;
   2780 	uint8_t **old_ary;
   2781 
   2782 	npages = (sz >> PAGE_SHIFT) + ((sz & PAGE_MASK) > 0);
   2783 
   2784 	if (sb->sb_npages == npages) {
   2785 		return 0;
   2786 	}
   2787 
   2788 	oldnpages = sb->sb_npages;
   2789 	old_ary = sb->sb_page_ary;
   2790 
   2791 	sb->sb_npages = npages;
   2792 	if (npages > 0) {
   2793 		sb->sb_page_ary =
   2794 		    kmem_alloc(sizeof(uint8_t *) * npages, KM_SLEEP);
   2795 	} else {
   2796 		sb->sb_page_ary = NULL;
   2797 	}
   2798 
   2799 	minpages = uimin(npages, oldnpages);
   2800 	/* copy any pages that will be reused */
   2801 	for (i = 0; i < minpages; ++i)
   2802 		sb->sb_page_ary[i] = old_ary[i];
   2803 	/* allocate any new pages */
   2804 	for (; i < npages; ++i)
   2805 		sb->sb_page_ary[i] = pool_cache_get(sb->sb_pool, PR_WAITOK);
   2806 	/* return any pages no longer needed */
   2807 	for (; i < oldnpages; ++i)
   2808 		pool_cache_put(sb->sb_pool, old_ary[i]);
   2809 
   2810 	if (old_ary != NULL)
   2811 		kmem_free(old_ary, sizeof(uint8_t *) * oldnpages);
   2812 
   2813 	sb->sb_size = sb->sb_npages << PAGE_SHIFT;
   2814 
   2815 	return 0;
   2816 }
   2817 
   2818 
   2819 static paddr_t
   2820 scatter_buf_map(struct scatter_buf *sb, off_t off)
   2821 {
   2822 	size_t pg;
   2823 	paddr_t pa;
   2824 
   2825 	pg = off >> PAGE_SHIFT;
   2826 
   2827 	if (pg >= sb->sb_npages)
   2828 		return -1;
   2829 	else if (!pmap_extract(pmap_kernel(), (vaddr_t)sb->sb_page_ary[pg], &pa))
   2830 		return -1;
   2831 
   2832 	return atop(pa);
   2833 }
   2834 
   2835 /* Initialize data for an io operation on a scatter buffer. Returns
   2836  * true if the transfer is valid, or false if out of range. */
   2837 static bool
   2838 scatter_io_init(struct scatter_buf *sb,
   2839 		    off_t off, size_t len,
   2840 		    struct scatter_io *sio)
   2841 {
   2842 	if ((off + len) > sb->sb_size) {
   2843 		DPRINTF(("video: scatter_io_init failed: off=%" PRId64
   2844 			 " len=%zu sb->sb_size=%zu\n",
   2845 			 off, len, sb->sb_size));
   2846 		return false;
   2847 	}
   2848 
   2849 	sio->sio_buf = sb;
   2850 	sio->sio_offset = off;
   2851 	sio->sio_resid = len;
   2852 
   2853 	return true;
   2854 }
   2855 
   2856 /* Store the pointer and size of the next contiguous segment.  Returns
   2857  * true if the segment is valid, or false if all has been transferred.
   2858  * Does not check for overflow. */
   2859 static bool
   2860 scatter_io_next(struct scatter_io *sio, void **p, size_t *sz)
   2861 {
   2862 	size_t pg, pgo;
   2863 
   2864 	if (sio->sio_resid == 0)
   2865 		return false;
   2866 
   2867 	pg = sio->sio_offset >> PAGE_SHIFT;
   2868 	pgo = sio->sio_offset & PAGE_MASK;
   2869 
   2870 	*sz = uimin(PAGE_SIZE - pgo, sio->sio_resid);
   2871 	*p = sio->sio_buf->sb_page_ary[pg] + pgo;
   2872 
   2873 	sio->sio_offset += *sz;
   2874 	sio->sio_resid -= *sz;
   2875 
   2876 	return true;
   2877 }
   2878 
   2879 /* Semi-undo of a failed segment copy.  Updates the scatter_io
   2880  * struct to the previous values prior to a failed segment copy. */
   2881 static void
   2882 scatter_io_undo(struct scatter_io *sio, size_t sz)
   2883 {
   2884 	sio->sio_offset -= sz;
   2885 	sio->sio_resid += sz;
   2886 }
   2887 
   2888 /* Copy data from src into the scatter_buf as described by io. */
   2889 static void
   2890 scatter_io_copyin(struct scatter_io *sio, const void *p)
   2891 {
   2892 	void *dst;
   2893 	const uint8_t *src = p;
   2894 	size_t sz;
   2895 
   2896 	while(scatter_io_next(sio, &dst, &sz)) {
   2897 		memcpy(dst, src, sz);
   2898 		src += sz;
   2899 	}
   2900 }
   2901 
   2902 /* --not used; commented to avoid compiler warnings--
   2903 static void
   2904 scatter_io_copyout(struct scatter_io *sio, void *p)
   2905 {
   2906 	void *src;
   2907 	uint8_t *dst = p;
   2908 	size_t sz;
   2909 
   2910 	while(scatter_io_next(sio, &src, &sz)) {
   2911 		memcpy(dst, src, sz);
   2912 		dst += sz;
   2913 	}
   2914 }
   2915 */
   2916 
   2917 /* Performat a series of uiomove calls on a scatter buf.  Returns
   2918  * EFAULT if uiomove EFAULTs on the first segment.  Otherwise, returns
   2919  * an incomplete transfer but with no error. */
   2920 static int
   2921 scatter_io_uiomove(struct scatter_io *sio, struct uio *uio)
   2922 {
   2923 	void *p;
   2924 	size_t sz;
   2925 	bool first = true;
   2926 	int err;
   2927 
   2928 	while(scatter_io_next(sio, &p, &sz)) {
   2929 		err = uiomove(p, sz, uio);
   2930 		if (err == EFAULT) {
   2931 			scatter_io_undo(sio, sz);
   2932 			if (first)
   2933 				return EFAULT;
   2934 			else
   2935 				return 0;
   2936 		}
   2937 		first = false;
   2938 	}
   2939 
   2940 	return 0;
   2941 }
   2942 
   2943 #endif /* NVIDEO > 0 */
   2944