1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  Support for a cx23417 mpeg encoder via cx23885 host port.
5  *
6  *    (c) 2004 Jelle Foks <jelle@foks.us>
7  *    (c) 2004 Gerd Knorr <kraxel@bytesex.org>
8  *    (c) 2008 Steven Toth <stoth@linuxtv.org>
9  *      - CX23885/7/8 support
10  *
11  *  Includes parts from the ivtv driver <http://sourceforge.net/projects/ivtv/>
12  */
13 
14 #include "cx23885.h"
15 #include "cx23885-ioctl.h"
16 
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/init.h>
20 #include <linux/fs.h>
21 #include <linux/delay.h>
22 #include <linux/device.h>
23 #include <linux/firmware.h>
24 #include <linux/slab.h>
25 #include <media/v4l2-common.h>
26 #include <media/v4l2-ioctl.h>
27 #include <media/drv-intf/cx2341x.h>
28 
29 #define CX23885_FIRM_IMAGE_SIZE 376836
30 #define CX23885_FIRM_IMAGE_NAME "v4l-cx23885-enc.fw"
31 
32 static unsigned int mpegbufs = 32;
33 module_param(mpegbufs, int, 0644);
34 MODULE_PARM_DESC(mpegbufs, "number of mpeg buffers, range 2-32");
35 static unsigned int mpeglines = 32;
36 module_param(mpeglines, int, 0644);
37 MODULE_PARM_DESC(mpeglines, "number of lines in an MPEG buffer, range 2-32");
38 static unsigned int mpeglinesize = 512;
39 module_param(mpeglinesize, int, 0644);
40 MODULE_PARM_DESC(mpeglinesize,
41 	"number of bytes in each line of an MPEG buffer, range 512-1024");
42 
43 static unsigned int v4l_debug;
44 module_param(v4l_debug, int, 0644);
45 MODULE_PARM_DESC(v4l_debug, "enable V4L debug messages");
46 
47 #define dprintk(level, fmt, arg...)\
48 	do { if (v4l_debug >= level) \
49 		printk(KERN_DEBUG pr_fmt("%s: 417:" fmt), \
50 			__func__, ##arg); \
51 	} while (0)
52 
53 static struct cx23885_tvnorm cx23885_tvnorms[] = {
54 	{
55 		.name      = "NTSC-M",
56 		.id        = V4L2_STD_NTSC_M,
57 	}, {
58 		.name      = "NTSC-JP",
59 		.id        = V4L2_STD_NTSC_M_JP,
60 	}, {
61 		.name      = "PAL-BG",
62 		.id        = V4L2_STD_PAL_BG,
63 	}, {
64 		.name      = "PAL-DK",
65 		.id        = V4L2_STD_PAL_DK,
66 	}, {
67 		.name      = "PAL-I",
68 		.id        = V4L2_STD_PAL_I,
69 	}, {
70 		.name      = "PAL-M",
71 		.id        = V4L2_STD_PAL_M,
72 	}, {
73 		.name      = "PAL-N",
74 		.id        = V4L2_STD_PAL_N,
75 	}, {
76 		.name      = "PAL-Nc",
77 		.id        = V4L2_STD_PAL_Nc,
78 	}, {
79 		.name      = "PAL-60",
80 		.id        = V4L2_STD_PAL_60,
81 	}, {
82 		.name      = "SECAM-L",
83 		.id        = V4L2_STD_SECAM_L,
84 	}, {
85 		.name      = "SECAM-DK",
86 		.id        = V4L2_STD_SECAM_DK,
87 	}
88 };
89 
90 /* ------------------------------------------------------------------ */
91 enum cx23885_capture_type {
92 	CX23885_MPEG_CAPTURE,
93 	CX23885_RAW_CAPTURE,
94 	CX23885_RAW_PASSTHRU_CAPTURE
95 };
96 enum cx23885_capture_bits {
97 	CX23885_RAW_BITS_NONE             = 0x00,
98 	CX23885_RAW_BITS_YUV_CAPTURE      = 0x01,
99 	CX23885_RAW_BITS_PCM_CAPTURE      = 0x02,
100 	CX23885_RAW_BITS_VBI_CAPTURE      = 0x04,
101 	CX23885_RAW_BITS_PASSTHRU_CAPTURE = 0x08,
102 	CX23885_RAW_BITS_TO_HOST_CAPTURE  = 0x10
103 };
104 enum cx23885_capture_end {
105 	CX23885_END_AT_GOP, /* stop at the end of gop, generate irq */
106 	CX23885_END_NOW, /* stop immediately, no irq */
107 };
108 enum cx23885_framerate {
109 	CX23885_FRAMERATE_NTSC_30, /* NTSC: 30fps */
110 	CX23885_FRAMERATE_PAL_25   /* PAL: 25fps */
111 };
112 enum cx23885_stream_port {
113 	CX23885_OUTPUT_PORT_MEMORY,
114 	CX23885_OUTPUT_PORT_STREAMING,
115 	CX23885_OUTPUT_PORT_SERIAL
116 };
117 enum cx23885_data_xfer_status {
118 	CX23885_MORE_BUFFERS_FOLLOW,
119 	CX23885_LAST_BUFFER,
120 };
121 enum cx23885_picture_mask {
122 	CX23885_PICTURE_MASK_NONE,
123 	CX23885_PICTURE_MASK_I_FRAMES,
124 	CX23885_PICTURE_MASK_I_P_FRAMES = 0x3,
125 	CX23885_PICTURE_MASK_ALL_FRAMES = 0x7,
126 };
127 enum cx23885_vbi_mode_bits {
128 	CX23885_VBI_BITS_SLICED,
129 	CX23885_VBI_BITS_RAW,
130 };
131 enum cx23885_vbi_insertion_bits {
132 	CX23885_VBI_BITS_INSERT_IN_XTENSION_USR_DATA,
133 	CX23885_VBI_BITS_INSERT_IN_PRIVATE_PACKETS = 0x1 << 1,
134 	CX23885_VBI_BITS_SEPARATE_STREAM = 0x2 << 1,
135 	CX23885_VBI_BITS_SEPARATE_STREAM_USR_DATA = 0x4 << 1,
136 	CX23885_VBI_BITS_SEPARATE_STREAM_PRV_DATA = 0x5 << 1,
137 };
138 enum cx23885_dma_unit {
139 	CX23885_DMA_BYTES,
140 	CX23885_DMA_FRAMES,
141 };
142 enum cx23885_dma_transfer_status_bits {
143 	CX23885_DMA_TRANSFER_BITS_DONE = 0x01,
144 	CX23885_DMA_TRANSFER_BITS_ERROR = 0x04,
145 	CX23885_DMA_TRANSFER_BITS_LL_ERROR = 0x10,
146 };
147 enum cx23885_pause {
148 	CX23885_PAUSE_ENCODING,
149 	CX23885_RESUME_ENCODING,
150 };
151 enum cx23885_copyright {
152 	CX23885_COPYRIGHT_OFF,
153 	CX23885_COPYRIGHT_ON,
154 };
155 enum cx23885_notification_type {
156 	CX23885_NOTIFICATION_REFRESH,
157 };
158 enum cx23885_notification_status {
159 	CX23885_NOTIFICATION_OFF,
160 	CX23885_NOTIFICATION_ON,
161 };
162 enum cx23885_notification_mailbox {
163 	CX23885_NOTIFICATION_NO_MAILBOX = -1,
164 };
165 enum cx23885_field1_lines {
166 	CX23885_FIELD1_SAA7114 = 0x00EF, /* 239 */
167 	CX23885_FIELD1_SAA7115 = 0x00F0, /* 240 */
168 	CX23885_FIELD1_MICRONAS = 0x0105, /* 261 */
169 };
170 enum cx23885_field2_lines {
171 	CX23885_FIELD2_SAA7114 = 0x00EF, /* 239 */
172 	CX23885_FIELD2_SAA7115 = 0x00F0, /* 240 */
173 	CX23885_FIELD2_MICRONAS = 0x0106, /* 262 */
174 };
175 enum cx23885_custom_data_type {
176 	CX23885_CUSTOM_EXTENSION_USR_DATA,
177 	CX23885_CUSTOM_PRIVATE_PACKET,
178 };
179 enum cx23885_mute {
180 	CX23885_UNMUTE,
181 	CX23885_MUTE,
182 };
183 enum cx23885_mute_video_mask {
184 	CX23885_MUTE_VIDEO_V_MASK = 0x0000FF00,
185 	CX23885_MUTE_VIDEO_U_MASK = 0x00FF0000,
186 	CX23885_MUTE_VIDEO_Y_MASK = 0xFF000000,
187 };
188 enum cx23885_mute_video_shift {
189 	CX23885_MUTE_VIDEO_V_SHIFT = 8,
190 	CX23885_MUTE_VIDEO_U_SHIFT = 16,
191 	CX23885_MUTE_VIDEO_Y_SHIFT = 24,
192 };
193 
194 /* defines below are from ivtv-driver.h */
195 #define IVTV_CMD_HW_BLOCKS_RST 0xFFFFFFFF
196 
197 /* Firmware API commands */
198 #define IVTV_API_STD_TIMEOUT 500
199 
200 /* Registers */
201 /* IVTV_REG_OFFSET */
202 #define IVTV_REG_ENC_SDRAM_REFRESH (0x07F8)
203 #define IVTV_REG_ENC_SDRAM_PRECHARGE (0x07FC)
204 #define IVTV_REG_SPU (0x9050)
205 #define IVTV_REG_HW_BLOCKS (0x9054)
206 #define IVTV_REG_VPU (0x9058)
207 #define IVTV_REG_APU (0xA064)
208 
209 /**** Bit definitions for MC417_RWD and MC417_OEN registers  ***
210   bits 31-16
211 +-----------+
212 | Reserved  |
213 +-----------+
214   bit 15  bit 14  bit 13 bit 12  bit 11  bit 10  bit 9   bit 8
215 +-------+-------+-------+-------+-------+-------+-------+-------+
216 | MIWR# | MIRD# | MICS# |MIRDY# |MIADDR3|MIADDR2|MIADDR1|MIADDR0|
217 +-------+-------+-------+-------+-------+-------+-------+-------+
218  bit 7   bit 6   bit 5   bit 4   bit 3   bit 2   bit 1   bit 0
219 +-------+-------+-------+-------+-------+-------+-------+-------+
220 |MIDATA7|MIDATA6|MIDATA5|MIDATA4|MIDATA3|MIDATA2|MIDATA1|MIDATA0|
221 +-------+-------+-------+-------+-------+-------+-------+-------+
222 ***/
223 #define MC417_MIWR	0x8000
224 #define MC417_MIRD	0x4000
225 #define MC417_MICS	0x2000
226 #define MC417_MIRDY	0x1000
227 #define MC417_MIADDR	0x0F00
228 #define MC417_MIDATA	0x00FF
229 
230 /* MIADDR* nibble definitions */
231 #define  MCI_MEMORY_DATA_BYTE0          0x000
232 #define  MCI_MEMORY_DATA_BYTE1          0x100
233 #define  MCI_MEMORY_DATA_BYTE2          0x200
234 #define  MCI_MEMORY_DATA_BYTE3          0x300
235 #define  MCI_MEMORY_ADDRESS_BYTE2       0x400
236 #define  MCI_MEMORY_ADDRESS_BYTE1       0x500
237 #define  MCI_MEMORY_ADDRESS_BYTE0       0x600
238 #define  MCI_REGISTER_DATA_BYTE0        0x800
239 #define  MCI_REGISTER_DATA_BYTE1        0x900
240 #define  MCI_REGISTER_DATA_BYTE2        0xA00
241 #define  MCI_REGISTER_DATA_BYTE3        0xB00
242 #define  MCI_REGISTER_ADDRESS_BYTE0     0xC00
243 #define  MCI_REGISTER_ADDRESS_BYTE1     0xD00
244 #define  MCI_REGISTER_MODE              0xE00
245 
246 /* Read and write modes */
247 #define  MCI_MODE_REGISTER_READ         0
248 #define  MCI_MODE_REGISTER_WRITE        1
249 #define  MCI_MODE_MEMORY_READ           0
250 #define  MCI_MODE_MEMORY_WRITE          0x40
251 
252 /*** Bit definitions for MC417_CTL register ****
253  bits 31-6   bits 5-4   bit 3    bits 2-1       Bit 0
254 +--------+-------------+--------+--------------+------------+
255 |Reserved|MC417_SPD_CTL|Reserved|MC417_GPIO_SEL|UART_GPIO_EN|
256 +--------+-------------+--------+--------------+------------+
257 ***/
258 #define MC417_SPD_CTL(x)	(((x) << 4) & 0x00000030)
259 #define MC417_GPIO_SEL(x)	(((x) << 1) & 0x00000006)
260 #define MC417_UART_GPIO_EN	0x00000001
261 
262 /* Values for speed control */
263 #define MC417_SPD_CTL_SLOW	0x1
264 #define MC417_SPD_CTL_MEDIUM	0x0
265 #define MC417_SPD_CTL_FAST	0x3     /* b'1x, but we use b'11 */
266 
267 /* Values for GPIO select */
268 #define MC417_GPIO_SEL_GPIO3	0x3
269 #define MC417_GPIO_SEL_GPIO2	0x2
270 #define MC417_GPIO_SEL_GPIO1	0x1
271 #define MC417_GPIO_SEL_GPIO0	0x0
272 
273 void cx23885_mc417_init(struct cx23885_dev *dev)
274 {
275 	u32 regval;
276 
277 	dprintk(2, "%s()\n", __func__);
278 
279 	/* Configure MC417_CTL register to defaults. */
280 	regval = MC417_SPD_CTL(MC417_SPD_CTL_FAST)	|
281 		 MC417_GPIO_SEL(MC417_GPIO_SEL_GPIO3)	|
282 		 MC417_UART_GPIO_EN;
283 	cx_write(MC417_CTL, regval);
284 
285 	/* Configure MC417_OEN to defaults. */
286 	regval = MC417_MIRDY;
287 	cx_write(MC417_OEN, regval);
288 
289 	/* Configure MC417_RWD to defaults. */
290 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS;
291 	cx_write(MC417_RWD, regval);
292 }
293 
294 static int mc417_wait_ready(struct cx23885_dev *dev)
295 {
296 	u32 mi_ready;
297 	unsigned long timeout = jiffies + msecs_to_jiffies(1);
298 
299 	for (;;) {
300 		mi_ready = cx_read(MC417_RWD) & MC417_MIRDY;
301 		if (mi_ready != 0)
302 			return 0;
303 		if (time_after(jiffies, timeout))
304 			return -1;
305 		udelay(1);
306 	}
307 }
308 
309 int mc417_register_write(struct cx23885_dev *dev, u16 address, u32 value)
310 {
311 	u32 regval;
312 
313 	/* Enable MC417 GPIO outputs except for MC417_MIRDY,
314 	 * which is an input.
315 	 */
316 	cx_write(MC417_OEN, MC417_MIRDY);
317 
318 	/* Write data byte 0 */
319 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE0 |
320 		(value & 0x000000FF);
321 	cx_write(MC417_RWD, regval);
322 
323 	/* Transition CS/WR to effect write transaction across bus. */
324 	regval |= MC417_MICS | MC417_MIWR;
325 	cx_write(MC417_RWD, regval);
326 
327 	/* Write data byte 1 */
328 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE1 |
329 		((value >> 8) & 0x000000FF);
330 	cx_write(MC417_RWD, regval);
331 	regval |= MC417_MICS | MC417_MIWR;
332 	cx_write(MC417_RWD, regval);
333 
334 	/* Write data byte 2 */
335 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE2 |
336 		((value >> 16) & 0x000000FF);
337 	cx_write(MC417_RWD, regval);
338 	regval |= MC417_MICS | MC417_MIWR;
339 	cx_write(MC417_RWD, regval);
340 
341 	/* Write data byte 3 */
342 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE3 |
343 		((value >> 24) & 0x000000FF);
344 	cx_write(MC417_RWD, regval);
345 	regval |= MC417_MICS | MC417_MIWR;
346 	cx_write(MC417_RWD, regval);
347 
348 	/* Write address byte 0 */
349 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_ADDRESS_BYTE0 |
350 		(address & 0xFF);
351 	cx_write(MC417_RWD, regval);
352 	regval |= MC417_MICS | MC417_MIWR;
353 	cx_write(MC417_RWD, regval);
354 
355 	/* Write address byte 1 */
356 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_ADDRESS_BYTE1 |
357 		((address >> 8) & 0xFF);
358 	cx_write(MC417_RWD, regval);
359 	regval |= MC417_MICS | MC417_MIWR;
360 	cx_write(MC417_RWD, regval);
361 
362 	/* Indicate that this is a write. */
363 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_MODE |
364 		MCI_MODE_REGISTER_WRITE;
365 	cx_write(MC417_RWD, regval);
366 	regval |= MC417_MICS | MC417_MIWR;
367 	cx_write(MC417_RWD, regval);
368 
369 	/* Wait for the trans to complete (MC417_MIRDY asserted). */
370 	return mc417_wait_ready(dev);
371 }
372 
373 int mc417_register_read(struct cx23885_dev *dev, u16 address, u32 *value)
374 {
375 	int retval;
376 	u32 regval;
377 	u32 tempval;
378 	u32 dataval;
379 
380 	/* Enable MC417 GPIO outputs except for MC417_MIRDY,
381 	 * which is an input.
382 	 */
383 	cx_write(MC417_OEN, MC417_MIRDY);
384 
385 	/* Write address byte 0 */
386 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_ADDRESS_BYTE0 |
387 		((address & 0x00FF));
388 	cx_write(MC417_RWD, regval);
389 	regval |= MC417_MICS | MC417_MIWR;
390 	cx_write(MC417_RWD, regval);
391 
392 	/* Write address byte 1 */
393 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_ADDRESS_BYTE1 |
394 		((address >> 8) & 0xFF);
395 	cx_write(MC417_RWD, regval);
396 	regval |= MC417_MICS | MC417_MIWR;
397 	cx_write(MC417_RWD, regval);
398 
399 	/* Indicate that this is a register read. */
400 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_MODE |
401 		MCI_MODE_REGISTER_READ;
402 	cx_write(MC417_RWD, regval);
403 	regval |= MC417_MICS | MC417_MIWR;
404 	cx_write(MC417_RWD, regval);
405 
406 	/* Wait for the trans to complete (MC417_MIRDY asserted). */
407 	retval = mc417_wait_ready(dev);
408 
409 	/* switch the DAT0-7 GPIO[10:3] to input mode */
410 	cx_write(MC417_OEN, MC417_MIRDY | MC417_MIDATA);
411 
412 	/* Read data byte 0 */
413 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE0;
414 	cx_write(MC417_RWD, regval);
415 
416 	/* Transition RD to effect read transaction across bus.
417 	 * Transition 0x5000 -> 0x9000 correct (RD/RDY -> WR/RDY)?
418 	 * Should it be 0x9000 -> 0xF000 (also why is RDY being set, its
419 	 * input only...)
420 	 */
421 	regval = MC417_MIWR | MC417_MIRDY | MCI_REGISTER_DATA_BYTE0;
422 	cx_write(MC417_RWD, regval);
423 
424 	/* Collect byte */
425 	tempval = cx_read(MC417_RWD);
426 	dataval = tempval & 0x000000FF;
427 
428 	/* Bring CS and RD high. */
429 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
430 	cx_write(MC417_RWD, regval);
431 
432 	/* Read data byte 1 */
433 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE1;
434 	cx_write(MC417_RWD, regval);
435 	regval = MC417_MIWR | MC417_MIRDY | MCI_REGISTER_DATA_BYTE1;
436 	cx_write(MC417_RWD, regval);
437 	tempval = cx_read(MC417_RWD);
438 	dataval |= ((tempval & 0x000000FF) << 8);
439 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
440 	cx_write(MC417_RWD, regval);
441 
442 	/* Read data byte 2 */
443 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE2;
444 	cx_write(MC417_RWD, regval);
445 	regval = MC417_MIWR | MC417_MIRDY | MCI_REGISTER_DATA_BYTE2;
446 	cx_write(MC417_RWD, regval);
447 	tempval = cx_read(MC417_RWD);
448 	dataval |= ((tempval & 0x000000FF) << 16);
449 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
450 	cx_write(MC417_RWD, regval);
451 
452 	/* Read data byte 3 */
453 	regval = MC417_MIRD | MC417_MIRDY | MCI_REGISTER_DATA_BYTE3;
454 	cx_write(MC417_RWD, regval);
455 	regval = MC417_MIWR | MC417_MIRDY | MCI_REGISTER_DATA_BYTE3;
456 	cx_write(MC417_RWD, regval);
457 	tempval = cx_read(MC417_RWD);
458 	dataval |= ((tempval & 0x000000FF) << 24);
459 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
460 	cx_write(MC417_RWD, regval);
461 
462 	*value  = dataval;
463 
464 	return retval;
465 }
466 
467 int mc417_memory_write(struct cx23885_dev *dev, u32 address, u32 value)
468 {
469 	u32 regval;
470 
471 	/* Enable MC417 GPIO outputs except for MC417_MIRDY,
472 	 * which is an input.
473 	 */
474 	cx_write(MC417_OEN, MC417_MIRDY);
475 
476 	/* Write data byte 0 */
477 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE0 |
478 		(value & 0x000000FF);
479 	cx_write(MC417_RWD, regval);
480 
481 	/* Transition CS/WR to effect write transaction across bus. */
482 	regval |= MC417_MICS | MC417_MIWR;
483 	cx_write(MC417_RWD, regval);
484 
485 	/* Write data byte 1 */
486 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE1 |
487 		((value >> 8) & 0x000000FF);
488 	cx_write(MC417_RWD, regval);
489 	regval |= MC417_MICS | MC417_MIWR;
490 	cx_write(MC417_RWD, regval);
491 
492 	/* Write data byte 2 */
493 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE2 |
494 		((value >> 16) & 0x000000FF);
495 	cx_write(MC417_RWD, regval);
496 	regval |= MC417_MICS | MC417_MIWR;
497 	cx_write(MC417_RWD, regval);
498 
499 	/* Write data byte 3 */
500 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE3 |
501 		((value >> 24) & 0x000000FF);
502 	cx_write(MC417_RWD, regval);
503 	regval |= MC417_MICS | MC417_MIWR;
504 	cx_write(MC417_RWD, regval);
505 
506 	/* Write address byte 2 */
507 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE2 |
508 		MCI_MODE_MEMORY_WRITE | ((address >> 16) & 0x3F);
509 	cx_write(MC417_RWD, regval);
510 	regval |= MC417_MICS | MC417_MIWR;
511 	cx_write(MC417_RWD, regval);
512 
513 	/* Write address byte 1 */
514 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE1 |
515 		((address >> 8) & 0xFF);
516 	cx_write(MC417_RWD, regval);
517 	regval |= MC417_MICS | MC417_MIWR;
518 	cx_write(MC417_RWD, regval);
519 
520 	/* Write address byte 0 */
521 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE0 |
522 		(address & 0xFF);
523 	cx_write(MC417_RWD, regval);
524 	regval |= MC417_MICS | MC417_MIWR;
525 	cx_write(MC417_RWD, regval);
526 
527 	/* Wait for the trans to complete (MC417_MIRDY asserted). */
528 	return mc417_wait_ready(dev);
529 }
530 
531 int mc417_memory_read(struct cx23885_dev *dev, u32 address, u32 *value)
532 {
533 	int retval;
534 	u32 regval;
535 	u32 tempval;
536 	u32 dataval;
537 
538 	/* Enable MC417 GPIO outputs except for MC417_MIRDY,
539 	 * which is an input.
540 	 */
541 	cx_write(MC417_OEN, MC417_MIRDY);
542 
543 	/* Write address byte 2 */
544 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE2 |
545 		MCI_MODE_MEMORY_READ | ((address >> 16) & 0x3F);
546 	cx_write(MC417_RWD, regval);
547 	regval |= MC417_MICS | MC417_MIWR;
548 	cx_write(MC417_RWD, regval);
549 
550 	/* Write address byte 1 */
551 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE1 |
552 		((address >> 8) & 0xFF);
553 	cx_write(MC417_RWD, regval);
554 	regval |= MC417_MICS | MC417_MIWR;
555 	cx_write(MC417_RWD, regval);
556 
557 	/* Write address byte 0 */
558 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_ADDRESS_BYTE0 |
559 		(address & 0xFF);
560 	cx_write(MC417_RWD, regval);
561 	regval |= MC417_MICS | MC417_MIWR;
562 	cx_write(MC417_RWD, regval);
563 
564 	/* Wait for the trans to complete (MC417_MIRDY asserted). */
565 	retval = mc417_wait_ready(dev);
566 
567 	/* switch the DAT0-7 GPIO[10:3] to input mode */
568 	cx_write(MC417_OEN, MC417_MIRDY | MC417_MIDATA);
569 
570 	/* Read data byte 3 */
571 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE3;
572 	cx_write(MC417_RWD, regval);
573 
574 	/* Transition RD to effect read transaction across bus. */
575 	regval = MC417_MIWR | MC417_MIRDY | MCI_MEMORY_DATA_BYTE3;
576 	cx_write(MC417_RWD, regval);
577 
578 	/* Collect byte */
579 	tempval = cx_read(MC417_RWD);
580 	dataval = ((tempval & 0x000000FF) << 24);
581 
582 	/* Bring CS and RD high. */
583 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
584 	cx_write(MC417_RWD, regval);
585 
586 	/* Read data byte 2 */
587 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE2;
588 	cx_write(MC417_RWD, regval);
589 	regval = MC417_MIWR | MC417_MIRDY | MCI_MEMORY_DATA_BYTE2;
590 	cx_write(MC417_RWD, regval);
591 	tempval = cx_read(MC417_RWD);
592 	dataval |= ((tempval & 0x000000FF) << 16);
593 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
594 	cx_write(MC417_RWD, regval);
595 
596 	/* Read data byte 1 */
597 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE1;
598 	cx_write(MC417_RWD, regval);
599 	regval = MC417_MIWR | MC417_MIRDY | MCI_MEMORY_DATA_BYTE1;
600 	cx_write(MC417_RWD, regval);
601 	tempval = cx_read(MC417_RWD);
602 	dataval |= ((tempval & 0x000000FF) << 8);
603 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
604 	cx_write(MC417_RWD, regval);
605 
606 	/* Read data byte 0 */
607 	regval = MC417_MIRD | MC417_MIRDY | MCI_MEMORY_DATA_BYTE0;
608 	cx_write(MC417_RWD, regval);
609 	regval = MC417_MIWR | MC417_MIRDY | MCI_MEMORY_DATA_BYTE0;
610 	cx_write(MC417_RWD, regval);
611 	tempval = cx_read(MC417_RWD);
612 	dataval |= (tempval & 0x000000FF);
613 	regval = MC417_MIWR | MC417_MIRD | MC417_MICS | MC417_MIRDY;
614 	cx_write(MC417_RWD, regval);
615 
616 	*value  = dataval;
617 
618 	return retval;
619 }
620 
621 void mc417_gpio_set(struct cx23885_dev *dev, u32 mask)
622 {
623 	u32 val;
624 
625 	/* Set the gpio value */
626 	mc417_register_read(dev, 0x900C, &val);
627 	val |= (mask & 0x000ffff);
628 	mc417_register_write(dev, 0x900C, val);
629 }
630 
631 void mc417_gpio_clear(struct cx23885_dev *dev, u32 mask)
632 {
633 	u32 val;
634 
635 	/* Clear the gpio value */
636 	mc417_register_read(dev, 0x900C, &val);
637 	val &= ~(mask & 0x0000ffff);
638 	mc417_register_write(dev, 0x900C, val);
639 }
640 
641 void mc417_gpio_enable(struct cx23885_dev *dev, u32 mask, int asoutput)
642 {
643 	u32 val;
644 
645 	/* Enable GPIO direction bits */
646 	mc417_register_read(dev, 0x9020, &val);
647 	if (asoutput)
648 		val |= (mask & 0x0000ffff);
649 	else
650 		val &= ~(mask & 0x0000ffff);
651 
652 	mc417_register_write(dev, 0x9020, val);
653 }
654 /* ------------------------------------------------------------------ */
655 
656 /* MPEG encoder API */
657 static char *cmd_to_str(int cmd)
658 {
659 	switch (cmd) {
660 	case CX2341X_ENC_PING_FW:
661 		return  "PING_FW";
662 	case CX2341X_ENC_START_CAPTURE:
663 		return  "START_CAPTURE";
664 	case CX2341X_ENC_STOP_CAPTURE:
665 		return  "STOP_CAPTURE";
666 	case CX2341X_ENC_SET_AUDIO_ID:
667 		return  "SET_AUDIO_ID";
668 	case CX2341X_ENC_SET_VIDEO_ID:
669 		return  "SET_VIDEO_ID";
670 	case CX2341X_ENC_SET_PCR_ID:
671 		return  "SET_PCR_ID";
672 	case CX2341X_ENC_SET_FRAME_RATE:
673 		return  "SET_FRAME_RATE";
674 	case CX2341X_ENC_SET_FRAME_SIZE:
675 		return  "SET_FRAME_SIZE";
676 	case CX2341X_ENC_SET_BIT_RATE:
677 		return  "SET_BIT_RATE";
678 	case CX2341X_ENC_SET_GOP_PROPERTIES:
679 		return  "SET_GOP_PROPERTIES";
680 	case CX2341X_ENC_SET_ASPECT_RATIO:
681 		return  "SET_ASPECT_RATIO";
682 	case CX2341X_ENC_SET_DNR_FILTER_MODE:
683 		return  "SET_DNR_FILTER_MODE";
684 	case CX2341X_ENC_SET_DNR_FILTER_PROPS:
685 		return  "SET_DNR_FILTER_PROPS";
686 	case CX2341X_ENC_SET_CORING_LEVELS:
687 		return  "SET_CORING_LEVELS";
688 	case CX2341X_ENC_SET_SPATIAL_FILTER_TYPE:
689 		return  "SET_SPATIAL_FILTER_TYPE";
690 	case CX2341X_ENC_SET_VBI_LINE:
691 		return  "SET_VBI_LINE";
692 	case CX2341X_ENC_SET_STREAM_TYPE:
693 		return  "SET_STREAM_TYPE";
694 	case CX2341X_ENC_SET_OUTPUT_PORT:
695 		return  "SET_OUTPUT_PORT";
696 	case CX2341X_ENC_SET_AUDIO_PROPERTIES:
697 		return  "SET_AUDIO_PROPERTIES";
698 	case CX2341X_ENC_HALT_FW:
699 		return  "HALT_FW";
700 	case CX2341X_ENC_GET_VERSION:
701 		return  "GET_VERSION";
702 	case CX2341X_ENC_SET_GOP_CLOSURE:
703 		return  "SET_GOP_CLOSURE";
704 	case CX2341X_ENC_GET_SEQ_END:
705 		return  "GET_SEQ_END";
706 	case CX2341X_ENC_SET_PGM_INDEX_INFO:
707 		return  "SET_PGM_INDEX_INFO";
708 	case CX2341X_ENC_SET_VBI_CONFIG:
709 		return  "SET_VBI_CONFIG";
710 	case CX2341X_ENC_SET_DMA_BLOCK_SIZE:
711 		return  "SET_DMA_BLOCK_SIZE";
712 	case CX2341X_ENC_GET_PREV_DMA_INFO_MB_10:
713 		return  "GET_PREV_DMA_INFO_MB_10";
714 	case CX2341X_ENC_GET_PREV_DMA_INFO_MB_9:
715 		return  "GET_PREV_DMA_INFO_MB_9";
716 	case CX2341X_ENC_SCHED_DMA_TO_HOST:
717 		return  "SCHED_DMA_TO_HOST";
718 	case CX2341X_ENC_INITIALIZE_INPUT:
719 		return  "INITIALIZE_INPUT";
720 	case CX2341X_ENC_SET_FRAME_DROP_RATE:
721 		return  "SET_FRAME_DROP_RATE";
722 	case CX2341X_ENC_PAUSE_ENCODER:
723 		return  "PAUSE_ENCODER";
724 	case CX2341X_ENC_REFRESH_INPUT:
725 		return  "REFRESH_INPUT";
726 	case CX2341X_ENC_SET_COPYRIGHT:
727 		return  "SET_COPYRIGHT";
728 	case CX2341X_ENC_SET_EVENT_NOTIFICATION:
729 		return  "SET_EVENT_NOTIFICATION";
730 	case CX2341X_ENC_SET_NUM_VSYNC_LINES:
731 		return  "SET_NUM_VSYNC_LINES";
732 	case CX2341X_ENC_SET_PLACEHOLDER:
733 		return  "SET_PLACEHOLDER";
734 	case CX2341X_ENC_MUTE_VIDEO:
735 		return  "MUTE_VIDEO";
736 	case CX2341X_ENC_MUTE_AUDIO:
737 		return  "MUTE_AUDIO";
738 	case CX2341X_ENC_MISC:
739 		return  "MISC";
740 	default:
741 		return "UNKNOWN";
742 	}
743 }
744 
745 static int cx23885_mbox_func(void *priv,
746 			     u32 command,
747 			     int in,
748 			     int out,
749 			     u32 data[CX2341X_MBOX_MAX_DATA])
750 {
751 	struct cx23885_dev *dev = priv;
752 	unsigned long timeout;
753 	u32 value, flag, retval = 0;
754 	int i;
755 
756 	dprintk(3, "%s: command(0x%X) = %s\n", __func__, command,
757 		cmd_to_str(command));
758 
759 	/* this may not be 100% safe if we can't read any memory location
760 	   without side effects */
761 	mc417_memory_read(dev, dev->cx23417_mailbox - 4, &value);
762 	if (value != 0x12345678) {
763 		pr_err("Firmware and/or mailbox pointer not initialized or corrupted, signature = 0x%x, cmd = %s\n",
764 			value, cmd_to_str(command));
765 		return -1;
766 	}
767 
768 	/* This read looks at 32 bits, but flag is only 8 bits.
769 	 * Seems we also bail if CMD or TIMEOUT bytes are set???
770 	 */
771 	mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
772 	if (flag) {
773 		pr_err("ERROR: Mailbox appears to be in use (%x), cmd = %s\n",
774 		       flag, cmd_to_str(command));
775 		return -1;
776 	}
777 
778 	flag |= 1; /* tell 'em we're working on it */
779 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
780 
781 	/* write command + args + fill remaining with zeros */
782 	/* command code */
783 	mc417_memory_write(dev, dev->cx23417_mailbox + 1, command);
784 	mc417_memory_write(dev, dev->cx23417_mailbox + 3,
785 		IVTV_API_STD_TIMEOUT); /* timeout */
786 	for (i = 0; i < in; i++) {
787 		mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, data[i]);
788 		dprintk(3, "API Input %d = %d\n", i, data[i]);
789 	}
790 	for (; i < CX2341X_MBOX_MAX_DATA; i++)
791 		mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, 0);
792 
793 	flag |= 3; /* tell 'em we're done writing */
794 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
795 
796 	/* wait for firmware to handle the API command */
797 	timeout = jiffies + msecs_to_jiffies(10);
798 	for (;;) {
799 		mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
800 		if (0 != (flag & 4))
801 			break;
802 		if (time_after(jiffies, timeout)) {
803 			pr_err("ERROR: API Mailbox timeout\n");
804 			return -1;
805 		}
806 		udelay(10);
807 	}
808 
809 	/* read output values */
810 	for (i = 0; i < out; i++) {
811 		mc417_memory_read(dev, dev->cx23417_mailbox + 4 + i, data + i);
812 		dprintk(3, "API Output %d = %d\n", i, data[i]);
813 	}
814 
815 	mc417_memory_read(dev, dev->cx23417_mailbox + 2, &retval);
816 	dprintk(3, "API result = %d\n", retval);
817 
818 	flag = 0;
819 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
820 
821 	return retval;
822 }
823 
824 /* We don't need to call the API often, so using just one
825  * mailbox will probably suffice
826  */
827 static int cx23885_api_cmd(struct cx23885_dev *dev,
828 			   u32 command,
829 			   u32 inputcnt,
830 			   u32 outputcnt,
831 			   ...)
832 {
833 	u32 data[CX2341X_MBOX_MAX_DATA];
834 	va_list vargs;
835 	int i, err;
836 
837 	dprintk(3, "%s() cmds = 0x%08x\n", __func__, command);
838 
839 	va_start(vargs, outputcnt);
840 	for (i = 0; i < inputcnt; i++)
841 		data[i] = va_arg(vargs, int);
842 
843 	err = cx23885_mbox_func(dev, command, inputcnt, outputcnt, data);
844 	for (i = 0; i < outputcnt; i++) {
845 		int *vptr = va_arg(vargs, int *);
846 		*vptr = data[i];
847 	}
848 	va_end(vargs);
849 
850 	return err;
851 }
852 
853 static int cx23885_api_func(void *priv, u32 cmd, int in, int out, u32 data[CX2341X_MBOX_MAX_DATA])
854 {
855 	return cx23885_mbox_func(priv, cmd, in, out, data);
856 }
857 
858 static int cx23885_find_mailbox(struct cx23885_dev *dev)
859 {
860 	u32 signature[4] = {
861 		0x12345678, 0x34567812, 0x56781234, 0x78123456
862 	};
863 	int signaturecnt = 0;
864 	u32 value;
865 	int i;
866 
867 	dprintk(2, "%s()\n", __func__);
868 
869 	for (i = 0; i < CX23885_FIRM_IMAGE_SIZE; i++) {
870 		mc417_memory_read(dev, i, &value);
871 		if (value == signature[signaturecnt])
872 			signaturecnt++;
873 		else
874 			signaturecnt = 0;
875 		if (4 == signaturecnt) {
876 			dprintk(1, "Mailbox signature found at 0x%x\n", i+1);
877 			return i+1;
878 		}
879 	}
880 	pr_err("Mailbox signature values not found!\n");
881 	return -1;
882 }
883 
884 static int cx23885_load_firmware(struct cx23885_dev *dev)
885 {
886 	static const unsigned char magic[8] = {
887 		0xa7, 0x0d, 0x00, 0x00, 0x66, 0xbb, 0x55, 0xaa
888 	};
889 	const struct firmware *firmware;
890 	int i, retval = 0;
891 	u32 value = 0;
892 	u32 gpio_output = 0;
893 	u32 gpio_value;
894 	u32 checksum = 0;
895 	u32 *dataptr;
896 
897 	dprintk(2, "%s()\n", __func__);
898 
899 	/* Save GPIO settings before reset of APU */
900 	retval |= mc417_memory_read(dev, 0x9020, &gpio_output);
901 	retval |= mc417_memory_read(dev, 0x900C, &gpio_value);
902 
903 	retval  = mc417_register_write(dev,
904 		IVTV_REG_VPU, 0xFFFFFFED);
905 	retval |= mc417_register_write(dev,
906 		IVTV_REG_HW_BLOCKS, IVTV_CMD_HW_BLOCKS_RST);
907 	retval |= mc417_register_write(dev,
908 		IVTV_REG_ENC_SDRAM_REFRESH, 0x80000800);
909 	retval |= mc417_register_write(dev,
910 		IVTV_REG_ENC_SDRAM_PRECHARGE, 0x1A);
911 	retval |= mc417_register_write(dev,
912 		IVTV_REG_APU, 0);
913 
914 	if (retval != 0) {
915 		pr_err("%s: Error with mc417_register_write\n",
916 			__func__);
917 		return -1;
918 	}
919 
920 	retval = request_firmware(&firmware, CX23885_FIRM_IMAGE_NAME,
921 				  &dev->pci->dev);
922 
923 	if (retval != 0) {
924 		pr_err("ERROR: Hotplug firmware request failed (%s).\n",
925 		       CX23885_FIRM_IMAGE_NAME);
926 		pr_err("Please fix your hotplug setup, the board will not work without firmware loaded!\n");
927 		return -1;
928 	}
929 
930 	if (firmware->size != CX23885_FIRM_IMAGE_SIZE) {
931 		pr_err("ERROR: Firmware size mismatch (have %zu, expected %d)\n",
932 		       firmware->size, CX23885_FIRM_IMAGE_SIZE);
933 		release_firmware(firmware);
934 		return -1;
935 	}
936 
937 	if (0 != memcmp(firmware->data, magic, 8)) {
938 		pr_err("ERROR: Firmware magic mismatch, wrong file?\n");
939 		release_firmware(firmware);
940 		return -1;
941 	}
942 
943 	/* transfer to the chip */
944 	dprintk(2, "Loading firmware ...\n");
945 	dataptr = (u32 *)firmware->data;
946 	for (i = 0; i < (firmware->size >> 2); i++) {
947 		value = *dataptr;
948 		checksum += ~value;
949 		if (mc417_memory_write(dev, i, value) != 0) {
950 			pr_err("ERROR: Loading firmware failed!\n");
951 			release_firmware(firmware);
952 			return -1;
953 		}
954 		dataptr++;
955 	}
956 
957 	/* read back to verify with the checksum */
958 	dprintk(1, "Verifying firmware ...\n");
959 	for (i--; i >= 0; i--) {
960 		if (mc417_memory_read(dev, i, &value) != 0) {
961 			pr_err("ERROR: Reading firmware failed!\n");
962 			release_firmware(firmware);
963 			return -1;
964 		}
965 		checksum -= ~value;
966 	}
967 	if (checksum) {
968 		pr_err("ERROR: Firmware load failed (checksum mismatch).\n");
969 		release_firmware(firmware);
970 		return -1;
971 	}
972 	release_firmware(firmware);
973 	dprintk(1, "Firmware upload successful.\n");
974 
975 	retval |= mc417_register_write(dev, IVTV_REG_HW_BLOCKS,
976 		IVTV_CMD_HW_BLOCKS_RST);
977 
978 	/* F/W power up disturbs the GPIOs, restore state */
979 	retval |= mc417_register_write(dev, 0x9020, gpio_output);
980 	retval |= mc417_register_write(dev, 0x900C, gpio_value);
981 
982 	retval |= mc417_register_read(dev, IVTV_REG_VPU, &value);
983 	retval |= mc417_register_write(dev, IVTV_REG_VPU, value & 0xFFFFFFE8);
984 
985 	/* Hardcoded GPIO's here */
986 	retval |= mc417_register_write(dev, 0x9020, 0x4000);
987 	retval |= mc417_register_write(dev, 0x900C, 0x4000);
988 
989 	mc417_register_read(dev, 0x9020, &gpio_output);
990 	mc417_register_read(dev, 0x900C, &gpio_value);
991 
992 	if (retval < 0)
993 		pr_err("%s: Error with mc417_register_write\n",
994 			__func__);
995 	return 0;
996 }
997 
998 void cx23885_417_check_encoder(struct cx23885_dev *dev)
999 {
1000 	u32 status, seq;
1001 
1002 	status = seq = 0;
1003 	cx23885_api_cmd(dev, CX2341X_ENC_GET_SEQ_END, 0, 2, &status, &seq);
1004 	dprintk(1, "%s() status = %d, seq = %d\n", __func__, status, seq);
1005 }
1006 
1007 static void cx23885_codec_settings(struct cx23885_dev *dev)
1008 {
1009 	dprintk(1, "%s()\n", __func__);
1010 
1011 	/* Dynamically change the height based on video standard */
1012 	if (dev->encodernorm.id & V4L2_STD_525_60)
1013 		dev->ts1.height = 480;
1014 	else
1015 		dev->ts1.height = 576;
1016 
1017 	/* assign frame size */
1018 	cx23885_api_cmd(dev, CX2341X_ENC_SET_FRAME_SIZE, 2, 0,
1019 				dev->ts1.height, dev->ts1.width);
1020 
1021 	dev->cxhdl.width = dev->ts1.width;
1022 	dev->cxhdl.height = dev->ts1.height;
1023 	dev->cxhdl.is_50hz =
1024 		(dev->encodernorm.id & V4L2_STD_625_50) != 0;
1025 
1026 	cx2341x_handler_setup(&dev->cxhdl);
1027 
1028 	cx23885_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 3, 1);
1029 	cx23885_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 4, 1);
1030 }
1031 
1032 static int cx23885_initialize_codec(struct cx23885_dev *dev, int startencoder)
1033 {
1034 	int version;
1035 	int retval;
1036 	u32 i, data[7];
1037 
1038 	dprintk(1, "%s()\n", __func__);
1039 
1040 	retval = cx23885_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
1041 	if (retval < 0) {
1042 		dprintk(2, "%s() PING OK\n", __func__);
1043 		retval = cx23885_load_firmware(dev);
1044 		if (retval < 0) {
1045 			pr_err("%s() f/w load failed\n", __func__);
1046 			return retval;
1047 		}
1048 		retval = cx23885_find_mailbox(dev);
1049 		if (retval < 0) {
1050 			pr_err("%s() mailbox < 0, error\n",
1051 				__func__);
1052 			return -1;
1053 		}
1054 		dev->cx23417_mailbox = retval;
1055 		retval = cx23885_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0);
1056 		if (retval < 0) {
1057 			pr_err("ERROR: cx23417 firmware ping failed!\n");
1058 			return -1;
1059 		}
1060 		retval = cx23885_api_cmd(dev, CX2341X_ENC_GET_VERSION, 0, 1,
1061 			&version);
1062 		if (retval < 0) {
1063 			pr_err("ERROR: cx23417 firmware get encoder :version failed!\n");
1064 			return -1;
1065 		}
1066 		dprintk(1, "cx23417 firmware version is 0x%08x\n", version);
1067 		msleep(200);
1068 	}
1069 
1070 	cx23885_codec_settings(dev);
1071 	msleep(60);
1072 
1073 	cx23885_api_cmd(dev, CX2341X_ENC_SET_NUM_VSYNC_LINES, 2, 0,
1074 		CX23885_FIELD1_SAA7115, CX23885_FIELD2_SAA7115);
1075 	cx23885_api_cmd(dev, CX2341X_ENC_SET_PLACEHOLDER, 12, 0,
1076 		CX23885_CUSTOM_EXTENSION_USR_DATA, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1077 		0, 0);
1078 
1079 	/* Setup to capture VBI */
1080 	data[0] = 0x0001BD00;
1081 	data[1] = 1;          /* frames per interrupt */
1082 	data[2] = 4;          /* total bufs */
1083 	data[3] = 0x91559155; /* start codes */
1084 	data[4] = 0x206080C0; /* stop codes */
1085 	data[5] = 6;          /* lines */
1086 	data[6] = 64;         /* BPL */
1087 
1088 	cx23885_api_cmd(dev, CX2341X_ENC_SET_VBI_CONFIG, 7, 0, data[0], data[1],
1089 		data[2], data[3], data[4], data[5], data[6]);
1090 
1091 	for (i = 2; i <= 24; i++) {
1092 		int valid;
1093 
1094 		valid = ((i >= 19) && (i <= 21));
1095 		cx23885_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0, i,
1096 				valid, 0 , 0, 0);
1097 		cx23885_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0,
1098 				i | 0x80000000, valid, 0, 0, 0);
1099 	}
1100 
1101 	cx23885_api_cmd(dev, CX2341X_ENC_MUTE_AUDIO, 1, 0, CX23885_UNMUTE);
1102 	msleep(60);
1103 
1104 	/* initialize the video input */
1105 	cx23885_api_cmd(dev, CX2341X_ENC_INITIALIZE_INPUT, 0, 0);
1106 	msleep(60);
1107 
1108 	/* Enable VIP style pixel invalidation so we work with scaled mode */
1109 	mc417_memory_write(dev, 2120, 0x00000080);
1110 
1111 	/* start capturing to the host interface */
1112 	if (startencoder) {
1113 		cx23885_api_cmd(dev, CX2341X_ENC_START_CAPTURE, 2, 0,
1114 			CX23885_MPEG_CAPTURE, CX23885_RAW_BITS_NONE);
1115 		msleep(10);
1116 	}
1117 
1118 	return 0;
1119 }
1120 
1121 /* ------------------------------------------------------------------ */
1122 
1123 static int queue_setup(struct vb2_queue *q,
1124 			   unsigned int *num_buffers, unsigned int *num_planes,
1125 			   unsigned int sizes[], struct device *alloc_devs[])
1126 {
1127 	struct cx23885_dev *dev = q->drv_priv;
1128 
1129 	dev->ts1.ts_packet_size  = mpeglinesize;
1130 	dev->ts1.ts_packet_count = mpeglines;
1131 	*num_planes = 1;
1132 	sizes[0] = mpeglinesize * mpeglines;
1133 	*num_buffers = mpegbufs;
1134 	return 0;
1135 }
1136 
1137 static int buffer_prepare(struct vb2_buffer *vb)
1138 {
1139 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1140 	struct cx23885_dev *dev = vb->vb2_queue->drv_priv;
1141 	struct cx23885_buffer *buf =
1142 		container_of(vbuf, struct cx23885_buffer, vb);
1143 
1144 	return cx23885_buf_prepare(buf, &dev->ts1);
1145 }
1146 
1147 static void buffer_finish(struct vb2_buffer *vb)
1148 {
1149 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1150 	struct cx23885_dev *dev = vb->vb2_queue->drv_priv;
1151 	struct cx23885_buffer *buf = container_of(vbuf,
1152 		struct cx23885_buffer, vb);
1153 
1154 	cx23885_free_buffer(dev, buf);
1155 }
1156 
1157 static void buffer_queue(struct vb2_buffer *vb)
1158 {
1159 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1160 	struct cx23885_dev *dev = vb->vb2_queue->drv_priv;
1161 	struct cx23885_buffer   *buf = container_of(vbuf,
1162 		struct cx23885_buffer, vb);
1163 
1164 	cx23885_buf_queue(&dev->ts1, buf);
1165 }
1166 
1167 static int cx23885_start_streaming(struct vb2_queue *q, unsigned int count)
1168 {
1169 	struct cx23885_dev *dev = q->drv_priv;
1170 	struct cx23885_dmaqueue *dmaq = &dev->ts1.mpegq;
1171 	unsigned long flags;
1172 	int ret;
1173 
1174 	ret = cx23885_initialize_codec(dev, 1);
1175 	if (ret == 0) {
1176 		struct cx23885_buffer *buf = list_entry(dmaq->active.next,
1177 			struct cx23885_buffer, queue);
1178 
1179 		cx23885_start_dma(&dev->ts1, dmaq, buf);
1180 		return 0;
1181 	}
1182 	spin_lock_irqsave(&dev->slock, flags);
1183 	while (!list_empty(&dmaq->active)) {
1184 		struct cx23885_buffer *buf = list_entry(dmaq->active.next,
1185 			struct cx23885_buffer, queue);
1186 
1187 		list_del(&buf->queue);
1188 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED);
1189 	}
1190 	spin_unlock_irqrestore(&dev->slock, flags);
1191 	return ret;
1192 }
1193 
1194 static void cx23885_stop_streaming(struct vb2_queue *q)
1195 {
1196 	struct cx23885_dev *dev = q->drv_priv;
1197 
1198 	/* stop mpeg capture */
1199 	cx23885_api_cmd(dev, CX2341X_ENC_STOP_CAPTURE, 3, 0,
1200 			CX23885_END_NOW, CX23885_MPEG_CAPTURE,
1201 			CX23885_RAW_BITS_NONE);
1202 
1203 	msleep(500);
1204 	cx23885_417_check_encoder(dev);
1205 	cx23885_cancel_buffers(&dev->ts1);
1206 }
1207 
1208 static const struct vb2_ops cx23885_qops = {
1209 	.queue_setup    = queue_setup,
1210 	.buf_prepare  = buffer_prepare,
1211 	.buf_finish = buffer_finish,
1212 	.buf_queue    = buffer_queue,
1213 	.wait_prepare = vb2_ops_wait_prepare,
1214 	.wait_finish = vb2_ops_wait_finish,
1215 	.start_streaming = cx23885_start_streaming,
1216 	.stop_streaming = cx23885_stop_streaming,
1217 };
1218 
1219 /* ------------------------------------------------------------------ */
1220 
1221 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *id)
1222 {
1223 	struct cx23885_dev *dev = video_drvdata(file);
1224 
1225 	*id = dev->tvnorm;
1226 	return 0;
1227 }
1228 
1229 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
1230 {
1231 	struct cx23885_dev *dev = video_drvdata(file);
1232 	unsigned int i;
1233 	int ret;
1234 
1235 	for (i = 0; i < ARRAY_SIZE(cx23885_tvnorms); i++)
1236 		if (id & cx23885_tvnorms[i].id)
1237 			break;
1238 	if (i == ARRAY_SIZE(cx23885_tvnorms))
1239 		return -EINVAL;
1240 
1241 	ret = cx23885_set_tvnorm(dev, id);
1242 	if (!ret)
1243 		dev->encodernorm = cx23885_tvnorms[i];
1244 	return ret;
1245 }
1246 
1247 static int vidioc_enum_input(struct file *file, void *priv,
1248 	struct v4l2_input *i)
1249 {
1250 	struct cx23885_dev *dev = video_drvdata(file);
1251 	dprintk(1, "%s()\n", __func__);
1252 	return cx23885_enum_input(dev, i);
1253 }
1254 
1255 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1256 {
1257 	return cx23885_get_input(file, priv, i);
1258 }
1259 
1260 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1261 {
1262 	return cx23885_set_input(file, priv, i);
1263 }
1264 
1265 static int vidioc_g_tuner(struct file *file, void *priv,
1266 				struct v4l2_tuner *t)
1267 {
1268 	struct cx23885_dev *dev = video_drvdata(file);
1269 
1270 	if (dev->tuner_type == TUNER_ABSENT)
1271 		return -EINVAL;
1272 	if (0 != t->index)
1273 		return -EINVAL;
1274 	strscpy(t->name, "Television", sizeof(t->name));
1275 	call_all(dev, tuner, g_tuner, t);
1276 
1277 	dprintk(1, "VIDIOC_G_TUNER: tuner type %d\n", t->type);
1278 
1279 	return 0;
1280 }
1281 
1282 static int vidioc_s_tuner(struct file *file, void *priv,
1283 				const struct v4l2_tuner *t)
1284 {
1285 	struct cx23885_dev *dev = video_drvdata(file);
1286 
1287 	if (dev->tuner_type == TUNER_ABSENT)
1288 		return -EINVAL;
1289 
1290 	/* Update the A/V core */
1291 	call_all(dev, tuner, s_tuner, t);
1292 
1293 	return 0;
1294 }
1295 
1296 static int vidioc_g_frequency(struct file *file, void *priv,
1297 				struct v4l2_frequency *f)
1298 {
1299 	struct cx23885_dev *dev = video_drvdata(file);
1300 
1301 	if (dev->tuner_type == TUNER_ABSENT)
1302 		return -EINVAL;
1303 	f->type = V4L2_TUNER_ANALOG_TV;
1304 	f->frequency = dev->freq;
1305 
1306 	call_all(dev, tuner, g_frequency, f);
1307 
1308 	return 0;
1309 }
1310 
1311 static int vidioc_s_frequency(struct file *file, void *priv,
1312 	const struct v4l2_frequency *f)
1313 {
1314 	return cx23885_set_frequency(file, priv, f);
1315 }
1316 
1317 static int vidioc_querycap(struct file *file, void  *priv,
1318 				struct v4l2_capability *cap)
1319 {
1320 	struct cx23885_dev *dev = video_drvdata(file);
1321 	struct cx23885_tsport  *tsport = &dev->ts1;
1322 
1323 	strscpy(cap->driver, dev->name, sizeof(cap->driver));
1324 	strscpy(cap->card, cx23885_boards[tsport->dev->board].name,
1325 		sizeof(cap->card));
1326 	sprintf(cap->bus_info, "PCIe:%s", pci_name(dev->pci));
1327 	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
1328 			    V4L2_CAP_STREAMING | V4L2_CAP_VBI_CAPTURE |
1329 			    V4L2_CAP_AUDIO | V4L2_CAP_DEVICE_CAPS;
1330 	if (dev->tuner_type != TUNER_ABSENT)
1331 		cap->capabilities |= V4L2_CAP_TUNER;
1332 
1333 	return 0;
1334 }
1335 
1336 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1337 					struct v4l2_fmtdesc *f)
1338 {
1339 	if (f->index != 0)
1340 		return -EINVAL;
1341 
1342 	f->pixelformat = V4L2_PIX_FMT_MPEG;
1343 
1344 	return 0;
1345 }
1346 
1347 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1348 				struct v4l2_format *f)
1349 {
1350 	struct cx23885_dev *dev = video_drvdata(file);
1351 
1352 	f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
1353 	f->fmt.pix.bytesperline = 0;
1354 	f->fmt.pix.sizeimage    =
1355 		dev->ts1.ts_packet_size * dev->ts1.ts_packet_count;
1356 	f->fmt.pix.colorspace   = 0;
1357 	f->fmt.pix.width        = dev->ts1.width;
1358 	f->fmt.pix.height       = dev->ts1.height;
1359 	f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
1360 	dprintk(1, "VIDIOC_G_FMT: w: %d, h: %d\n",
1361 		dev->ts1.width, dev->ts1.height);
1362 	return 0;
1363 }
1364 
1365 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1366 				struct v4l2_format *f)
1367 {
1368 	struct cx23885_dev *dev = video_drvdata(file);
1369 
1370 	f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
1371 	f->fmt.pix.bytesperline = 0;
1372 	f->fmt.pix.sizeimage    =
1373 		dev->ts1.ts_packet_size * dev->ts1.ts_packet_count;
1374 	f->fmt.pix.colorspace   = 0;
1375 	f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
1376 	dprintk(1, "VIDIOC_TRY_FMT: w: %d, h: %d\n",
1377 		dev->ts1.width, dev->ts1.height);
1378 	return 0;
1379 }
1380 
1381 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1382 				struct v4l2_format *f)
1383 {
1384 	struct cx23885_dev *dev = video_drvdata(file);
1385 
1386 	f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
1387 	f->fmt.pix.bytesperline = 0;
1388 	f->fmt.pix.sizeimage    =
1389 		dev->ts1.ts_packet_size * dev->ts1.ts_packet_count;
1390 	f->fmt.pix.colorspace   = 0;
1391 	f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
1392 	dprintk(1, "VIDIOC_S_FMT: w: %d, h: %d, f: %d\n",
1393 		f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.field);
1394 	return 0;
1395 }
1396 
1397 static int vidioc_log_status(struct file *file, void *priv)
1398 {
1399 	struct cx23885_dev *dev = video_drvdata(file);
1400 	char name[32 + 2];
1401 
1402 	snprintf(name, sizeof(name), "%s/2", dev->name);
1403 	call_all(dev, core, log_status);
1404 	v4l2_ctrl_handler_log_status(&dev->cxhdl.hdl, name);
1405 	return 0;
1406 }
1407 
1408 static const struct v4l2_file_operations mpeg_fops = {
1409 	.owner	       = THIS_MODULE,
1410 	.open           = v4l2_fh_open,
1411 	.release        = vb2_fop_release,
1412 	.read           = vb2_fop_read,
1413 	.poll		= vb2_fop_poll,
1414 	.unlocked_ioctl = video_ioctl2,
1415 	.mmap           = vb2_fop_mmap,
1416 };
1417 
1418 static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
1419 	.vidioc_g_std		 = vidioc_g_std,
1420 	.vidioc_s_std		 = vidioc_s_std,
1421 	.vidioc_enum_input	 = vidioc_enum_input,
1422 	.vidioc_g_input		 = vidioc_g_input,
1423 	.vidioc_s_input		 = vidioc_s_input,
1424 	.vidioc_g_tuner		 = vidioc_g_tuner,
1425 	.vidioc_s_tuner		 = vidioc_s_tuner,
1426 	.vidioc_g_frequency	 = vidioc_g_frequency,
1427 	.vidioc_s_frequency	 = vidioc_s_frequency,
1428 	.vidioc_querycap	 = vidioc_querycap,
1429 	.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1430 	.vidioc_g_fmt_vid_cap	 = vidioc_g_fmt_vid_cap,
1431 	.vidioc_try_fmt_vid_cap	 = vidioc_try_fmt_vid_cap,
1432 	.vidioc_s_fmt_vid_cap	 = vidioc_s_fmt_vid_cap,
1433 	.vidioc_reqbufs       = vb2_ioctl_reqbufs,
1434 	.vidioc_prepare_buf   = vb2_ioctl_prepare_buf,
1435 	.vidioc_querybuf      = vb2_ioctl_querybuf,
1436 	.vidioc_qbuf          = vb2_ioctl_qbuf,
1437 	.vidioc_dqbuf         = vb2_ioctl_dqbuf,
1438 	.vidioc_streamon      = vb2_ioctl_streamon,
1439 	.vidioc_streamoff     = vb2_ioctl_streamoff,
1440 	.vidioc_log_status	 = vidioc_log_status,
1441 #ifdef CONFIG_VIDEO_ADV_DEBUG
1442 	.vidioc_g_chip_info	 = cx23885_g_chip_info,
1443 	.vidioc_g_register	 = cx23885_g_register,
1444 	.vidioc_s_register	 = cx23885_s_register,
1445 #endif
1446 };
1447 
1448 static struct video_device cx23885_mpeg_template = {
1449 	.name          = "cx23885",
1450 	.fops          = &mpeg_fops,
1451 	.ioctl_ops     = &mpeg_ioctl_ops,
1452 	.tvnorms       = CX23885_NORMS,
1453 };
1454 
1455 void cx23885_417_unregister(struct cx23885_dev *dev)
1456 {
1457 	dprintk(1, "%s()\n", __func__);
1458 
1459 	if (dev->v4l_device) {
1460 		if (video_is_registered(dev->v4l_device))
1461 			video_unregister_device(dev->v4l_device);
1462 		else
1463 			video_device_release(dev->v4l_device);
1464 		v4l2_ctrl_handler_free(&dev->cxhdl.hdl);
1465 		dev->v4l_device = NULL;
1466 	}
1467 }
1468 
1469 static struct video_device *cx23885_video_dev_alloc(
1470 	struct cx23885_tsport *tsport,
1471 	struct pci_dev *pci,
1472 	struct video_device *template,
1473 	char *type)
1474 {
1475 	struct video_device *vfd;
1476 	struct cx23885_dev *dev = tsport->dev;
1477 
1478 	dprintk(1, "%s()\n", __func__);
1479 
1480 	vfd = video_device_alloc();
1481 	if (NULL == vfd)
1482 		return NULL;
1483 	*vfd = *template;
1484 	snprintf(vfd->name, sizeof(vfd->name), "%s (%s)",
1485 		cx23885_boards[tsport->dev->board].name, type);
1486 	vfd->v4l2_dev = &dev->v4l2_dev;
1487 	vfd->release = video_device_release;
1488 	return vfd;
1489 }
1490 
1491 int cx23885_417_register(struct cx23885_dev *dev)
1492 {
1493 	/* FIXME: Port1 hardcoded here */
1494 	int err = -ENODEV;
1495 	struct cx23885_tsport *tsport = &dev->ts1;
1496 	struct vb2_queue *q;
1497 
1498 	dprintk(1, "%s()\n", __func__);
1499 
1500 	if (cx23885_boards[dev->board].portb != CX23885_MPEG_ENCODER)
1501 		return err;
1502 
1503 	/* Set default TV standard */
1504 	dev->encodernorm = cx23885_tvnorms[0];
1505 
1506 	if (dev->encodernorm.id & V4L2_STD_525_60)
1507 		tsport->height = 480;
1508 	else
1509 		tsport->height = 576;
1510 
1511 	tsport->width = 720;
1512 	dev->cxhdl.port = CX2341X_PORT_SERIAL;
1513 	err = cx2341x_handler_init(&dev->cxhdl, 50);
1514 	if (err)
1515 		return err;
1516 	dev->cxhdl.priv = dev;
1517 	dev->cxhdl.func = cx23885_api_func;
1518 	cx2341x_handler_set_50hz(&dev->cxhdl, tsport->height == 576);
1519 	v4l2_ctrl_add_handler(&dev->ctrl_handler, &dev->cxhdl.hdl, NULL, false);
1520 
1521 	/* Allocate and initialize V4L video device */
1522 	dev->v4l_device = cx23885_video_dev_alloc(tsport,
1523 		dev->pci, &cx23885_mpeg_template, "mpeg");
1524 	q = &dev->vb2_mpegq;
1525 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1526 	q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
1527 	q->gfp_flags = GFP_DMA32;
1528 	q->min_buffers_needed = 2;
1529 	q->drv_priv = dev;
1530 	q->buf_struct_size = sizeof(struct cx23885_buffer);
1531 	q->ops = &cx23885_qops;
1532 	q->mem_ops = &vb2_dma_sg_memops;
1533 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1534 	q->lock = &dev->lock;
1535 	q->dev = &dev->pci->dev;
1536 
1537 	err = vb2_queue_init(q);
1538 	if (err < 0)
1539 		return err;
1540 	video_set_drvdata(dev->v4l_device, dev);
1541 	dev->v4l_device->lock = &dev->lock;
1542 	dev->v4l_device->queue = q;
1543 	dev->v4l_device->device_caps = V4L2_CAP_VIDEO_CAPTURE |
1544 				       V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1545 	if (dev->tuner_type != TUNER_ABSENT)
1546 		dev->v4l_device->device_caps |= V4L2_CAP_TUNER;
1547 	err = video_register_device(dev->v4l_device,
1548 		VFL_TYPE_GRABBER, -1);
1549 	if (err < 0) {
1550 		pr_info("%s: can't register mpeg device\n", dev->name);
1551 		return err;
1552 	}
1553 
1554 	pr_info("%s: registered device %s [mpeg]\n",
1555 	       dev->name, video_device_node_name(dev->v4l_device));
1556 
1557 	/* ST: Configure the encoder parameters, but don't begin
1558 	 * encoding, this resolves an issue where the first time the
1559 	 * encoder is started video can be choppy.
1560 	 */
1561 	cx23885_initialize_codec(dev, 0);
1562 
1563 	return 0;
1564 }
1565 
1566 MODULE_FIRMWARE(CX23885_FIRM_IMAGE_NAME);
1567