cx23885-video.c revision 19696f09daeff897a672144be89a16b8df18c004
1/*
2 *  Driver for the Conexant CX23885 PCIe bridge
3 *
4 *  Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
5 *
6 *  This program is free software; you can redistribute it and/or modify
7 *  it under the terms of the GNU General Public License as published by
8 *  the Free Software Foundation; either version 2 of the License, or
9 *  (at your option) any later version.
10 *
11 *  This program is distributed in the hope that it will be useful,
12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 *
15 *  GNU General Public License for more details.
16 *
17 *  You should have received a copy of the GNU General Public License
18 *  along with this program; if not, write to the Free Software
19 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22#include <linux/init.h>
23#include <linux/list.h>
24#include <linux/module.h>
25#include <linux/moduleparam.h>
26#include <linux/kmod.h>
27#include <linux/kernel.h>
28#include <linux/slab.h>
29#include <linux/interrupt.h>
30#include <linux/delay.h>
31#include <linux/kthread.h>
32#include <asm/div64.h>
33
34#include "cx23885.h"
35#include <media/v4l2-common.h>
36#include <media/v4l2-ioctl.h>
37#include "cx23885-ioctl.h"
38#include "tuner-xc2028.h"
39
40#include <media/cx25840.h>
41
42MODULE_DESCRIPTION("v4l2 driver module for cx23885 based TV cards");
43MODULE_AUTHOR("Steven Toth <stoth@linuxtv.org>");
44MODULE_LICENSE("GPL");
45
46/* ------------------------------------------------------------------ */
47
48static unsigned int video_nr[] = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
49static unsigned int vbi_nr[]   = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
50static unsigned int radio_nr[] = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
51
52module_param_array(video_nr, int, NULL, 0444);
53module_param_array(vbi_nr,   int, NULL, 0444);
54module_param_array(radio_nr, int, NULL, 0444);
55
56MODULE_PARM_DESC(video_nr, "video device numbers");
57MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
58MODULE_PARM_DESC(radio_nr, "radio device numbers");
59
60static unsigned int video_debug;
61module_param(video_debug, int, 0644);
62MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
63
64static unsigned int irq_debug;
65module_param(irq_debug, int, 0644);
66MODULE_PARM_DESC(irq_debug, "enable debug messages [IRQ handler]");
67
68static unsigned int vid_limit = 16;
69module_param(vid_limit, int, 0644);
70MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
71
72#define dprintk(level, fmt, arg...)\
73	do { if (video_debug >= level)\
74		printk(KERN_DEBUG "%s: " fmt, dev->name, ## arg);\
75	} while (0)
76
77/* ------------------------------------------------------------------- */
78/* static data                                                         */
79
80#define FORMAT_FLAGS_PACKED       0x01
81#if 0
82static struct cx23885_fmt formats[] = {
83	{
84		.name     = "8 bpp, gray",
85		.fourcc   = V4L2_PIX_FMT_GREY,
86		.depth    = 8,
87		.flags    = FORMAT_FLAGS_PACKED,
88	}, {
89		.name     = "15 bpp RGB, le",
90		.fourcc   = V4L2_PIX_FMT_RGB555,
91		.depth    = 16,
92		.flags    = FORMAT_FLAGS_PACKED,
93	}, {
94		.name     = "15 bpp RGB, be",
95		.fourcc   = V4L2_PIX_FMT_RGB555X,
96		.depth    = 16,
97		.flags    = FORMAT_FLAGS_PACKED,
98	}, {
99		.name     = "16 bpp RGB, le",
100		.fourcc   = V4L2_PIX_FMT_RGB565,
101		.depth    = 16,
102		.flags    = FORMAT_FLAGS_PACKED,
103	}, {
104		.name     = "16 bpp RGB, be",
105		.fourcc   = V4L2_PIX_FMT_RGB565X,
106		.depth    = 16,
107		.flags    = FORMAT_FLAGS_PACKED,
108	}, {
109		.name     = "24 bpp RGB, le",
110		.fourcc   = V4L2_PIX_FMT_BGR24,
111		.depth    = 24,
112		.flags    = FORMAT_FLAGS_PACKED,
113	}, {
114		.name     = "32 bpp RGB, le",
115		.fourcc   = V4L2_PIX_FMT_BGR32,
116		.depth    = 32,
117		.flags    = FORMAT_FLAGS_PACKED,
118	}, {
119		.name     = "32 bpp RGB, be",
120		.fourcc   = V4L2_PIX_FMT_RGB32,
121		.depth    = 32,
122		.flags    = FORMAT_FLAGS_PACKED,
123	}, {
124		.name     = "4:2:2, packed, YUYV",
125		.fourcc   = V4L2_PIX_FMT_YUYV,
126		.depth    = 16,
127		.flags    = FORMAT_FLAGS_PACKED,
128	}, {
129		.name     = "4:2:2, packed, UYVY",
130		.fourcc   = V4L2_PIX_FMT_UYVY,
131		.depth    = 16,
132		.flags    = FORMAT_FLAGS_PACKED,
133	},
134};
135#else
136static struct cx23885_fmt formats[] = {
137	{
138#if 0
139		.name     = "4:2:2, packed, UYVY",
140		.fourcc   = V4L2_PIX_FMT_UYVY,
141		.depth    = 16,
142		.flags    = FORMAT_FLAGS_PACKED,
143	}, {
144#endif
145		.name     = "4:2:2, packed, YUYV",
146		.fourcc   = V4L2_PIX_FMT_YUYV,
147		.depth    = 16,
148		.flags    = FORMAT_FLAGS_PACKED,
149	}
150};
151#endif
152
153static struct cx23885_fmt *format_by_fourcc(unsigned int fourcc)
154{
155	unsigned int i;
156
157	for (i = 0; i < ARRAY_SIZE(formats); i++)
158		if (formats[i].fourcc == fourcc)
159			return formats+i;
160
161	printk(KERN_ERR "%s(%c%c%c%c) NOT FOUND\n", __func__,
162		(fourcc & 0xff),
163		((fourcc >> 8) & 0xff),
164		((fourcc >> 16) & 0xff),
165		((fourcc >> 24) & 0xff)
166		);
167	return NULL;
168}
169
170/* ------------------------------------------------------------------- */
171
172static const struct v4l2_queryctrl no_ctl = {
173	.name  = "42",
174	.flags = V4L2_CTRL_FLAG_DISABLED,
175};
176
177static struct cx23885_ctrl cx23885_ctls[] = {
178	/* --- video --- */
179	{
180		.v = {
181			.id            = V4L2_CID_BRIGHTNESS,
182			.name          = "Brightness",
183			.minimum       = 0x00,
184			.maximum       = 0xff,
185			.step          = 1,
186			.default_value = 0x7f,
187			.type          = V4L2_CTRL_TYPE_INTEGER,
188		},
189		.off                   = 128,
190		.reg                   = LUMA_CTRL,
191		.mask                  = 0x00ff,
192		.shift                 = 0,
193	}, {
194		.v = {
195			.id            = V4L2_CID_CONTRAST,
196			.name          = "Contrast",
197			.minimum       = 0,
198			.maximum       = 0x7f,
199			.step          = 1,
200			.default_value = 0x3f,
201			.type          = V4L2_CTRL_TYPE_INTEGER,
202		},
203		.off                   = 0,
204		.reg                   = LUMA_CTRL,
205		.mask                  = 0xff00,
206		.shift                 = 8,
207	}, {
208		.v = {
209			.id            = V4L2_CID_HUE,
210			.name          = "Hue",
211			.minimum       = -127,
212			.maximum       = 128,
213			.step          = 1,
214			.default_value = 0x0,
215			.type          = V4L2_CTRL_TYPE_INTEGER,
216		},
217		.off                   = 128,
218		.reg                   = CHROMA_CTRL,
219		.mask                  = 0xff0000,
220		.shift                 = 16,
221	}, {
222		/* strictly, this only describes only U saturation.
223		 * V saturation is handled specially through code.
224		 */
225		.v = {
226			.id            = V4L2_CID_SATURATION,
227			.name          = "Saturation",
228			.minimum       = 0,
229			.maximum       = 0x7f,
230			.step          = 1,
231			.default_value = 0x3f,
232			.type          = V4L2_CTRL_TYPE_INTEGER,
233		},
234		.off                   = 0,
235		.reg                   = CHROMA_CTRL,
236		.mask                  = 0x00ff,
237		.shift                 = 0,
238	}, {
239	/* --- audio --- */
240		.v = {
241			.id            = V4L2_CID_AUDIO_MUTE,
242			.name          = "Mute",
243			.minimum       = 0,
244			.maximum       = 1,
245			.default_value = 1,
246			.type          = V4L2_CTRL_TYPE_BOOLEAN,
247		},
248		.reg                   = PATH1_CTL1,
249		.mask                  = (0x1f << 24),
250		.shift                 = 24,
251	}, {
252		.v = {
253			.id            = V4L2_CID_AUDIO_VOLUME,
254			.name          = "Volume",
255			.minimum       = 0,
256			.maximum       = 0x3f,
257			.step          = 1,
258			.default_value = 0x3f,
259			.type          = V4L2_CTRL_TYPE_INTEGER,
260		},
261		.reg                   = PATH1_VOL_CTL,
262		.mask                  = 0xff,
263		.shift                 = 0,
264	}
265};
266static const int CX23885_CTLS = ARRAY_SIZE(cx23885_ctls);
267
268/* Must be sorted from low to high control ID! */
269static const u32 cx23885_user_ctrls[] = {
270	V4L2_CID_USER_CLASS,
271	V4L2_CID_BRIGHTNESS,
272	V4L2_CID_CONTRAST,
273	V4L2_CID_SATURATION,
274	V4L2_CID_HUE,
275	V4L2_CID_AUDIO_VOLUME,
276	V4L2_CID_AUDIO_MUTE,
277	0
278};
279
280static const u32 *ctrl_classes[] = {
281	cx23885_user_ctrls,
282	NULL
283};
284
285void cx23885_video_wakeup(struct cx23885_dev *dev,
286	struct cx23885_dmaqueue *q, u32 count)
287{
288	struct cx23885_buffer *buf;
289	int bc;
290
291	for (bc = 0;; bc++) {
292		if (list_empty(&q->active))
293			break;
294		buf = list_entry(q->active.next,
295				 struct cx23885_buffer, vb.queue);
296
297		/* count comes from the hw and is is 16bit wide --
298		 * this trick handles wrap-arounds correctly for
299		 * up to 32767 buffers in flight... */
300		if ((s16) (count - buf->count) < 0)
301			break;
302
303		do_gettimeofday(&buf->vb.ts);
304		dprintk(2, "[%p/%d] wakeup reg=%d buf=%d\n", buf, buf->vb.i,
305			count, buf->count);
306		buf->vb.state = VIDEOBUF_DONE;
307		list_del(&buf->vb.queue);
308		wake_up(&buf->vb.done);
309	}
310	if (list_empty(&q->active))
311		del_timer(&q->timeout);
312	else
313		mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
314	if (bc != 1)
315		printk(KERN_ERR "%s: %d buffers handled (should be 1)\n",
316			__func__, bc);
317}
318
319static int cx23885_set_tvnorm(struct cx23885_dev *dev, v4l2_std_id norm)
320{
321	dprintk(1, "%s(norm = 0x%08x) name: [%s]\n",
322		__func__,
323		(unsigned int)norm,
324		v4l2_norm_to_name(norm));
325
326	dev->tvnorm = norm;
327
328	call_all(dev, core, s_std, norm);
329
330	return 0;
331}
332
333static struct video_device *cx23885_vdev_init(struct cx23885_dev *dev,
334				    struct pci_dev *pci,
335				    struct video_device *template,
336				    char *type)
337{
338	struct video_device *vfd;
339	dprintk(1, "%s()\n", __func__);
340
341	vfd = video_device_alloc();
342	if (NULL == vfd)
343		return NULL;
344	*vfd = *template;
345	vfd->v4l2_dev = &dev->v4l2_dev;
346	vfd->release = video_device_release;
347	snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)",
348		 dev->name, type, cx23885_boards[dev->board].name);
349	video_set_drvdata(vfd, dev);
350	return vfd;
351}
352
353static int cx23885_ctrl_query(struct v4l2_queryctrl *qctrl)
354{
355	int i;
356
357	if (qctrl->id < V4L2_CID_BASE ||
358	    qctrl->id >= V4L2_CID_LASTP1)
359		return -EINVAL;
360	for (i = 0; i < CX23885_CTLS; i++)
361		if (cx23885_ctls[i].v.id == qctrl->id)
362			break;
363	if (i == CX23885_CTLS) {
364		*qctrl = no_ctl;
365		return 0;
366	}
367	*qctrl = cx23885_ctls[i].v;
368	return 0;
369}
370
371/* ------------------------------------------------------------------- */
372/* resource management                                                 */
373
374static int res_get(struct cx23885_dev *dev, struct cx23885_fh *fh,
375	unsigned int bit)
376{
377	dprintk(1, "%s()\n", __func__);
378	if (fh->resources & bit)
379		/* have it already allocated */
380		return 1;
381
382	/* is it free? */
383	mutex_lock(&dev->lock);
384	if (dev->resources & bit) {
385		/* no, someone else uses it */
386		mutex_unlock(&dev->lock);
387		return 0;
388	}
389	/* it's free, grab it */
390	fh->resources  |= bit;
391	dev->resources |= bit;
392	dprintk(1, "res: get %d\n", bit);
393	mutex_unlock(&dev->lock);
394	return 1;
395}
396
397static int res_check(struct cx23885_fh *fh, unsigned int bit)
398{
399	return fh->resources & bit;
400}
401
402static int res_locked(struct cx23885_dev *dev, unsigned int bit)
403{
404	return dev->resources & bit;
405}
406
407static void res_free(struct cx23885_dev *dev, struct cx23885_fh *fh,
408	unsigned int bits)
409{
410	BUG_ON((fh->resources & bits) != bits);
411	dprintk(1, "%s()\n", __func__);
412
413	mutex_lock(&dev->lock);
414	fh->resources  &= ~bits;
415	dev->resources &= ~bits;
416	dprintk(1, "res: put %d\n", bits);
417	mutex_unlock(&dev->lock);
418}
419
420static int cx23885_flatiron_write(struct cx23885_dev *dev, u8 reg, u8 data)
421{
422	/* 8 bit registers, 8 bit values */
423	u8 buf[] = { reg, data };
424
425	struct i2c_msg msg = { .addr = 0x98 >> 1,
426		.flags = 0, .buf = buf, .len = 2 };
427
428	return i2c_transfer(&dev->i2c_bus[2].i2c_adap, &msg, 1);
429}
430
431static u8 cx23885_flatiron_read(struct cx23885_dev *dev, u8 reg)
432{
433	/* 8 bit registers, 8 bit values */
434	int ret;
435	u8 b0[] = { reg };
436	u8 b1[] = { 0 };
437
438	struct i2c_msg msg[] = {
439		{ .addr = 0x98 >> 1, .flags = 0, .buf = b0, .len = 1 },
440		{ .addr = 0x98 >> 1, .flags = I2C_M_RD, .buf = b1, .len = 1 }
441	};
442
443	ret = i2c_transfer(&dev->i2c_bus[2].i2c_adap, &msg[0], 2);
444	if (ret != 2)
445		printk(KERN_ERR "%s() error\n", __func__);
446
447	return b1[0];
448}
449
450static void cx23885_flatiron_dump(struct cx23885_dev *dev)
451{
452	int i;
453	dprintk(1, "Flatiron dump\n");
454	for (i = 0; i < 0x24; i++) {
455		dprintk(1, "FI[%02x] = %02x\n", i,
456			cx23885_flatiron_read(dev, i));
457	}
458}
459
460static int cx23885_flatiron_mux(struct cx23885_dev *dev, int input)
461{
462	u8 val;
463	dprintk(1, "%s(input = %d)\n", __func__, input);
464
465	if (input == 1)
466		val = cx23885_flatiron_read(dev, CH_PWR_CTRL1) & ~FLD_CH_SEL;
467	else if (input == 2)
468		val = cx23885_flatiron_read(dev, CH_PWR_CTRL1) | FLD_CH_SEL;
469	else
470		return -EINVAL;
471
472	val |= 0x20; /* Enable clock to delta-sigma and dec filter */
473
474	cx23885_flatiron_write(dev, CH_PWR_CTRL1, val);
475
476	/* Wake up */
477	cx23885_flatiron_write(dev, CH_PWR_CTRL2, 0);
478
479	if (video_debug)
480		cx23885_flatiron_dump(dev);
481
482	return 0;
483}
484
485static int cx23885_video_mux(struct cx23885_dev *dev, unsigned int input)
486{
487	dprintk(1, "%s() video_mux: %d [vmux=%d, gpio=0x%x,0x%x,0x%x,0x%x]\n",
488		__func__,
489		input, INPUT(input)->vmux,
490		INPUT(input)->gpio0, INPUT(input)->gpio1,
491		INPUT(input)->gpio2, INPUT(input)->gpio3);
492	dev->input = input;
493
494	if (dev->board == CX23885_BOARD_MYGICA_X8506 ||
495		dev->board == CX23885_BOARD_MAGICPRO_PROHDTVE2) {
496		/* Select Analog TV */
497		if (INPUT(input)->type == CX23885_VMUX_TELEVISION)
498			cx23885_gpio_clear(dev, GPIO_0);
499	}
500
501	/* Tell the internal A/V decoder */
502	v4l2_subdev_call(dev->sd_cx25840, video, s_routing,
503			INPUT(input)->vmux, 0, 0);
504
505	if ((dev->board == CX23885_BOARD_HAUPPAUGE_HVR1800) ||
506		(dev->board == CX23885_BOARD_MPX885)) {
507		/* Configure audio routing */
508		v4l2_subdev_call(dev->sd_cx25840, audio, s_routing,
509			INPUT(input)->amux, 0, 0);
510
511		if (INPUT(input)->amux == CX25840_AUDIO7)
512			cx23885_flatiron_mux(dev, 1);
513		else if (INPUT(input)->amux == CX25840_AUDIO6)
514			cx23885_flatiron_mux(dev, 2);
515	}
516
517	return 0;
518}
519
520static int cx23885_audio_mux(struct cx23885_dev *dev, unsigned int input)
521{
522	dprintk(1, "%s(input=%d)\n", __func__, input);
523
524	/* The baseband video core of the cx23885 has two audio inputs.
525	 * LR1 and LR2. In almost every single case so far only HVR1xxx
526	 * cards we've only ever supported LR1. Time to support LR2,
527	 * which is available via the optional white breakout header on
528	 * the board.
529	 * We'll use a could of existing enums in the card struct to allow
530	 * devs to specify which baseband input they need, or just default
531	 * to what we've always used.
532	 */
533	if (INPUT(input)->amux == CX25840_AUDIO7)
534		cx23885_flatiron_mux(dev, 1);
535	else if (INPUT(input)->amux == CX25840_AUDIO6)
536		cx23885_flatiron_mux(dev, 2);
537	else {
538		/* Not specifically defined, assume the default. */
539		cx23885_flatiron_mux(dev, 1);
540	}
541
542	return 0;
543}
544
545/* ------------------------------------------------------------------ */
546static int cx23885_start_video_dma(struct cx23885_dev *dev,
547			   struct cx23885_dmaqueue *q,
548			   struct cx23885_buffer *buf)
549{
550	dprintk(1, "%s()\n", __func__);
551
552	/* setup fifo + format */
553	cx23885_sram_channel_setup(dev, &dev->sram_channels[SRAM_CH01],
554				buf->bpl, buf->risc.dma);
555
556	/* reset counter */
557	cx_write(VID_A_GPCNT_CTL, 3);
558	q->count = 1;
559
560	/* enable irq */
561	cx23885_irq_add_enable(dev, 0x01);
562	cx_set(VID_A_INT_MSK, 0x000011);
563
564	/* start dma */
565	cx_set(DEV_CNTRL2, (1<<5));
566	cx_set(VID_A_DMA_CTL, 0x11); /* FIFO and RISC enable */
567
568	return 0;
569}
570
571
572static int cx23885_restart_video_queue(struct cx23885_dev *dev,
573			       struct cx23885_dmaqueue *q)
574{
575	struct cx23885_buffer *buf, *prev;
576	struct list_head *item;
577	dprintk(1, "%s()\n", __func__);
578
579	if (!list_empty(&q->active)) {
580		buf = list_entry(q->active.next, struct cx23885_buffer,
581			vb.queue);
582		dprintk(2, "restart_queue [%p/%d]: restart dma\n",
583			buf, buf->vb.i);
584		cx23885_start_video_dma(dev, q, buf);
585		list_for_each(item, &q->active) {
586			buf = list_entry(item, struct cx23885_buffer,
587				vb.queue);
588			buf->count    = q->count++;
589		}
590		mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
591		return 0;
592	}
593
594	prev = NULL;
595	for (;;) {
596		if (list_empty(&q->queued))
597			return 0;
598		buf = list_entry(q->queued.next, struct cx23885_buffer,
599			vb.queue);
600		if (NULL == prev) {
601			list_move_tail(&buf->vb.queue, &q->active);
602			cx23885_start_video_dma(dev, q, buf);
603			buf->vb.state = VIDEOBUF_ACTIVE;
604			buf->count    = q->count++;
605			mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
606			dprintk(2, "[%p/%d] restart_queue - first active\n",
607				buf, buf->vb.i);
608
609		} else if (prev->vb.width  == buf->vb.width  &&
610			   prev->vb.height == buf->vb.height &&
611			   prev->fmt       == buf->fmt) {
612			list_move_tail(&buf->vb.queue, &q->active);
613			buf->vb.state = VIDEOBUF_ACTIVE;
614			buf->count    = q->count++;
615			prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
616			prev->risc.jmp[2] = cpu_to_le32(0); /* Bits 63 - 32 */
617			dprintk(2, "[%p/%d] restart_queue - move to active\n",
618				buf, buf->vb.i);
619		} else {
620			return 0;
621		}
622		prev = buf;
623	}
624}
625
626static int buffer_setup(struct videobuf_queue *q, unsigned int *count,
627	unsigned int *size)
628{
629	struct cx23885_fh *fh = q->priv_data;
630
631	*size = fh->fmt->depth*fh->width*fh->height >> 3;
632	if (0 == *count)
633		*count = 32;
634	if (*size * *count > vid_limit * 1024 * 1024)
635		*count = (vid_limit * 1024 * 1024) / *size;
636	return 0;
637}
638
639static int buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
640	       enum v4l2_field field)
641{
642	struct cx23885_fh *fh  = q->priv_data;
643	struct cx23885_dev *dev = fh->dev;
644	struct cx23885_buffer *buf =
645		container_of(vb, struct cx23885_buffer, vb);
646	int rc, init_buffer = 0;
647	u32 line0_offset, line1_offset;
648	struct videobuf_dmabuf *dma = videobuf_to_dma(&buf->vb);
649
650	BUG_ON(NULL == fh->fmt);
651	if (fh->width  < 48 || fh->width  > norm_maxw(dev->tvnorm) ||
652	    fh->height < 32 || fh->height > norm_maxh(dev->tvnorm))
653		return -EINVAL;
654	buf->vb.size = (fh->width * fh->height * fh->fmt->depth) >> 3;
655	if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
656		return -EINVAL;
657
658	if (buf->fmt       != fh->fmt    ||
659	    buf->vb.width  != fh->width  ||
660	    buf->vb.height != fh->height ||
661	    buf->vb.field  != field) {
662		buf->fmt       = fh->fmt;
663		buf->vb.width  = fh->width;
664		buf->vb.height = fh->height;
665		buf->vb.field  = field;
666		init_buffer = 1;
667	}
668
669	if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
670		init_buffer = 1;
671		rc = videobuf_iolock(q, &buf->vb, NULL);
672		if (0 != rc)
673			goto fail;
674	}
675
676	if (init_buffer) {
677		buf->bpl = buf->vb.width * buf->fmt->depth >> 3;
678		switch (buf->vb.field) {
679		case V4L2_FIELD_TOP:
680			cx23885_risc_buffer(dev->pci, &buf->risc,
681					 dma->sglist, 0, UNSET,
682					 buf->bpl, 0, buf->vb.height);
683			break;
684		case V4L2_FIELD_BOTTOM:
685			cx23885_risc_buffer(dev->pci, &buf->risc,
686					 dma->sglist, UNSET, 0,
687					 buf->bpl, 0, buf->vb.height);
688			break;
689		case V4L2_FIELD_INTERLACED:
690			if (dev->tvnorm & V4L2_STD_NTSC) {
691				/* cx25840 transmits NTSC bottom field first */
692				dprintk(1, "%s() Creating NTSC risc\n",
693					__func__);
694				line0_offset = buf->bpl;
695				line1_offset = 0;
696			} else {
697				/* All other formats are top field first */
698				dprintk(1, "%s() Creating PAL/SECAM risc\n",
699					__func__);
700				line0_offset = 0;
701				line1_offset = buf->bpl;
702			}
703			cx23885_risc_buffer(dev->pci, &buf->risc,
704					dma->sglist, line0_offset,
705					line1_offset,
706					buf->bpl, buf->bpl,
707					buf->vb.height >> 1);
708			break;
709		case V4L2_FIELD_SEQ_TB:
710			cx23885_risc_buffer(dev->pci, &buf->risc,
711					 dma->sglist,
712					 0, buf->bpl * (buf->vb.height >> 1),
713					 buf->bpl, 0,
714					 buf->vb.height >> 1);
715			break;
716		case V4L2_FIELD_SEQ_BT:
717			cx23885_risc_buffer(dev->pci, &buf->risc,
718					 dma->sglist,
719					 buf->bpl * (buf->vb.height >> 1), 0,
720					 buf->bpl, 0,
721					 buf->vb.height >> 1);
722			break;
723		default:
724			BUG();
725		}
726	}
727	dprintk(2, "[%p/%d] buffer_prep - %dx%d %dbpp \"%s\" - dma=0x%08lx\n",
728		buf, buf->vb.i,
729		fh->width, fh->height, fh->fmt->depth, fh->fmt->name,
730		(unsigned long)buf->risc.dma);
731
732	buf->vb.state = VIDEOBUF_PREPARED;
733	return 0;
734
735 fail:
736	cx23885_free_buffer(q, buf);
737	return rc;
738}
739
740static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
741{
742	struct cx23885_buffer   *buf = container_of(vb,
743		struct cx23885_buffer, vb);
744	struct cx23885_buffer   *prev;
745	struct cx23885_fh       *fh   = vq->priv_data;
746	struct cx23885_dev      *dev  = fh->dev;
747	struct cx23885_dmaqueue *q    = &dev->vidq;
748
749	/* add jump to stopper */
750	buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
751	buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma);
752	buf->risc.jmp[2] = cpu_to_le32(0); /* bits 63-32 */
753
754	if (!list_empty(&q->queued)) {
755		list_add_tail(&buf->vb.queue, &q->queued);
756		buf->vb.state = VIDEOBUF_QUEUED;
757		dprintk(2, "[%p/%d] buffer_queue - append to queued\n",
758			buf, buf->vb.i);
759
760	} else if (list_empty(&q->active)) {
761		list_add_tail(&buf->vb.queue, &q->active);
762		cx23885_start_video_dma(dev, q, buf);
763		buf->vb.state = VIDEOBUF_ACTIVE;
764		buf->count    = q->count++;
765		mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
766		dprintk(2, "[%p/%d] buffer_queue - first active\n",
767			buf, buf->vb.i);
768
769	} else {
770		prev = list_entry(q->active.prev, struct cx23885_buffer,
771			vb.queue);
772		if (prev->vb.width  == buf->vb.width  &&
773		    prev->vb.height == buf->vb.height &&
774		    prev->fmt       == buf->fmt) {
775			list_add_tail(&buf->vb.queue, &q->active);
776			buf->vb.state = VIDEOBUF_ACTIVE;
777			buf->count    = q->count++;
778			prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
779			/* 64 bit bits 63-32 */
780			prev->risc.jmp[2] = cpu_to_le32(0);
781			dprintk(2, "[%p/%d] buffer_queue - append to active\n",
782				buf, buf->vb.i);
783
784		} else {
785			list_add_tail(&buf->vb.queue, &q->queued);
786			buf->vb.state = VIDEOBUF_QUEUED;
787			dprintk(2, "[%p/%d] buffer_queue - first queued\n",
788				buf, buf->vb.i);
789		}
790	}
791}
792
793static void buffer_release(struct videobuf_queue *q,
794	struct videobuf_buffer *vb)
795{
796	struct cx23885_buffer *buf = container_of(vb,
797		struct cx23885_buffer, vb);
798
799	cx23885_free_buffer(q, buf);
800}
801
802static struct videobuf_queue_ops cx23885_video_qops = {
803	.buf_setup    = buffer_setup,
804	.buf_prepare  = buffer_prepare,
805	.buf_queue    = buffer_queue,
806	.buf_release  = buffer_release,
807};
808
809static struct videobuf_queue *get_queue(struct cx23885_fh *fh)
810{
811	switch (fh->type) {
812	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
813		return &fh->vidq;
814	case V4L2_BUF_TYPE_VBI_CAPTURE:
815		return &fh->vbiq;
816	default:
817		BUG();
818		return NULL;
819	}
820}
821
822static int get_resource(struct cx23885_fh *fh)
823{
824	switch (fh->type) {
825	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
826		return RESOURCE_VIDEO;
827	case V4L2_BUF_TYPE_VBI_CAPTURE:
828		return RESOURCE_VBI;
829	default:
830		BUG();
831		return 0;
832	}
833}
834
835static int video_open(struct file *file)
836{
837	struct video_device *vdev = video_devdata(file);
838	struct cx23885_dev *dev = video_drvdata(file);
839	struct cx23885_fh *fh;
840	enum v4l2_buf_type type = 0;
841	int radio = 0;
842
843	switch (vdev->vfl_type) {
844	case VFL_TYPE_GRABBER:
845		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
846		break;
847	case VFL_TYPE_VBI:
848		type = V4L2_BUF_TYPE_VBI_CAPTURE;
849		break;
850	case VFL_TYPE_RADIO:
851		radio = 1;
852		break;
853	}
854
855	dprintk(1, "open dev=%s radio=%d type=%s\n",
856		video_device_node_name(vdev), radio, v4l2_type_names[type]);
857
858	/* allocate + initialize per filehandle data */
859	fh = kzalloc(sizeof(*fh), GFP_KERNEL);
860	if (NULL == fh)
861		return -ENOMEM;
862
863	file->private_data = fh;
864	fh->dev      = dev;
865	fh->radio    = radio;
866	fh->type     = type;
867	fh->width    = 320;
868	fh->height   = 240;
869	fh->fmt      = format_by_fourcc(V4L2_PIX_FMT_YUYV);
870
871	videobuf_queue_sg_init(&fh->vidq, &cx23885_video_qops,
872			    &dev->pci->dev, &dev->slock,
873			    V4L2_BUF_TYPE_VIDEO_CAPTURE,
874			    V4L2_FIELD_INTERLACED,
875			    sizeof(struct cx23885_buffer),
876			    fh, NULL);
877
878	videobuf_queue_sg_init(&fh->vbiq, &cx23885_vbi_qops,
879		&dev->pci->dev, &dev->slock,
880		V4L2_BUF_TYPE_VBI_CAPTURE,
881		V4L2_FIELD_SEQ_TB,
882		sizeof(struct cx23885_buffer),
883		fh, NULL);
884
885
886	dprintk(1, "post videobuf_queue_init()\n");
887
888	return 0;
889}
890
891static ssize_t video_read(struct file *file, char __user *data,
892	size_t count, loff_t *ppos)
893{
894	struct cx23885_fh *fh = file->private_data;
895
896	switch (fh->type) {
897	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
898		if (res_locked(fh->dev, RESOURCE_VIDEO))
899			return -EBUSY;
900		return videobuf_read_one(&fh->vidq, data, count, ppos,
901					 file->f_flags & O_NONBLOCK);
902	case V4L2_BUF_TYPE_VBI_CAPTURE:
903		if (!res_get(fh->dev, fh, RESOURCE_VBI))
904			return -EBUSY;
905		return videobuf_read_stream(&fh->vbiq, data, count, ppos, 1,
906					    file->f_flags & O_NONBLOCK);
907	default:
908		BUG();
909		return 0;
910	}
911}
912
913static unsigned int video_poll(struct file *file,
914	struct poll_table_struct *wait)
915{
916	struct cx23885_fh *fh = file->private_data;
917	struct cx23885_buffer *buf;
918	unsigned int rc = POLLERR;
919
920	if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
921		if (!res_get(fh->dev, fh, RESOURCE_VBI))
922			return POLLERR;
923		return videobuf_poll_stream(file, &fh->vbiq, wait);
924	}
925
926	mutex_lock(&fh->vidq.vb_lock);
927	if (res_check(fh, RESOURCE_VIDEO)) {
928		/* streaming capture */
929		if (list_empty(&fh->vidq.stream))
930			goto done;
931		buf = list_entry(fh->vidq.stream.next,
932			struct cx23885_buffer, vb.stream);
933	} else {
934		/* read() capture */
935		buf = (struct cx23885_buffer *)fh->vidq.read_buf;
936		if (NULL == buf)
937			goto done;
938	}
939	poll_wait(file, &buf->vb.done, wait);
940	if (buf->vb.state == VIDEOBUF_DONE ||
941	    buf->vb.state == VIDEOBUF_ERROR)
942		rc =  POLLIN|POLLRDNORM;
943	else
944		rc = 0;
945done:
946	mutex_unlock(&fh->vidq.vb_lock);
947	return rc;
948}
949
950static int video_release(struct file *file)
951{
952	struct cx23885_fh *fh = file->private_data;
953	struct cx23885_dev *dev = fh->dev;
954
955	/* turn off overlay */
956	if (res_check(fh, RESOURCE_OVERLAY)) {
957		/* FIXME */
958		res_free(dev, fh, RESOURCE_OVERLAY);
959	}
960
961	/* stop video capture */
962	if (res_check(fh, RESOURCE_VIDEO)) {
963		videobuf_queue_cancel(&fh->vidq);
964		res_free(dev, fh, RESOURCE_VIDEO);
965	}
966	if (fh->vidq.read_buf) {
967		buffer_release(&fh->vidq, fh->vidq.read_buf);
968		kfree(fh->vidq.read_buf);
969	}
970
971	/* stop vbi capture */
972	if (res_check(fh, RESOURCE_VBI)) {
973		if (fh->vbiq.streaming)
974			videobuf_streamoff(&fh->vbiq);
975		if (fh->vbiq.reading)
976			videobuf_read_stop(&fh->vbiq);
977		res_free(dev, fh, RESOURCE_VBI);
978	}
979
980	videobuf_mmap_free(&fh->vidq);
981	file->private_data = NULL;
982	kfree(fh);
983
984	/* We are not putting the tuner to sleep here on exit, because
985	 * we want to use the mpeg encoder in another session to capture
986	 * tuner video. Closing this will result in no video to the encoder.
987	 */
988
989	return 0;
990}
991
992static int video_mmap(struct file *file, struct vm_area_struct *vma)
993{
994	struct cx23885_fh *fh = file->private_data;
995
996	return videobuf_mmap_mapper(get_queue(fh), vma);
997}
998
999/* ------------------------------------------------------------------ */
1000/* VIDEO CTRL IOCTLS                                                  */
1001
1002static int cx23885_get_control(struct cx23885_dev *dev,
1003	struct v4l2_control *ctl)
1004{
1005	dprintk(1, "%s() calling cx25840(VIDIOC_G_CTRL)\n", __func__);
1006	call_all(dev, core, g_ctrl, ctl);
1007	return 0;
1008}
1009
1010static int cx23885_set_control(struct cx23885_dev *dev,
1011	struct v4l2_control *ctl)
1012{
1013	dprintk(1, "%s() calling cx25840(VIDIOC_S_CTRL)\n", __func__);
1014	call_all(dev, core, s_ctrl, ctl);
1015
1016	return 0;
1017}
1018
1019static void init_controls(struct cx23885_dev *dev)
1020{
1021	struct v4l2_control ctrl;
1022	int i;
1023
1024	for (i = 0; i < CX23885_CTLS; i++) {
1025		ctrl.id = cx23885_ctls[i].v.id;
1026		ctrl.value = cx23885_ctls[i].v.default_value;
1027
1028		cx23885_set_control(dev, &ctrl);
1029	}
1030}
1031
1032/* ------------------------------------------------------------------ */
1033/* VIDEO IOCTLS                                                       */
1034
1035static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1036	struct v4l2_format *f)
1037{
1038	struct cx23885_fh *fh   = priv;
1039
1040	f->fmt.pix.width        = fh->width;
1041	f->fmt.pix.height       = fh->height;
1042	f->fmt.pix.field        = fh->vidq.field;
1043	f->fmt.pix.pixelformat  = fh->fmt->fourcc;
1044	f->fmt.pix.bytesperline =
1045		(f->fmt.pix.width * fh->fmt->depth) >> 3;
1046	f->fmt.pix.sizeimage =
1047		f->fmt.pix.height * f->fmt.pix.bytesperline;
1048
1049	return 0;
1050}
1051
1052static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1053	struct v4l2_format *f)
1054{
1055	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1056	struct cx23885_fmt *fmt;
1057	enum v4l2_field   field;
1058	unsigned int      maxw, maxh;
1059
1060	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1061	if (NULL == fmt)
1062		return -EINVAL;
1063
1064	field = f->fmt.pix.field;
1065	maxw  = norm_maxw(dev->tvnorm);
1066	maxh  = norm_maxh(dev->tvnorm);
1067
1068	if (V4L2_FIELD_ANY == field) {
1069		field = (f->fmt.pix.height > maxh/2)
1070			? V4L2_FIELD_INTERLACED
1071			: V4L2_FIELD_BOTTOM;
1072	}
1073
1074	switch (field) {
1075	case V4L2_FIELD_TOP:
1076	case V4L2_FIELD_BOTTOM:
1077		maxh = maxh / 2;
1078		break;
1079	case V4L2_FIELD_INTERLACED:
1080		break;
1081	default:
1082		return -EINVAL;
1083	}
1084
1085	f->fmt.pix.field = field;
1086	v4l_bound_align_image(&f->fmt.pix.width, 48, maxw, 2,
1087			      &f->fmt.pix.height, 32, maxh, 0, 0);
1088	f->fmt.pix.bytesperline =
1089		(f->fmt.pix.width * fmt->depth) >> 3;
1090	f->fmt.pix.sizeimage =
1091		f->fmt.pix.height * f->fmt.pix.bytesperline;
1092
1093	return 0;
1094}
1095
1096static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1097	struct v4l2_format *f)
1098{
1099	struct cx23885_fh *fh = priv;
1100	struct cx23885_dev *dev  = ((struct cx23885_fh *)priv)->dev;
1101	struct v4l2_mbus_framefmt mbus_fmt;
1102	int err;
1103
1104	dprintk(2, "%s()\n", __func__);
1105	err = vidioc_try_fmt_vid_cap(file, priv, f);
1106
1107	if (0 != err)
1108		return err;
1109	fh->fmt        = format_by_fourcc(f->fmt.pix.pixelformat);
1110	fh->width      = f->fmt.pix.width;
1111	fh->height     = f->fmt.pix.height;
1112	fh->vidq.field = f->fmt.pix.field;
1113	dprintk(2, "%s() width=%d height=%d field=%d\n", __func__,
1114		fh->width, fh->height, fh->vidq.field);
1115	v4l2_fill_mbus_format(&mbus_fmt, &f->fmt.pix, V4L2_MBUS_FMT_FIXED);
1116	call_all(dev, video, s_mbus_fmt, &mbus_fmt);
1117	v4l2_fill_pix_format(&f->fmt.pix, &mbus_fmt);
1118	return 0;
1119}
1120
1121static int vidioc_querycap(struct file *file, void  *priv,
1122	struct v4l2_capability *cap)
1123{
1124	struct cx23885_dev *dev  = ((struct cx23885_fh *)priv)->dev;
1125
1126	strcpy(cap->driver, "cx23885");
1127	strlcpy(cap->card, cx23885_boards[dev->board].name,
1128		sizeof(cap->card));
1129	sprintf(cap->bus_info, "PCIe:%s", pci_name(dev->pci));
1130	cap->capabilities =
1131		V4L2_CAP_VIDEO_CAPTURE |
1132		V4L2_CAP_READWRITE     |
1133		V4L2_CAP_STREAMING     |
1134		V4L2_CAP_VBI_CAPTURE;
1135	if (UNSET != dev->tuner_type)
1136		cap->capabilities |= V4L2_CAP_TUNER;
1137	return 0;
1138}
1139
1140static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1141	struct v4l2_fmtdesc *f)
1142{
1143	if (unlikely(f->index >= ARRAY_SIZE(formats)))
1144		return -EINVAL;
1145
1146	strlcpy(f->description, formats[f->index].name,
1147		sizeof(f->description));
1148	f->pixelformat = formats[f->index].fourcc;
1149
1150	return 0;
1151}
1152
1153static int vidioc_reqbufs(struct file *file, void *priv,
1154	struct v4l2_requestbuffers *p)
1155{
1156	struct cx23885_fh *fh = priv;
1157	return videobuf_reqbufs(get_queue(fh), p);
1158}
1159
1160static int vidioc_querybuf(struct file *file, void *priv,
1161	struct v4l2_buffer *p)
1162{
1163	struct cx23885_fh *fh = priv;
1164	return videobuf_querybuf(get_queue(fh), p);
1165}
1166
1167static int vidioc_qbuf(struct file *file, void *priv,
1168	struct v4l2_buffer *p)
1169{
1170	struct cx23885_fh *fh = priv;
1171	return videobuf_qbuf(get_queue(fh), p);
1172}
1173
1174static int vidioc_dqbuf(struct file *file, void *priv,
1175	struct v4l2_buffer *p)
1176{
1177	struct cx23885_fh *fh = priv;
1178	return videobuf_dqbuf(get_queue(fh), p,
1179				file->f_flags & O_NONBLOCK);
1180}
1181
1182static int vidioc_streamon(struct file *file, void *priv,
1183	enum v4l2_buf_type i)
1184{
1185	struct cx23885_fh *fh = priv;
1186	struct cx23885_dev *dev = fh->dev;
1187	dprintk(1, "%s()\n", __func__);
1188
1189	if ((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
1190		(fh->type != V4L2_BUF_TYPE_VBI_CAPTURE))
1191		return -EINVAL;
1192	if (unlikely(i != fh->type))
1193		return -EINVAL;
1194
1195	if (unlikely(!res_get(dev, fh, get_resource(fh))))
1196		return -EBUSY;
1197
1198	/* Don't start VBI streaming unless vida streaming
1199	 * has already started.
1200	 */
1201	if ((fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) &&
1202		((cx_read(VID_A_DMA_CTL) & 0x11) == 0))
1203		return -EINVAL;
1204
1205	return videobuf_streamon(get_queue(fh));
1206}
1207
1208static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1209{
1210	struct cx23885_fh *fh = priv;
1211	struct cx23885_dev *dev = fh->dev;
1212	int err, res;
1213	dprintk(1, "%s()\n", __func__);
1214
1215	if ((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
1216		(fh->type != V4L2_BUF_TYPE_VBI_CAPTURE))
1217		return -EINVAL;
1218	if (i != fh->type)
1219		return -EINVAL;
1220
1221	res = get_resource(fh);
1222	err = videobuf_streamoff(get_queue(fh));
1223	if (err < 0)
1224		return err;
1225	res_free(dev, fh, res);
1226	return 0;
1227}
1228
1229static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *tvnorms)
1230{
1231	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1232	dprintk(1, "%s()\n", __func__);
1233
1234	mutex_lock(&dev->lock);
1235	cx23885_set_tvnorm(dev, *tvnorms);
1236	mutex_unlock(&dev->lock);
1237
1238	return 0;
1239}
1240
1241static int cx23885_enum_input(struct cx23885_dev *dev, struct v4l2_input *i)
1242{
1243	static const char *iname[] = {
1244		[CX23885_VMUX_COMPOSITE1] = "Composite1",
1245		[CX23885_VMUX_COMPOSITE2] = "Composite2",
1246		[CX23885_VMUX_COMPOSITE3] = "Composite3",
1247		[CX23885_VMUX_COMPOSITE4] = "Composite4",
1248		[CX23885_VMUX_SVIDEO]     = "S-Video",
1249		[CX23885_VMUX_COMPONENT]  = "Component",
1250		[CX23885_VMUX_TELEVISION] = "Television",
1251		[CX23885_VMUX_CABLE]      = "Cable TV",
1252		[CX23885_VMUX_DVB]        = "DVB",
1253		[CX23885_VMUX_DEBUG]      = "for debug only",
1254	};
1255	unsigned int n;
1256	dprintk(1, "%s()\n", __func__);
1257
1258	n = i->index;
1259	if (n >= MAX_CX23885_INPUT)
1260		return -EINVAL;
1261
1262	if (0 == INPUT(n)->type)
1263		return -EINVAL;
1264
1265	i->index = n;
1266	i->type  = V4L2_INPUT_TYPE_CAMERA;
1267	strcpy(i->name, iname[INPUT(n)->type]);
1268	if ((CX23885_VMUX_TELEVISION == INPUT(n)->type) ||
1269		(CX23885_VMUX_CABLE == INPUT(n)->type)) {
1270		i->type = V4L2_INPUT_TYPE_TUNER;
1271		i->std = CX23885_NORMS;
1272	}
1273
1274	/* Two selectable audio inputs for non-tv inputs */
1275	if (INPUT(n)->type != CX23885_VMUX_TELEVISION)
1276		i->audioset = 0x3;
1277
1278	return 0;
1279}
1280
1281static int vidioc_enum_input(struct file *file, void *priv,
1282				struct v4l2_input *i)
1283{
1284	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1285	dprintk(1, "%s()\n", __func__);
1286	return cx23885_enum_input(dev, i);
1287}
1288
1289static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1290{
1291	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1292
1293	*i = dev->input;
1294	dprintk(1, "%s() returns %d\n", __func__, *i);
1295	return 0;
1296}
1297
1298static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1299{
1300	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1301
1302	dprintk(1, "%s(%d)\n", __func__, i);
1303
1304	if (i >= MAX_CX23885_INPUT) {
1305		dprintk(1, "%s() -EINVAL\n", __func__);
1306		return -EINVAL;
1307	}
1308
1309	if (INPUT(i)->type == 0)
1310		return -EINVAL;
1311
1312	mutex_lock(&dev->lock);
1313	cx23885_video_mux(dev, i);
1314
1315	/* By default establish the default audio input for the card also */
1316	/* Caller is free to use VIDIOC_S_AUDIO to override afterwards */
1317	cx23885_audio_mux(dev, i);
1318	mutex_unlock(&dev->lock);
1319	return 0;
1320}
1321
1322static int vidioc_log_status(struct file *file, void *priv)
1323{
1324	struct cx23885_fh  *fh  = priv;
1325	struct cx23885_dev *dev = fh->dev;
1326
1327	printk(KERN_INFO
1328		"%s/0: ============  START LOG STATUS  ============\n",
1329	       dev->name);
1330	call_all(dev, core, log_status);
1331	printk(KERN_INFO
1332		"%s/0: =============  END LOG STATUS  =============\n",
1333	       dev->name);
1334	return 0;
1335}
1336
1337static int cx23885_query_audinput(struct file *file, void *priv,
1338	struct v4l2_audio *i)
1339{
1340	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1341	static const char *iname[] = {
1342		[0] = "Baseband L/R 1",
1343		[1] = "Baseband L/R 2",
1344	};
1345	unsigned int n;
1346	dprintk(1, "%s()\n", __func__);
1347
1348	n = i->index;
1349	if (n >= 2)
1350		return -EINVAL;
1351
1352	memset(i, 0, sizeof(*i));
1353	i->index = n;
1354	strcpy(i->name, iname[n]);
1355	i->capability  = V4L2_AUDCAP_STEREO;
1356	i->mode  = V4L2_AUDMODE_AVL;
1357	return 0;
1358
1359}
1360
1361static int vidioc_enum_audinput(struct file *file, void *priv,
1362				struct v4l2_audio *i)
1363{
1364	return cx23885_query_audinput(file, priv, i);
1365}
1366
1367static int vidioc_g_audinput(struct file *file, void *priv,
1368	struct v4l2_audio *i)
1369{
1370	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1371
1372	i->index = dev->audinput;
1373	dprintk(1, "%s(input=%d)\n", __func__, i->index);
1374
1375	return cx23885_query_audinput(file, priv, i);
1376}
1377
1378static int vidioc_s_audinput(struct file *file, void *priv,
1379	struct v4l2_audio *i)
1380{
1381	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1382	if (i->index >= 2)
1383		return -EINVAL;
1384
1385	dprintk(1, "%s(%d)\n", __func__, i->index);
1386
1387	dev->audinput = i->index;
1388
1389	/* Skip the audio defaults from the cards struct, caller wants
1390	 * directly touch the audio mux hardware. */
1391	cx23885_flatiron_mux(dev, dev->audinput + 1);
1392	return 0;
1393}
1394
1395static int vidioc_queryctrl(struct file *file, void *priv,
1396				struct v4l2_queryctrl *qctrl)
1397{
1398	qctrl->id = v4l2_ctrl_next(ctrl_classes, qctrl->id);
1399	if (unlikely(qctrl->id == 0))
1400		return -EINVAL;
1401	return cx23885_ctrl_query(qctrl);
1402}
1403
1404static int vidioc_g_ctrl(struct file *file, void *priv,
1405				struct v4l2_control *ctl)
1406{
1407	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1408
1409	return cx23885_get_control(dev, ctl);
1410}
1411
1412static int vidioc_s_ctrl(struct file *file, void *priv,
1413				struct v4l2_control *ctl)
1414{
1415	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1416
1417	return cx23885_set_control(dev, ctl);
1418}
1419
1420static int vidioc_g_tuner(struct file *file, void *priv,
1421				struct v4l2_tuner *t)
1422{
1423	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1424
1425	if (unlikely(UNSET == dev->tuner_type))
1426		return -EINVAL;
1427	if (0 != t->index)
1428		return -EINVAL;
1429
1430	strcpy(t->name, "Television");
1431
1432	call_all(dev, tuner, g_tuner, t);
1433	return 0;
1434}
1435
1436static int vidioc_s_tuner(struct file *file, void *priv,
1437				struct v4l2_tuner *t)
1438{
1439	struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
1440
1441	if (UNSET == dev->tuner_type)
1442		return -EINVAL;
1443	if (0 != t->index)
1444		return -EINVAL;
1445	/* Update the A/V core */
1446	call_all(dev, tuner, s_tuner, t);
1447
1448	return 0;
1449}
1450
1451static int vidioc_g_frequency(struct file *file, void *priv,
1452				struct v4l2_frequency *f)
1453{
1454	struct cx23885_fh *fh = priv;
1455	struct cx23885_dev *dev = fh->dev;
1456
1457	if (unlikely(UNSET == dev->tuner_type))
1458		return -EINVAL;
1459
1460	/* f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; */
1461	f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
1462	f->frequency = dev->freq;
1463
1464	call_all(dev, tuner, g_frequency, f);
1465
1466	return 0;
1467}
1468
1469static int cx23885_set_freq(struct cx23885_dev *dev, struct v4l2_frequency *f)
1470{
1471	if (unlikely(UNSET == dev->tuner_type))
1472		return -EINVAL;
1473	if (unlikely(f->tuner != 0))
1474		return -EINVAL;
1475
1476	mutex_lock(&dev->lock);
1477	dev->freq = f->frequency;
1478
1479	call_all(dev, tuner, s_frequency, f);
1480
1481	/* When changing channels it is required to reset TVAUDIO */
1482	msleep(10);
1483
1484	mutex_unlock(&dev->lock);
1485
1486	return 0;
1487}
1488
1489static int vidioc_s_frequency(struct file *file, void *priv,
1490				struct v4l2_frequency *f)
1491{
1492	struct cx23885_fh *fh = priv;
1493	struct cx23885_dev *dev = fh->dev;
1494
1495	if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
1496		return -EINVAL;
1497	if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
1498		return -EINVAL;
1499
1500	return
1501		cx23885_set_freq(dev, f);
1502}
1503
1504/* ----------------------------------------------------------- */
1505
1506static void cx23885_vid_timeout(unsigned long data)
1507{
1508	struct cx23885_dev *dev = (struct cx23885_dev *)data;
1509	struct cx23885_dmaqueue *q = &dev->vidq;
1510	struct cx23885_buffer *buf;
1511	unsigned long flags;
1512
1513	spin_lock_irqsave(&dev->slock, flags);
1514	while (!list_empty(&q->active)) {
1515		buf = list_entry(q->active.next,
1516			struct cx23885_buffer, vb.queue);
1517		list_del(&buf->vb.queue);
1518		buf->vb.state = VIDEOBUF_ERROR;
1519		wake_up(&buf->vb.done);
1520		printk(KERN_ERR "%s: [%p/%d] timeout - dma=0x%08lx\n",
1521			dev->name, buf, buf->vb.i,
1522			(unsigned long)buf->risc.dma);
1523	}
1524	cx23885_restart_video_queue(dev, q);
1525	spin_unlock_irqrestore(&dev->slock, flags);
1526}
1527
1528int cx23885_video_irq(struct cx23885_dev *dev, u32 status)
1529{
1530	u32 mask, count;
1531	int handled = 0;
1532
1533	mask   = cx_read(VID_A_INT_MSK);
1534	if (0 == (status & mask))
1535		return handled;
1536
1537	cx_write(VID_A_INT_STAT, status);
1538
1539	/* risc op code error, fifo overflow or line sync detection error */
1540	if ((status & VID_BC_MSK_OPC_ERR) ||
1541		(status & VID_BC_MSK_SYNC) ||
1542		(status & VID_BC_MSK_OF)) {
1543
1544		if (status & VID_BC_MSK_OPC_ERR) {
1545			dprintk(7, " (VID_BC_MSK_OPC_ERR 0x%08x)\n",
1546				VID_BC_MSK_OPC_ERR);
1547			printk(KERN_WARNING "%s: video risc op code error\n",
1548				dev->name);
1549			cx23885_sram_channel_dump(dev,
1550				&dev->sram_channels[SRAM_CH01]);
1551		}
1552
1553		if (status & VID_BC_MSK_SYNC)
1554			dprintk(7, " (VID_BC_MSK_SYNC 0x%08x) "
1555				"video lines miss-match\n",
1556				VID_BC_MSK_SYNC);
1557
1558		if (status & VID_BC_MSK_OF)
1559			dprintk(7, " (VID_BC_MSK_OF 0x%08x) fifo overflow\n",
1560				VID_BC_MSK_OF);
1561
1562	}
1563
1564	/* Video */
1565	if (status & VID_BC_MSK_RISCI1) {
1566		spin_lock(&dev->slock);
1567		count = cx_read(VID_A_GPCNT);
1568		cx23885_video_wakeup(dev, &dev->vidq, count);
1569		spin_unlock(&dev->slock);
1570		handled++;
1571	}
1572	if (status & VID_BC_MSK_RISCI2) {
1573		dprintk(2, "stopper video\n");
1574		spin_lock(&dev->slock);
1575		cx23885_restart_video_queue(dev, &dev->vidq);
1576		spin_unlock(&dev->slock);
1577		handled++;
1578	}
1579
1580	/* Allow the VBI framework to process it's payload */
1581	handled += cx23885_vbi_irq(dev, status);
1582
1583	return handled;
1584}
1585
1586/* ----------------------------------------------------------- */
1587/* exported stuff                                              */
1588
1589static const struct v4l2_file_operations video_fops = {
1590	.owner	       = THIS_MODULE,
1591	.open	       = video_open,
1592	.release       = video_release,
1593	.read	       = video_read,
1594	.poll          = video_poll,
1595	.mmap	       = video_mmap,
1596	.ioctl	       = video_ioctl2,
1597};
1598
1599static const struct v4l2_ioctl_ops video_ioctl_ops = {
1600	.vidioc_querycap      = vidioc_querycap,
1601	.vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
1602	.vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
1603	.vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
1604	.vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
1605	.vidioc_g_fmt_vbi_cap     = cx23885_vbi_fmt,
1606	.vidioc_try_fmt_vbi_cap   = cx23885_vbi_fmt,
1607	.vidioc_s_fmt_vbi_cap     = cx23885_vbi_fmt,
1608	.vidioc_reqbufs       = vidioc_reqbufs,
1609	.vidioc_querybuf      = vidioc_querybuf,
1610	.vidioc_qbuf          = vidioc_qbuf,
1611	.vidioc_dqbuf         = vidioc_dqbuf,
1612	.vidioc_s_std         = vidioc_s_std,
1613	.vidioc_enum_input    = vidioc_enum_input,
1614	.vidioc_g_input       = vidioc_g_input,
1615	.vidioc_s_input       = vidioc_s_input,
1616	.vidioc_log_status    = vidioc_log_status,
1617	.vidioc_queryctrl     = vidioc_queryctrl,
1618	.vidioc_g_ctrl        = vidioc_g_ctrl,
1619	.vidioc_s_ctrl        = vidioc_s_ctrl,
1620	.vidioc_streamon      = vidioc_streamon,
1621	.vidioc_streamoff     = vidioc_streamoff,
1622	.vidioc_g_tuner       = vidioc_g_tuner,
1623	.vidioc_s_tuner       = vidioc_s_tuner,
1624	.vidioc_g_frequency   = vidioc_g_frequency,
1625	.vidioc_s_frequency   = vidioc_s_frequency,
1626	.vidioc_g_chip_ident  = cx23885_g_chip_ident,
1627#ifdef CONFIG_VIDEO_ADV_DEBUG
1628	.vidioc_g_register    = cx23885_g_register,
1629	.vidioc_s_register    = cx23885_s_register,
1630#endif
1631	.vidioc_enumaudio     = vidioc_enum_audinput,
1632	.vidioc_g_audio       = vidioc_g_audinput,
1633	.vidioc_s_audio       = vidioc_s_audinput,
1634};
1635
1636static struct video_device cx23885_vbi_template;
1637static struct video_device cx23885_video_template = {
1638	.name                 = "cx23885-video",
1639	.fops                 = &video_fops,
1640	.ioctl_ops 	      = &video_ioctl_ops,
1641	.tvnorms              = CX23885_NORMS,
1642	.current_norm         = V4L2_STD_NTSC_M,
1643};
1644
1645static const struct v4l2_file_operations radio_fops = {
1646	.owner         = THIS_MODULE,
1647	.open          = video_open,
1648	.release       = video_release,
1649	.ioctl         = video_ioctl2,
1650};
1651
1652
1653void cx23885_video_unregister(struct cx23885_dev *dev)
1654{
1655	dprintk(1, "%s()\n", __func__);
1656	cx23885_irq_remove(dev, 0x01);
1657
1658	if (dev->vbi_dev) {
1659		if (video_is_registered(dev->vbi_dev))
1660			video_unregister_device(dev->vbi_dev);
1661		else
1662			video_device_release(dev->vbi_dev);
1663		dev->vbi_dev = NULL;
1664		btcx_riscmem_free(dev->pci, &dev->vbiq.stopper);
1665	}
1666	if (dev->video_dev) {
1667		if (video_is_registered(dev->video_dev))
1668			video_unregister_device(dev->video_dev);
1669		else
1670			video_device_release(dev->video_dev);
1671		dev->video_dev = NULL;
1672
1673		btcx_riscmem_free(dev->pci, &dev->vidq.stopper);
1674	}
1675
1676	if (dev->audio_dev)
1677		cx23885_audio_unregister(dev);
1678}
1679
1680int cx23885_video_register(struct cx23885_dev *dev)
1681{
1682	int err;
1683
1684	dprintk(1, "%s()\n", __func__);
1685	spin_lock_init(&dev->slock);
1686
1687	/* Initialize VBI template */
1688	memcpy(&cx23885_vbi_template, &cx23885_video_template,
1689		sizeof(cx23885_vbi_template));
1690	strcpy(cx23885_vbi_template.name, "cx23885-vbi");
1691
1692	dev->tvnorm = cx23885_video_template.current_norm;
1693
1694	/* init video dma queues */
1695	INIT_LIST_HEAD(&dev->vidq.active);
1696	INIT_LIST_HEAD(&dev->vidq.queued);
1697	dev->vidq.timeout.function = cx23885_vid_timeout;
1698	dev->vidq.timeout.data = (unsigned long)dev;
1699	init_timer(&dev->vidq.timeout);
1700	cx23885_risc_stopper(dev->pci, &dev->vidq.stopper,
1701		VID_A_DMA_CTL, 0x11, 0x00);
1702
1703	/* init vbi dma queues */
1704	INIT_LIST_HEAD(&dev->vbiq.active);
1705	INIT_LIST_HEAD(&dev->vbiq.queued);
1706	dev->vbiq.timeout.function = cx23885_vbi_timeout;
1707	dev->vbiq.timeout.data = (unsigned long)dev;
1708	init_timer(&dev->vbiq.timeout);
1709	cx23885_risc_stopper(dev->pci, &dev->vbiq.stopper,
1710		VID_A_DMA_CTL, 0x22, 0x00);
1711
1712	cx23885_irq_add_enable(dev, 0x01);
1713
1714	if ((TUNER_ABSENT != dev->tuner_type) &&
1715			((dev->tuner_bus == 0) || (dev->tuner_bus == 1))) {
1716		struct v4l2_subdev *sd = NULL;
1717
1718		if (dev->tuner_addr)
1719			sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
1720				&dev->i2c_bus[dev->tuner_bus].i2c_adap,
1721				"tuner", dev->tuner_addr, NULL);
1722		else
1723			sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
1724				&dev->i2c_bus[dev->tuner_bus].i2c_adap,
1725				"tuner", 0, v4l2_i2c_tuner_addrs(ADDRS_TV));
1726		if (sd) {
1727			struct tuner_setup tun_setup;
1728
1729			memset(&tun_setup, 0, sizeof(tun_setup));
1730			tun_setup.mode_mask = T_ANALOG_TV;
1731			tun_setup.type = dev->tuner_type;
1732			tun_setup.addr = v4l2_i2c_subdev_addr(sd);
1733			tun_setup.tuner_callback = cx23885_tuner_callback;
1734
1735			v4l2_subdev_call(sd, tuner, s_type_addr, &tun_setup);
1736
1737			if (dev->board == CX23885_BOARD_LEADTEK_WINFAST_PXTV1200) {
1738				struct xc2028_ctrl ctrl = {
1739					.fname = XC2028_DEFAULT_FIRMWARE,
1740					.max_len = 64
1741				};
1742				struct v4l2_priv_tun_config cfg = {
1743					.tuner = dev->tuner_type,
1744					.priv = &ctrl
1745				};
1746				v4l2_subdev_call(sd, tuner, s_config, &cfg);
1747			}
1748		}
1749	}
1750
1751	/* register Video device */
1752	dev->video_dev = cx23885_vdev_init(dev, dev->pci,
1753		&cx23885_video_template, "video");
1754	err = video_register_device(dev->video_dev, VFL_TYPE_GRABBER,
1755				    video_nr[dev->nr]);
1756	if (err < 0) {
1757		printk(KERN_INFO "%s: can't register video device\n",
1758			dev->name);
1759		goto fail_unreg;
1760	}
1761	printk(KERN_INFO "%s: registered device %s [v4l2]\n",
1762	       dev->name, video_device_node_name(dev->video_dev));
1763
1764	/* register VBI device */
1765	dev->vbi_dev = cx23885_vdev_init(dev, dev->pci,
1766		&cx23885_vbi_template, "vbi");
1767	err = video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
1768				    vbi_nr[dev->nr]);
1769	if (err < 0) {
1770		printk(KERN_INFO "%s: can't register vbi device\n",
1771			dev->name);
1772		goto fail_unreg;
1773	}
1774	printk(KERN_INFO "%s: registered device %s\n",
1775	       dev->name, video_device_node_name(dev->vbi_dev));
1776
1777	/* Register ALSA audio device */
1778	dev->audio_dev = cx23885_audio_register(dev);
1779
1780	/* initial device configuration */
1781	mutex_lock(&dev->lock);
1782	cx23885_set_tvnorm(dev, dev->tvnorm);
1783	init_controls(dev);
1784	cx23885_video_mux(dev, 0);
1785	cx23885_audio_mux(dev, 0);
1786	mutex_unlock(&dev->lock);
1787
1788	return 0;
1789
1790fail_unreg:
1791	cx23885_video_unregister(dev);
1792	return err;
1793}
1794
1795