tw68-video.c 28.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 *  tw68 functions to handle video data
 *
 *  Much of this code is derived from the cx88 and sa7134 drivers, which
 *  were in turn derived from the bt87x driver.  The original work was by
 *  Gerd Knorr; more recently the code was enhanced by Mauro Carvalho Chehab,
 *  Hans Verkuil, Andy Walls and many others.  Their work is gratefully
 *  acknowledged.  Full credit goes to them - any problems within this code
 *  are mine.
 *
11 12 13 14 15
 *  Copyright (C) 2009  William M. Brack
 *
 *  Refactored and updated to the latest v4l core frameworks:
 *
 *  Copyright (C) 2014 Hans Verkuil <hverkuil@xs4all.nl>
16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#include <linux/module.h>
#include <media/v4l2-common.h>
30 31
#include <media/v4l2-event.h>
#include <media/videobuf2-dma-sg.h>
32 33 34 35 36 37 38 39 40 41 42 43

#include "tw68.h"
#include "tw68-reg.h"

/* ------------------------------------------------------------------ */
/* data structs for video                                             */
/*
 * FIXME -
 * Note that the saa7134 has formats, e.g. YUV420, which are classified
 * as "planar".  These affect overlay mode, and are flagged with a field
 * ".planar" in the format.  Do we need to implement this in this driver?
 */
44
static const struct tw68_format formats[] = {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
	{
		.name		= "15 bpp RGB, le",
		.fourcc		= V4L2_PIX_FMT_RGB555,
		.depth		= 16,
		.twformat	= ColorFormatRGB15,
	}, {
		.name		= "15 bpp RGB, be",
		.fourcc		= V4L2_PIX_FMT_RGB555X,
		.depth		= 16,
		.twformat	= ColorFormatRGB15 | ColorFormatBSWAP,
	}, {
		.name		= "16 bpp RGB, le",
		.fourcc		= V4L2_PIX_FMT_RGB565,
		.depth		= 16,
		.twformat	= ColorFormatRGB16,
	}, {
		.name		= "16 bpp RGB, be",
		.fourcc		= V4L2_PIX_FMT_RGB565X,
		.depth		= 16,
		.twformat	= ColorFormatRGB16 | ColorFormatBSWAP,
	}, {
		.name		= "24 bpp RGB, le",
		.fourcc		= V4L2_PIX_FMT_BGR24,
		.depth		= 24,
		.twformat	= ColorFormatRGB24,
	}, {
		.name		= "24 bpp RGB, be",
		.fourcc		= V4L2_PIX_FMT_RGB24,
		.depth		= 24,
		.twformat	= ColorFormatRGB24 | ColorFormatBSWAP,
	}, {
		.name		= "32 bpp RGB, le",
		.fourcc		= V4L2_PIX_FMT_BGR32,
		.depth		= 32,
		.twformat	= ColorFormatRGB32,
	}, {
		.name		= "32 bpp RGB, be",
		.fourcc		= V4L2_PIX_FMT_RGB32,
		.depth		= 32,
		.twformat	= ColorFormatRGB32 | ColorFormatBSWAP |
				  ColorFormatWSWAP,
	}, {
		.name		= "4:2:2 packed, YUYV",
		.fourcc		= V4L2_PIX_FMT_YUYV,
		.depth		= 16,
		.twformat	= ColorFormatYUY2,
	}, {
		.name		= "4:2:2 packed, UYVY",
		.fourcc		= V4L2_PIX_FMT_UYVY,
		.depth		= 16,
		.twformat	= ColorFormatYUY2 | ColorFormatBSWAP,
	}
};
#define FORMATS ARRAY_SIZE(formats)

#define NORM_625_50			\
		.h_delay	= 3,	\
		.h_delay0	= 133,	\
		.h_start	= 0,	\
		.h_stop		= 719,	\
		.v_delay	= 24,	\
		.vbi_v_start_0	= 7,	\
		.vbi_v_stop_0	= 22,	\
		.video_v_start	= 24,	\
		.video_v_stop	= 311,	\
		.vbi_v_start_1	= 319

#define NORM_525_60			\
		.h_delay	= 8,	\
		.h_delay0	= 138,	\
		.h_start	= 0,	\
		.h_stop		= 719,	\
		.v_delay	= 22,	\
		.vbi_v_start_0	= 10,	\
		.vbi_v_stop_0	= 21,	\
		.video_v_start	= 22,	\
		.video_v_stop	= 262,	\
		.vbi_v_start_1	= 273

/*
 * The following table is searched by tw68_s_std, first for a specific
 * match, then for an entry which contains the desired id.  The table
 * entries should therefore be ordered in ascending order of specificity.
 */
129
static const struct tw68_tvnorm tvnorms[] = {
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	{
		.name		= "PAL", /* autodetect */
		.id		= V4L2_STD_PAL,
		NORM_625_50,

		.sync_control	= 0x18,
		.luma_control	= 0x40,
		.chroma_ctrl1	= 0x81,
		.chroma_gain	= 0x2a,
		.chroma_ctrl2	= 0x06,
		.vgate_misc	= 0x1c,
		.format		= VideoFormatPALBDGHI,
	}, {
		.name		= "NTSC",
		.id		= V4L2_STD_NTSC,
		NORM_525_60,

		.sync_control	= 0x59,
		.luma_control	= 0x40,
		.chroma_ctrl1	= 0x89,
		.chroma_gain	= 0x2a,
		.chroma_ctrl2	= 0x0e,
		.vgate_misc	= 0x18,
		.format		= VideoFormatNTSC,
	}, {
		.name		= "SECAM",
		.id		= V4L2_STD_SECAM,
		NORM_625_50,

		.sync_control	= 0x18,
		.luma_control	= 0x1b,
		.chroma_ctrl1	= 0xd1,
		.chroma_gain	= 0x80,
		.chroma_ctrl2	= 0x00,
		.vgate_misc	= 0x1c,
		.format		= VideoFormatSECAM,
	}, {
		.name		= "PAL-M",
		.id		= V4L2_STD_PAL_M,
		NORM_525_60,

		.sync_control	= 0x59,
		.luma_control	= 0x40,
		.chroma_ctrl1	= 0xb9,
		.chroma_gain	= 0x2a,
		.chroma_ctrl2	= 0x0e,
		.vgate_misc	= 0x18,
		.format		= VideoFormatPALM,
	}, {
		.name		= "PAL-Nc",
		.id		= V4L2_STD_PAL_Nc,
		NORM_625_50,

		.sync_control	= 0x18,
		.luma_control	= 0x40,
		.chroma_ctrl1	= 0xa1,
		.chroma_gain	= 0x2a,
		.chroma_ctrl2	= 0x06,
		.vgate_misc	= 0x1c,
		.format		= VideoFormatPALNC,
	}, {
		.name		= "PAL-60",
		.id		= V4L2_STD_PAL_60,
		.h_delay	= 186,
		.h_start	= 0,
		.h_stop		= 719,
		.v_delay	= 26,
		.video_v_start	= 23,
		.video_v_stop	= 262,
		.vbi_v_start_0	= 10,
		.vbi_v_stop_0	= 21,
		.vbi_v_start_1	= 273,

		.sync_control	= 0x18,
		.luma_control	= 0x40,
		.chroma_ctrl1	= 0x81,
		.chroma_gain	= 0x2a,
		.chroma_ctrl2	= 0x06,
		.vgate_misc	= 0x1c,
		.format		= VideoFormatPAL60,
	}
};
#define TVNORMS ARRAY_SIZE(tvnorms)

214
static const struct tw68_format *format_by_fourcc(unsigned int fourcc)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
{
	unsigned int i;

	for (i = 0; i < FORMATS; i++)
		if (formats[i].fourcc == fourcc)
			return formats+i;
	return NULL;
}


/* ------------------------------------------------------------------ */
/*
 * Note that the cropping rectangles are described in terms of a single
 * frame, i.e. line positions are only 1/2 the interlaced equivalent
 */
230
static void set_tvnorm(struct tw68_dev *dev, const struct tw68_tvnorm *norm)
231 232
{
	if (norm != dev->tvnorm) {
233 234
		dev->width = 720;
		dev->height = (norm->id & V4L2_STD_525_60) ? 480 : 576;
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
		dev->tvnorm = norm;
		tw68_set_tvnorm_hw(dev);
	}
}

/*
 * tw68_set_scale
 *
 * Scaling and Cropping for video decoding
 *
 * We are working with 3 values for horizontal and vertical - scale,
 * delay and active.
 *
 * HACTIVE represent the actual number of pixels in the "usable" image,
 * before scaling.  HDELAY represents the number of pixels skipped
 * between the start of the horizontal sync and the start of the image.
 * HSCALE is calculated using the formula
252
 *	HSCALE = (HACTIVE / (#pixels desired)) * 256
253 254 255 256 257 258 259 260 261 262
 *
 * The vertical registers are similar, except based upon the total number
 * of lines in the image, and the first line of the image (i.e. ignoring
 * vertical sync and VBI).
 *
 * Note that the number of bytes reaching the FIFO (and hence needing
 * to be processed by the DMAP program) is completely dependent upon
 * these values, especially HSCALE.
 *
 * Parameters:
263 264 265 266 267
 *	@dev		pointer to the device structure, needed for
 *			getting current norm (as well as debug print)
 *	@width		actual image width (from user buffer)
 *	@height		actual image height
 *	@field		indicates Top, Bottom or Interlaced
268 269 270 271
 */
static int tw68_set_scale(struct tw68_dev *dev, unsigned int width,
			  unsigned int height, enum v4l2_field field)
{
272
	const struct tw68_tvnorm *norm = dev->tvnorm;
273 274 275 276 277 278 279 280
	/* set individually for debugging clarity */
	int hactive, hdelay, hscale;
	int vactive, vdelay, vscale;
	int comb;

	if (V4L2_FIELD_HAS_BOTH(field))	/* if field is interlaced */
		height /= 2;		/* we must set for 1-frame */

281 282 283
	pr_debug("%s: width=%d, height=%d, both=%d\n"
		 "  tvnorm h_delay=%d, h_start=%d, h_stop=%d, "
		 "v_delay=%d, v_start=%d, v_stop=%d\n" , __func__,
284
		width, height, V4L2_FIELD_HAS_BOTH(field),
285 286 287
		norm->h_delay, norm->h_start, norm->h_stop,
		norm->v_delay, norm->video_v_start,
		norm->video_v_stop);
288 289 290

	switch (dev->vdecoder) {
	case TW6800:
291
		hdelay = norm->h_delay0;
292 293
		break;
	default:
294
		hdelay = norm->h_delay;
295 296
		break;
	}
297 298 299

	hdelay += norm->h_start;
	hactive = norm->h_stop - norm->h_start + 1;
300 301 302

	hscale = (hactive * 256) / (width);

303 304
	vdelay = norm->v_delay;
	vactive = ((norm->id & V4L2_STD_525_60) ? 524 : 624) / 2 - norm->video_v_start;
305 306
	vscale = (vactive * 256) / height;

307
	pr_debug("%s: %dx%d [%s%s,%s]\n", __func__,
308 309 310 311
		width, height,
		V4L2_FIELD_HAS_TOP(field)    ? "T" : "",
		V4L2_FIELD_HAS_BOTTOM(field) ? "B" : "",
		v4l2_norm_to_name(dev->tvnorm->id));
312
	pr_debug("%s: hactive=%d, hdelay=%d, hscale=%d; "
313 314 315 316 317 318 319
		"vactive=%d, vdelay=%d, vscale=%d\n", __func__,
		hactive, hdelay, hscale, vactive, vdelay, vscale);

	comb =	((vdelay & 0x300)  >> 2) |
		((vactive & 0x300) >> 4) |
		((hdelay & 0x300)  >> 6) |
		((hactive & 0x300) >> 8);
320
	pr_debug("%s: setting CROP_HI=%02x, VDELAY_LO=%02x, "
321 322 323 324 325 326 327 328 329
		"VACTIVE_LO=%02x, HDELAY_LO=%02x, HACTIVE_LO=%02x\n",
		__func__, comb, vdelay, vactive, hdelay, hactive);
	tw_writeb(TW68_CROP_HI, comb);
	tw_writeb(TW68_VDELAY_LO, vdelay & 0xff);
	tw_writeb(TW68_VACTIVE_LO, vactive & 0xff);
	tw_writeb(TW68_HDELAY_LO, hdelay & 0xff);
	tw_writeb(TW68_HACTIVE_LO, hactive & 0xff);

	comb = ((vscale & 0xf00) >> 4) | ((hscale & 0xf00) >> 8);
330
	pr_debug("%s: setting SCALE_HI=%02x, VSCALE_LO=%02x, "
331 332 333 334 335 336 337 338 339 340
		"HSCALE_LO=%02x\n", __func__, comb, vscale, hscale);
	tw_writeb(TW68_SCALE_HI, comb);
	tw_writeb(TW68_VSCALE_LO, vscale);
	tw_writeb(TW68_HSCALE_LO, hscale);

	return 0;
}

/* ------------------------------------------------------------------ */

341 342
int tw68_video_start_dma(struct tw68_dev *dev, struct tw68_buf *buf)
{
343
	/* Set cropping and scaling */
344
	tw68_set_scale(dev, dev->width, dev->height, dev->field);
345 346 347 348 349 350
	/*
	 *  Set start address for RISC program.  Note that if the DMAP
	 *  processor is currently running, it must be stopped before
	 *  a new address can be set.
	 */
	tw_clearl(TW68_DMAC, TW68_DMAP_EN);
351
	tw_writel(TW68_DMAP_SA, cpu_to_le32(buf->dma));
352 353 354
	/* Clear any pending interrupts */
	tw_writel(TW68_INTSTAT, dev->board_virqmask);
	/* Enable the risc engine and the fifo */
355
	tw_andorl(TW68_DMAC, 0xff, dev->fmt->twformat |
356 357 358 359 360 361 362 363
		ColorFormatGamma | TW68_DMAP_EN | TW68_FIFO_EN);
	dev->pci_irqmask |= dev->board_virqmask;
	tw_setl(TW68_INTMASK, dev->pci_irqmask);
	return 0;
}

/* ------------------------------------------------------------------ */

364 365
/* nr of (tw68-)pages for the given buffer size */
static int tw68_buffer_pages(int size)
366
{
367 368 369 370
	size  = PAGE_ALIGN(size);
	size += PAGE_SIZE; /* for non-page-aligned buffers */
	size /= 4096;
	return size;
371 372
}

373 374 375
/* calc max # of buffers from size (must not exceed the 4MB virtual
 * address space per DMA channel) */
static int tw68_buffer_count(unsigned int size, unsigned int count)
376
{
377
	unsigned int maxcount;
378

379 380 381 382
	maxcount = 1024 / tw68_buffer_pages(size);
	if (count > maxcount)
		count = maxcount;
	return count;
383 384
}

385 386
/* ------------------------------------------------------------- */
/* vb2 queue operations                                          */
387

388 389 390
static int tw68_queue_setup(struct vb2_queue *q, const struct v4l2_format *fmt,
			   unsigned int *num_buffers, unsigned int *num_planes,
			   unsigned int sizes[], void *alloc_ctxs[])
391
{
392 393
	struct tw68_dev *dev = vb2_get_drv_priv(q);
	unsigned tot_bufs = q->num_buffers + *num_buffers;
394

395 396 397 398 399 400 401 402 403 404 405 406 407
	sizes[0] = (dev->fmt->depth * dev->width * dev->height) >> 3;
	/*
	 * We allow create_bufs, but only if the sizeimage is the same as the
	 * current sizeimage. The tw68_buffer_count calculation becomes quite
	 * difficult otherwise.
	 */
	if (fmt && fmt->fmt.pix.sizeimage < sizes[0])
		return -EINVAL;
	*num_planes = 1;
	if (tot_bufs < 2)
		tot_bufs = 2;
	tot_bufs = tw68_buffer_count(sizes[0], tot_bufs);
	*num_buffers = tot_bufs - q->num_buffers;
408 409 410 411 412

	return 0;
}

/*
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
 * The risc program for each buffers works as follows: it starts with a simple
 * 'JUMP to addr + 8', which is effectively a NOP. Then the program to DMA the
 * buffer follows and at the end we have a JUMP back to the start + 8 (skipping
 * the initial JUMP).
 *
 * This is the program of the first buffer to be queued if the active list is
 * empty and it just keeps DMAing this buffer without generating any interrupts.
 *
 * If a new buffer is added then the initial JUMP in the program generates an
 * interrupt as well which signals that the previous buffer has been DMAed
 * successfully and that it can be returned to userspace.
 *
 * It also sets the final jump of the previous buffer to the start of the new
 * buffer, thus chaining the new buffer into the DMA chain. This is a single
 * atomic u32 write, so there is no race condition.
428
 *
429 430
 * The end-result of all this that you only get an interrupt when a buffer
 * is ready, so the control flow is very easy.
431
 */
432
static void tw68_buf_queue(struct vb2_buffer *vb)
433
{
434 435 436 437 438 439 440
	struct vb2_queue *vq = vb->vb2_queue;
	struct tw68_dev *dev = vb2_get_drv_priv(vq);
	struct tw68_buf *buf = container_of(vb, struct tw68_buf, vb);
	struct tw68_buf *prev;
	unsigned long flags;

	spin_lock_irqsave(&dev->slock, flags);
441

442 443 444 445 446 447 448 449 450 451 452
	/* append a 'JUMP to start of buffer' to the buffer risc program */
	buf->jmp[0] = cpu_to_le32(RISC_JUMP);
	buf->jmp[1] = cpu_to_le32(buf->dma + 8);

	if (!list_empty(&dev->active)) {
		prev = list_entry(dev->active.prev, struct tw68_buf, list);
		buf->cpu[0] |= cpu_to_le32(RISC_INT_BIT);
		prev->jmp[1] = cpu_to_le32(buf->dma);
	}
	list_add_tail(&buf->list, &dev->active);
	spin_unlock_irqrestore(&dev->slock, flags);
453 454 455
}

/*
456
 * buffer_prepare
457
 *
458 459 460 461 462 463 464
 * Set the ancilliary information into the buffer structure.  This
 * includes generating the necessary risc program if it hasn't already
 * been done for the current buffer format.
 * The structure fh contains the details of the format requested by the
 * user - type, width, height and #fields.  This is compared with the
 * last format set for the current buffer.  If they differ, the risc
 * code (which controls the filling of the buffer) is (re-)generated.
465
 */
466
static int tw68_buf_prepare(struct vb2_buffer *vb)
467
{
468 469
	struct vb2_queue *vq = vb->vb2_queue;
	struct tw68_dev *dev = vb2_get_drv_priv(vq);
470
	struct tw68_buf *buf = container_of(vb, struct tw68_buf, vb);
471 472 473
	struct sg_table *dma = vb2_dma_sg_plane_desc(vb, 0);
	unsigned size, bpl;
	int rc;
474

475 476 477 478
	size = (dev->width * dev->height * dev->fmt->depth) >> 3;
	if (vb2_plane_size(vb, 0) < size)
		return -EINVAL;
	vb2_set_plane_payload(vb, 0, size);
479

480 481 482
	rc = dma_map_sg(&dev->pci->dev, dma->sgl, dma->nents, DMA_FROM_DEVICE);
	if (!rc)
		return -EIO;
483

484 485 486 487 488
	bpl = (dev->width * dev->fmt->depth) >> 3;
	switch (dev->field) {
	case V4L2_FIELD_TOP:
		tw68_risc_buffer(dev->pci, buf, dma->sgl,
				 0, UNSET, bpl, 0, dev->height);
489
		break;
490 491 492
	case V4L2_FIELD_BOTTOM:
		tw68_risc_buffer(dev->pci, buf, dma->sgl,
				 UNSET, 0, bpl, 0, dev->height);
493
		break;
494 495 496 497
	case V4L2_FIELD_SEQ_TB:
		tw68_risc_buffer(dev->pci, buf, dma->sgl,
				 0, bpl * (dev->height >> 1),
				 bpl, 0, dev->height >> 1);
498
		break;
499 500 501 502
	case V4L2_FIELD_SEQ_BT:
		tw68_risc_buffer(dev->pci, buf, dma->sgl,
				 bpl * (dev->height >> 1), 0,
				 bpl, 0, dev->height >> 1);
503
		break;
504
	case V4L2_FIELD_INTERLACED:
505
	default:
506 507 508
		tw68_risc_buffer(dev->pci, buf, dma->sgl,
				 0, bpl, bpl, bpl, dev->height >> 1);
		break;
509 510 511 512
	}
	return 0;
}

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
static void tw68_buf_finish(struct vb2_buffer *vb)
{
	struct vb2_queue *vq = vb->vb2_queue;
	struct tw68_dev *dev = vb2_get_drv_priv(vq);
	struct sg_table *dma = vb2_dma_sg_plane_desc(vb, 0);
	struct tw68_buf *buf = container_of(vb, struct tw68_buf, vb);

	dma_unmap_sg(&dev->pci->dev, dma->sgl, dma->nents, DMA_FROM_DEVICE);

	pci_free_consistent(dev->pci, buf->size, buf->cpu, buf->dma);
}

static int tw68_start_streaming(struct vb2_queue *q, unsigned int count)
{
	struct tw68_dev *dev = vb2_get_drv_priv(q);
	struct tw68_buf *buf =
		container_of(dev->active.next, struct tw68_buf, list);

	dev->seqnr = 0;
	tw68_video_start_dma(dev, buf);
	return 0;
}

static void tw68_stop_streaming(struct vb2_queue *q)
537
{
538 539 540 541 542 543 544
	struct tw68_dev *dev = vb2_get_drv_priv(q);

	/* Stop risc & fifo */
	tw_clearl(TW68_DMAC, TW68_DMAP_EN | TW68_FIFO_EN);
	while (!list_empty(&dev->active)) {
		struct tw68_buf *buf =
			container_of(dev->active.next, struct tw68_buf, list);
545

546 547 548
		list_del(&buf->list);
		vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
	}
549 550
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564
static struct vb2_ops tw68_video_qops = {
	.queue_setup	= tw68_queue_setup,
	.buf_queue	= tw68_buf_queue,
	.buf_prepare	= tw68_buf_prepare,
	.buf_finish	= tw68_buf_finish,
	.start_streaming = tw68_start_streaming,
	.stop_streaming = tw68_stop_streaming,
	.wait_prepare	= vb2_ops_wait_prepare,
	.wait_finish	= vb2_ops_wait_finish,
};

/* ------------------------------------------------------------------ */

static int tw68_s_ctrl(struct v4l2_ctrl *ctrl)
565
{
566 567
	struct tw68_dev *dev =
		container_of(ctrl->handler, struct tw68_dev, hdl);
568

569
	switch (ctrl->id) {
570
	case V4L2_CID_BRIGHTNESS:
571
		tw_writeb(TW68_BRIGHT, ctrl->val);
572 573
		break;
	case V4L2_CID_HUE:
574
		tw_writeb(TW68_HUE, ctrl->val);
575 576
		break;
	case V4L2_CID_CONTRAST:
577
		tw_writeb(TW68_CONTRAST, ctrl->val);
578 579
		break;
	case V4L2_CID_SATURATION:
580 581
		tw_writeb(TW68_SAT_U, ctrl->val);
		tw_writeb(TW68_SAT_V, ctrl->val);
582 583
		break;
	case V4L2_CID_COLOR_KILLER:
584
		if (ctrl->val)
585 586 587 588 589
			tw_andorb(TW68_MISC2, 0xe0, 0xe0);
		else
			tw_andorb(TW68_MISC2, 0xe0, 0x00);
		break;
	case V4L2_CID_CHROMA_AGC:
590
		if (ctrl->val)
591 592 593 594 595
			tw_andorb(TW68_LOOP, 0x30, 0x20);
		else
			tw_andorb(TW68_LOOP, 0x30, 0x00);
		break;
	}
596
	return 0;
597 598
}

599
/* ------------------------------------------------------------------ */
600

601 602 603 604 605 606 607 608
/*
 * Note that this routine returns what is stored in the fh structure, and
 * does not interrogate any of the device registers.
 */
static int tw68_g_fmt_vid_cap(struct file *file, void *priv,
				struct v4l2_format *f)
{
	struct tw68_dev *dev = video_drvdata(file);
609

610 611 612 613
	f->fmt.pix.width        = dev->width;
	f->fmt.pix.height       = dev->height;
	f->fmt.pix.field        = dev->field;
	f->fmt.pix.pixelformat  = dev->fmt->fourcc;
614
	f->fmt.pix.bytesperline =
615
		(f->fmt.pix.width * (dev->fmt->depth)) >> 3;
616 617 618
	f->fmt.pix.sizeimage =
		f->fmt.pix.height * f->fmt.pix.bytesperline;
	f->fmt.pix.colorspace	= V4L2_COLORSPACE_SMPTE170M;
619
	f->fmt.pix.priv = 0;
620 621 622 623 624 625
	return 0;
}

static int tw68_try_fmt_vid_cap(struct file *file, void *priv,
						struct v4l2_format *f)
{
626 627
	struct tw68_dev *dev = video_drvdata(file);
	const struct tw68_format *fmt;
628
	enum v4l2_field field;
629
	unsigned int maxh;
630 631 632 633 634 635

	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
	if (NULL == fmt)
		return -EINVAL;

	field = f->fmt.pix.field;
636
	maxh  = (dev->tvnorm->id & V4L2_STD_525_60) ? 480 : 576;
637 638 639 640 641 642

	switch (field) {
	case V4L2_FIELD_TOP:
	case V4L2_FIELD_BOTTOM:
		break;
	case V4L2_FIELD_INTERLACED:
643 644
	case V4L2_FIELD_SEQ_BT:
	case V4L2_FIELD_SEQ_TB:
645 646 647
		maxh = maxh * 2;
		break;
	default:
648 649 650 651
		field = (f->fmt.pix.height > maxh / 2)
			? V4L2_FIELD_INTERLACED
			: V4L2_FIELD_BOTTOM;
		break;
652 653 654 655 656 657 658
	}

	f->fmt.pix.field = field;
	if (f->fmt.pix.width  < 48)
		f->fmt.pix.width  = 48;
	if (f->fmt.pix.height < 32)
		f->fmt.pix.height = 32;
659 660
	if (f->fmt.pix.width > 720)
		f->fmt.pix.width = 720;
661 662 663 664 665 666 667
	if (f->fmt.pix.height > maxh)
		f->fmt.pix.height = maxh;
	f->fmt.pix.width &= ~0x03;
	f->fmt.pix.bytesperline =
		(f->fmt.pix.width * (fmt->depth)) >> 3;
	f->fmt.pix.sizeimage =
		f->fmt.pix.height * f->fmt.pix.bytesperline;
668
	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
669 670 671 672 673 674 675 676 677 678 679 680
	return 0;
}

/*
 * Note that tw68_s_fmt_vid_cap sets the information into the fh structure,
 * and it will be used for all future new buffers.  However, there could be
 * some number of buffers on the "active" chain which will be filled before
 * the change takes place.
 */
static int tw68_s_fmt_vid_cap(struct file *file, void *priv,
					struct v4l2_format *f)
{
681
	struct tw68_dev *dev = video_drvdata(file);
682 683 684 685 686 687
	int err;

	err = tw68_try_fmt_vid_cap(file, priv, f);
	if (0 != err)
		return err;

688 689 690 691
	dev->fmt = format_by_fourcc(f->fmt.pix.pixelformat);
	dev->width = f->fmt.pix.width;
	dev->height = f->fmt.pix.height;
	dev->field = f->fmt.pix.field;
692 693 694 695 696 697
	return 0;
}

static int tw68_enum_input(struct file *file, void *priv,
					struct v4l2_input *i)
{
698
	struct tw68_dev *dev = video_drvdata(file);
699 700 701
	unsigned int n;

	n = i->index;
702
	if (n >= TW68_INPUT_MAX)
703 704
		return -EINVAL;
	i->index = n;
705 706 707
	i->type = V4L2_INPUT_TYPE_CAMERA;
	snprintf(i->name, sizeof(i->name), "Composite %d", n);

708
	/* If the query is for the current input, get live data */
709
	if (n == dev->input) {
710 711 712 713 714 715 716 717 718 719 720 721 722 723
		int v1 = tw_readb(TW68_STATUS1);
		int v2 = tw_readb(TW68_MVSN);

		if (0 != (v1 & (1 << 7)))
			i->status |= V4L2_IN_ST_NO_SYNC;
		if (0 != (v1 & (1 << 6)))
			i->status |= V4L2_IN_ST_NO_H_LOCK;
		if (0 != (v1 & (1 << 2)))
			i->status |= V4L2_IN_ST_NO_SIGNAL;
		if (0 != (v1 & 1 << 1))
			i->status |= V4L2_IN_ST_NO_COLOR;
		if (0 != (v2 & (1 << 2)))
			i->status |= V4L2_IN_ST_MACROVISION;
	}
724
	i->std = video_devdata(file)->tvnorms;
725 726 727 728 729
	return 0;
}

static int tw68_g_input(struct file *file, void *priv, unsigned int *i)
{
730
	struct tw68_dev *dev = video_drvdata(file);
731

732
	*i = dev->input;
733 734 735 736 737
	return 0;
}

static int tw68_s_input(struct file *file, void *priv, unsigned int i)
{
738
	struct tw68_dev *dev = video_drvdata(file);
739

740
	if (i >= TW68_INPUT_MAX)
741
		return -EINVAL;
742 743
	dev->input = i;
	tw_andorb(TW68_INFORM, 0x03 << 2, dev->input << 2);
744 745 746 747 748 749
	return 0;
}

static int tw68_querycap(struct file *file, void  *priv,
					struct v4l2_capability *cap)
{
750
	struct tw68_dev *dev = video_drvdata(file);
751 752

	strcpy(cap->driver, "tw68");
753
	strlcpy(cap->card, "Techwell Capture Card",
754 755
		sizeof(cap->card));
	sprintf(cap->bus_info, "PCI:%s", pci_name(dev->pci));
756
	cap->device_caps =
757 758
		V4L2_CAP_VIDEO_CAPTURE |
		V4L2_CAP_READWRITE |
759
		V4L2_CAP_STREAMING;
760

761
	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
762 763 764
	return 0;
}

765
static int tw68_s_std(struct file *file, void *priv, v4l2_std_id id)
766
{
767
	struct tw68_dev *dev = video_drvdata(file);
768 769
	unsigned int i;

770 771
	if (vb2_is_busy(&dev->vidq))
		return -EBUSY;
772 773 774

	/* Look for match on complete norm id (may have mult bits) */
	for (i = 0; i < TVNORMS; i++) {
775
		if (id == tvnorms[i].id)
776 777 778 779
			break;
	}

	/* If no exact match, look for norm which contains this one */
780 781 782
	if (i == TVNORMS) {
		for (i = 0; i < TVNORMS; i++)
			if (id & tvnorms[i].id)
783
				break;
784
	}
785 786 787 788 789 790 791 792 793 794
	/* If still not matched, give up */
	if (i == TVNORMS)
		return -EINVAL;

	set_tvnorm(dev, &tvnorms[i]);	/* do the actual setting */
	return 0;
}

static int tw68_g_std(struct file *file, void *priv, v4l2_std_id *id)
{
795
	struct tw68_dev *dev = video_drvdata(file);
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

	*id = dev->tvnorm->id;
	return 0;
}

static int tw68_enum_fmt_vid_cap(struct file *file, void  *priv,
					struct v4l2_fmtdesc *f)
{
	if (f->index >= FORMATS)
		return -EINVAL;

	strlcpy(f->description, formats[f->index].name,
		sizeof(f->description));

	f->pixelformat = formats[f->index].fourcc;

	return 0;
}

/*
 * Used strictly for internal development and debugging, this routine
 * prints out the current register contents for the tw68xx device.
 */
static void tw68_dump_regs(struct tw68_dev *dev)
{
	unsigned char line[80];
	int i, j, k;
	unsigned char *cptr;

825
	pr_info("Full dump of TW68 registers:\n");
826 827 828 829 830 831 832 833 834 835 836 837
	/* First we do the PCI regs, 8 4-byte regs per line */
	for (i = 0; i < 0x100; i += 32) {
		cptr = line;
		cptr += sprintf(cptr, "%03x  ", i);
		/* j steps through the next 4 words */
		for (j = i; j < i + 16; j += 4)
			cptr += sprintf(cptr, "%08x ", tw_readl(j));
		*cptr++ = ' ';
		for (; j < i + 32; j += 4)
			cptr += sprintf(cptr, "%08x ", tw_readl(j));
		*cptr++ = '\n';
		*cptr = 0;
838
		pr_info("%s", line);
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
	}
	/* Next the control regs, which are single-byte, address mod 4 */
	while (i < 0x400) {
		cptr = line;
		cptr += sprintf(cptr, "%03x ", i);
		/* Print out 4 groups of 4 bytes */
		for (j = 0; j < 4; j++) {
			for (k = 0; k < 4; k++) {
				cptr += sprintf(cptr, "%02x ",
					tw_readb(i));
				i += 4;
			}
			*cptr++ = ' ';
		}
		*cptr++ = '\n';
		*cptr = 0;
855
		pr_info("%s", line);
856 857 858 859 860
	}
}

static int vidioc_log_status(struct file *file, void *priv)
{
861
	struct tw68_dev *dev = video_drvdata(file);
862 863

	tw68_dump_regs(dev);
864
	return v4l2_ctrl_log_status(file, priv);
865 866
}

867
#ifdef CONFIG_VIDEO_ADV_DEBUG
868 869 870
static int vidioc_g_register(struct file *file, void *priv,
			      struct v4l2_dbg_register *reg)
{
871
	struct tw68_dev *dev = video_drvdata(file);
872 873 874 875 876 877 878 879 880

	if (reg->size == 1)
		reg->val = tw_readb(reg->reg);
	else
		reg->val = tw_readl(reg->reg);
	return 0;
}

static int vidioc_s_register(struct file *file, void *priv,
881
				const struct v4l2_dbg_register *reg)
882
{
883
	struct tw68_dev *dev = video_drvdata(file);
884 885 886 887 888 889 890 891 892

	if (reg->size == 1)
		tw_writeb(reg->reg, reg->val);
	else
		tw_writel(reg->reg & 0xffff, reg->val);
	return 0;
}
#endif

893 894 895 896
static const struct v4l2_ctrl_ops tw68_ctrl_ops = {
	.s_ctrl = tw68_s_ctrl,
};

897 898
static const struct v4l2_file_operations video_fops = {
	.owner			= THIS_MODULE,
899 900 901 902 903 904
	.open			= v4l2_fh_open,
	.release		= vb2_fop_release,
	.read			= vb2_fop_read,
	.poll			= vb2_fop_poll,
	.mmap			= vb2_fop_mmap,
	.unlocked_ioctl		= video_ioctl2,
905 906 907 908 909
};

static const struct v4l2_ioctl_ops video_ioctl_ops = {
	.vidioc_querycap		= tw68_querycap,
	.vidioc_enum_fmt_vid_cap	= tw68_enum_fmt_vid_cap,
910 911 912 913 914
	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
	.vidioc_querybuf		= vb2_ioctl_querybuf,
	.vidioc_qbuf			= vb2_ioctl_qbuf,
	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
915 916 917 918 919
	.vidioc_s_std			= tw68_s_std,
	.vidioc_g_std			= tw68_g_std,
	.vidioc_enum_input		= tw68_enum_input,
	.vidioc_g_input			= tw68_g_input,
	.vidioc_s_input			= tw68_s_input,
920 921
	.vidioc_streamon		= vb2_ioctl_streamon,
	.vidioc_streamoff		= vb2_ioctl_streamoff,
922 923 924 925
	.vidioc_g_fmt_vid_cap		= tw68_g_fmt_vid_cap,
	.vidioc_try_fmt_vid_cap		= tw68_try_fmt_vid_cap,
	.vidioc_s_fmt_vid_cap		= tw68_s_fmt_vid_cap,
	.vidioc_log_status		= vidioc_log_status,
926 927 928
	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
#ifdef CONFIG_VIDEO_ADV_DEBUG
929 930 931 932 933
	.vidioc_g_register              = vidioc_g_register,
	.vidioc_s_register              = vidioc_s_register,
#endif
};

934
static struct video_device tw68_video_template = {
935 936 937
	.name			= "tw68_video",
	.fops			= &video_fops,
	.ioctl_ops		= &video_ioctl_ops,
938
	.release		= video_device_release_empty,
939 940 941
	.tvnorms		= TW68_NORMS,
};

942 943
/* ------------------------------------------------------------------ */
/* exported stuff                                                     */
944 945 946 947 948 949 950
void tw68_set_tvnorm_hw(struct tw68_dev *dev)
{
	tw_andorb(TW68_SDT, 0x07, dev->tvnorm->format);
}

int tw68_video_init1(struct tw68_dev *dev)
{
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
	struct v4l2_ctrl_handler *hdl = &dev->hdl;

	v4l2_ctrl_handler_init(hdl, 6);
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_BRIGHTNESS, -128, 127, 1, 20);
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_CONTRAST, 0, 255, 1, 100);
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_SATURATION, 0, 255, 1, 128);
	/* NTSC only */
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_HUE, -128, 127, 1, 0);
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
	v4l2_ctrl_new_std(hdl, &tw68_ctrl_ops,
			V4L2_CID_CHROMA_AGC, 0, 1, 1, 1);
	if (hdl->error) {
		v4l2_ctrl_handler_free(hdl);
		return hdl->error;
	}
	dev->v4l2_dev.ctrl_handler = hdl;
	v4l2_ctrl_handler_setup(hdl);
973 974 975
	return 0;
}

976
int tw68_video_init2(struct tw68_dev *dev, int video_nr)
977
{
978 979
	int ret;

980 981
	set_tvnorm(dev, &tvnorms[0]);

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
	dev->fmt      = format_by_fourcc(V4L2_PIX_FMT_BGR24);
	dev->width    = 720;
	dev->height   = 576;
	dev->field    = V4L2_FIELD_INTERLACED;

	INIT_LIST_HEAD(&dev->active);
	dev->vidq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	dev->vidq.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
	dev->vidq.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ | VB2_DMABUF;
	dev->vidq.ops = &tw68_video_qops;
	dev->vidq.mem_ops = &vb2_dma_sg_memops;
	dev->vidq.drv_priv = dev;
	dev->vidq.gfp_flags = __GFP_DMA32;
	dev->vidq.buf_struct_size = sizeof(struct tw68_buf);
	dev->vidq.lock = &dev->lock;
	dev->vidq.min_buffers_needed = 2;
	ret = vb2_queue_init(&dev->vidq);
	if (ret)
		return ret;
	dev->vdev = tw68_video_template;
	dev->vdev.v4l2_dev = &dev->v4l2_dev;
	dev->vdev.lock = &dev->lock;
	dev->vdev.queue = &dev->vidq;
	video_set_drvdata(&dev->vdev, dev);
	return video_register_device(&dev->vdev, VFL_TYPE_GRABBER, video_nr);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
}

/*
 * tw68_irq_video_done
 */
void tw68_irq_video_done(struct tw68_dev *dev, unsigned long status)
{
	__u32 reg;

	/* reset interrupts handled by this routine */
	tw_writel(TW68_INTSTAT, status);
	/*
	 * Check most likely first
	 *
	 * DMAPI shows we have reached the end of the risc code
	 * for the current buffer.
	 */
	if (status & TW68_DMAPI) {
1025 1026
		struct tw68_buf *buf;

1027
		spin_lock(&dev->slock);
1028 1029
		buf = list_entry(dev->active.next, struct tw68_buf, list);
		list_del(&buf->list);
1030
		spin_unlock(&dev->slock);
1031 1032 1033 1034
		v4l2_get_timestamp(&buf->vb.v4l2_buf.timestamp);
		buf->vb.v4l2_buf.field = dev->field;
		buf->vb.v4l2_buf.sequence = dev->seqnr++;
		vb2_buffer_done(&buf->vb, VB2_BUF_STATE_DONE);
1035 1036 1037 1038
		status &= ~(TW68_DMAPI);
		if (0 == status)
			return;
	}
1039 1040 1041 1042 1043 1044
	if (status & (TW68_VLOCK | TW68_HLOCK))
		dev_dbg(&dev->pci->dev, "Lost sync\n");
	if (status & TW68_PABORT)
		dev_err(&dev->pci->dev, "PABORT interrupt\n");
	if (status & TW68_DMAPERR)
		dev_err(&dev->pci->dev, "DMAPERR interrupt\n");
1045 1046 1047 1048
	/*
	 * On TW6800, FDMIS is apparently generated if video input is switched
	 * during operation.  Therefore, it is not enabled for that chip.
	 */
1049 1050 1051 1052
	if (status & TW68_FDMIS)
		dev_dbg(&dev->pci->dev, "FDMIS interrupt\n");
	if (status & TW68_FFOF) {
		/* probably a logic error */
1053 1054
		reg = tw_readl(TW68_DMAC) & TW68_FIFO_EN;
		tw_clearl(TW68_DMAC, TW68_FIFO_EN);
1055
		dev_dbg(&dev->pci->dev, "FFOF interrupt\n");
1056 1057 1058
		tw_setl(TW68_DMAC, reg);
	}
	if (status & TW68_FFERR)
1059
		dev_dbg(&dev->pci->dev, "FFERR interrupt\n");
1060
}