1 /*
2  *
3  *  Support for a cx23417 mpeg encoder via cx231xx host port.
4  *
5  *    (c) 2004 Jelle Foks <jelle@foks.us>
6  *    (c) 2004 Gerd Knorr <kraxel@bytesex.org>
7  *    (c) 2008 Steven Toth <stoth@linuxtv.org>
8  *      - CX23885/7/8 support
9  *
10  *  Includes parts from the ivtv driver( http://ivtv.sourceforge.net/),
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2 of the License, or
15  *  (at your option) any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  */
22 
23 #include "cx231xx.h"
24 
25 #include <linux/module.h>
26 #include <linux/moduleparam.h>
27 #include <linux/init.h>
28 #include <linux/fs.h>
29 #include <linux/delay.h>
30 #include <linux/device.h>
31 #include <linux/firmware.h>
32 #include <linux/slab.h>
33 #include <linux/vmalloc.h>
34 #include <media/v4l2-common.h>
35 #include <media/v4l2-ioctl.h>
36 #include <media/v4l2-event.h>
37 #include <media/drv-intf/cx2341x.h>
38 #include <media/tuner.h>
39 
40 #define CX231xx_FIRM_IMAGE_SIZE 376836
41 #define CX231xx_FIRM_IMAGE_NAME "v4l-cx23885-enc.fw"
42 
43 /* for polaris ITVC */
44 #define ITVC_WRITE_DIR          0x03FDFC00
45 #define ITVC_READ_DIR            0x0001FC00
46 
47 #define  MCI_MEMORY_DATA_BYTE0          0x00
48 #define  MCI_MEMORY_DATA_BYTE1          0x08
49 #define  MCI_MEMORY_DATA_BYTE2          0x10
50 #define  MCI_MEMORY_DATA_BYTE3          0x18
51 
52 #define  MCI_MEMORY_ADDRESS_BYTE2       0x20
53 #define  MCI_MEMORY_ADDRESS_BYTE1       0x28
54 #define  MCI_MEMORY_ADDRESS_BYTE0       0x30
55 
56 #define  MCI_REGISTER_DATA_BYTE0        0x40
57 #define  MCI_REGISTER_DATA_BYTE1        0x48
58 #define  MCI_REGISTER_DATA_BYTE2        0x50
59 #define  MCI_REGISTER_DATA_BYTE3        0x58
60 
61 #define  MCI_REGISTER_ADDRESS_BYTE0     0x60
62 #define  MCI_REGISTER_ADDRESS_BYTE1     0x68
63 
64 #define  MCI_REGISTER_MODE              0x70
65 
66 /* Read and write modes for polaris ITVC */
67 #define  MCI_MODE_REGISTER_READ         0x000
68 #define  MCI_MODE_REGISTER_WRITE        0x100
69 #define  MCI_MODE_MEMORY_READ           0x000
70 #define  MCI_MODE_MEMORY_WRITE          0x4000
71 
72 static unsigned int mpegbufs = 8;
73 module_param(mpegbufs, int, 0644);
74 MODULE_PARM_DESC(mpegbufs, "number of mpeg buffers, range 2-32");
75 
76 static unsigned int mpeglines = 128;
77 module_param(mpeglines, int, 0644);
78 MODULE_PARM_DESC(mpeglines, "number of lines in an MPEG buffer, range 2-32");
79 
80 static unsigned int mpeglinesize = 512;
81 module_param(mpeglinesize, int, 0644);
82 MODULE_PARM_DESC(mpeglinesize,
83 	"number of bytes in each line of an MPEG buffer, range 512-1024");
84 
85 static unsigned int v4l_debug = 1;
86 module_param(v4l_debug, int, 0644);
87 MODULE_PARM_DESC(v4l_debug, "enable V4L debug messages");
88 
89 #define dprintk(level, fmt, arg...)	\
90 	do {				\
91 		if (v4l_debug >= level) \
92 			printk(KERN_DEBUG pr_fmt(fmt), ## arg); \
93 	} while (0)
94 
95 static struct cx231xx_tvnorm cx231xx_tvnorms[] = {
96 	{
97 		.name      = "NTSC-M",
98 		.id        = V4L2_STD_NTSC_M,
99 	}, {
100 		.name      = "NTSC-JP",
101 		.id        = V4L2_STD_NTSC_M_JP,
102 	}, {
103 		.name      = "PAL-BG",
104 		.id        = V4L2_STD_PAL_BG,
105 	}, {
106 		.name      = "PAL-DK",
107 		.id        = V4L2_STD_PAL_DK,
108 	}, {
109 		.name      = "PAL-I",
110 		.id        = V4L2_STD_PAL_I,
111 	}, {
112 		.name      = "PAL-M",
113 		.id        = V4L2_STD_PAL_M,
114 	}, {
115 		.name      = "PAL-N",
116 		.id        = V4L2_STD_PAL_N,
117 	}, {
118 		.name      = "PAL-Nc",
119 		.id        = V4L2_STD_PAL_Nc,
120 	}, {
121 		.name      = "PAL-60",
122 		.id        = V4L2_STD_PAL_60,
123 	}, {
124 		.name      = "SECAM-L",
125 		.id        = V4L2_STD_SECAM_L,
126 	}, {
127 		.name      = "SECAM-DK",
128 		.id        = V4L2_STD_SECAM_DK,
129 	}
130 };
131 
132 /* ------------------------------------------------------------------ */
133 
134 enum cx231xx_capture_type {
135 	CX231xx_MPEG_CAPTURE,
136 	CX231xx_RAW_CAPTURE,
137 	CX231xx_RAW_PASSTHRU_CAPTURE
138 };
139 
140 enum cx231xx_capture_bits {
141 	CX231xx_RAW_BITS_NONE             = 0x00,
142 	CX231xx_RAW_BITS_YUV_CAPTURE      = 0x01,
143 	CX231xx_RAW_BITS_PCM_CAPTURE      = 0x02,
144 	CX231xx_RAW_BITS_VBI_CAPTURE      = 0x04,
145 	CX231xx_RAW_BITS_PASSTHRU_CAPTURE = 0x08,
146 	CX231xx_RAW_BITS_TO_HOST_CAPTURE  = 0x10
147 };
148 
149 enum cx231xx_capture_end {
150 	CX231xx_END_AT_GOP, /* stop at the end of gop, generate irq */
151 	CX231xx_END_NOW, /* stop immediately, no irq */
152 };
153 
154 enum cx231xx_framerate {
155 	CX231xx_FRAMERATE_NTSC_30, /* NTSC: 30fps */
156 	CX231xx_FRAMERATE_PAL_25   /* PAL: 25fps */
157 };
158 
159 enum cx231xx_stream_port {
160 	CX231xx_OUTPUT_PORT_MEMORY,
161 	CX231xx_OUTPUT_PORT_STREAMING,
162 	CX231xx_OUTPUT_PORT_SERIAL
163 };
164 
165 enum cx231xx_data_xfer_status {
166 	CX231xx_MORE_BUFFERS_FOLLOW,
167 	CX231xx_LAST_BUFFER,
168 };
169 
170 enum cx231xx_picture_mask {
171 	CX231xx_PICTURE_MASK_NONE,
172 	CX231xx_PICTURE_MASK_I_FRAMES,
173 	CX231xx_PICTURE_MASK_I_P_FRAMES = 0x3,
174 	CX231xx_PICTURE_MASK_ALL_FRAMES = 0x7,
175 };
176 
177 enum cx231xx_vbi_mode_bits {
178 	CX231xx_VBI_BITS_SLICED,
179 	CX231xx_VBI_BITS_RAW,
180 };
181 
182 enum cx231xx_vbi_insertion_bits {
183 	CX231xx_VBI_BITS_INSERT_IN_XTENSION_USR_DATA,
184 	CX231xx_VBI_BITS_INSERT_IN_PRIVATE_PACKETS = 0x1 << 1,
185 	CX231xx_VBI_BITS_SEPARATE_STREAM = 0x2 << 1,
186 	CX231xx_VBI_BITS_SEPARATE_STREAM_USR_DATA = 0x4 << 1,
187 	CX231xx_VBI_BITS_SEPARATE_STREAM_PRV_DATA = 0x5 << 1,
188 };
189 
190 enum cx231xx_dma_unit {
191 	CX231xx_DMA_BYTES,
192 	CX231xx_DMA_FRAMES,
193 };
194 
195 enum cx231xx_dma_transfer_status_bits {
196 	CX231xx_DMA_TRANSFER_BITS_DONE = 0x01,
197 	CX231xx_DMA_TRANSFER_BITS_ERROR = 0x04,
198 	CX231xx_DMA_TRANSFER_BITS_LL_ERROR = 0x10,
199 };
200 
201 enum cx231xx_pause {
202 	CX231xx_PAUSE_ENCODING,
203 	CX231xx_RESUME_ENCODING,
204 };
205 
206 enum cx231xx_copyright {
207 	CX231xx_COPYRIGHT_OFF,
208 	CX231xx_COPYRIGHT_ON,
209 };
210 
211 enum cx231xx_notification_type {
212 	CX231xx_NOTIFICATION_REFRESH,
213 };
214 
215 enum cx231xx_notification_status {
216 	CX231xx_NOTIFICATION_OFF,
217 	CX231xx_NOTIFICATION_ON,
218 };
219 
220 enum cx231xx_notification_mailbox {
221 	CX231xx_NOTIFICATION_NO_MAILBOX = -1,
222 };
223 
224 enum cx231xx_field1_lines {
225 	CX231xx_FIELD1_SAA7114 = 0x00EF, /* 239 */
226 	CX231xx_FIELD1_SAA7115 = 0x00F0, /* 240 */
227 	CX231xx_FIELD1_MICRONAS = 0x0105, /* 261 */
228 };
229 
230 enum cx231xx_field2_lines {
231 	CX231xx_FIELD2_SAA7114 = 0x00EF, /* 239 */
232 	CX231xx_FIELD2_SAA7115 = 0x00F0, /* 240 */
233 	CX231xx_FIELD2_MICRONAS = 0x0106, /* 262 */
234 };
235 
236 enum cx231xx_custom_data_type {
237 	CX231xx_CUSTOM_EXTENSION_USR_DATA,
238 	CX231xx_CUSTOM_PRIVATE_PACKET,
239 };
240 
241 enum cx231xx_mute {
242 	CX231xx_UNMUTE,
243 	CX231xx_MUTE,
244 };
245 
246 enum cx231xx_mute_video_mask {
247 	CX231xx_MUTE_VIDEO_V_MASK = 0x0000FF00,
248 	CX231xx_MUTE_VIDEO_U_MASK = 0x00FF0000,
249 	CX231xx_MUTE_VIDEO_Y_MASK = 0xFF000000,
250 };
251 
252 enum cx231xx_mute_video_shift {
253 	CX231xx_MUTE_VIDEO_V_SHIFT = 8,
254 	CX231xx_MUTE_VIDEO_U_SHIFT = 16,
255 	CX231xx_MUTE_VIDEO_Y_SHIFT = 24,
256 };
257 
258 /* defines below are from ivtv-driver.h */
259 #define IVTV_CMD_HW_BLOCKS_RST 0xFFFFFFFF
260 
261 /* Firmware API commands */
262 #define IVTV_API_STD_TIMEOUT 500
263 
264 /* Registers */
265 /* IVTV_REG_OFFSET */
266 #define IVTV_REG_ENC_SDRAM_REFRESH (0x07F8)
267 #define IVTV_REG_ENC_SDRAM_PRECHARGE (0x07FC)
268 #define IVTV_REG_SPU (0x9050)
269 #define IVTV_REG_HW_BLOCKS (0x9054)
270 #define IVTV_REG_VPU (0x9058)
271 #define IVTV_REG_APU (0xA064)
272 
273 /*
274  * Bit definitions for MC417_RWD and MC417_OEN registers
275  *
276  * bits 31-16
277  *+-----------+
278  *| Reserved  |
279  *|+-----------+
280  *|  bit 15  bit 14  bit 13 bit 12  bit 11  bit 10  bit 9   bit 8
281  *|+-------+-------+-------+-------+-------+-------+-------+-------+
282  *|| MIWR# | MIRD# | MICS# |MIRDY# |MIADDR3|MIADDR2|MIADDR1|MIADDR0|
283  *|+-------+-------+-------+-------+-------+-------+-------+-------+
284  *| bit 7   bit 6   bit 5   bit 4   bit 3   bit 2   bit 1   bit 0
285  *|+-------+-------+-------+-------+-------+-------+-------+-------+
286  *||MIDATA7|MIDATA6|MIDATA5|MIDATA4|MIDATA3|MIDATA2|MIDATA1|MIDATA0|
287  *|+-------+-------+-------+-------+-------+-------+-------+-------+
288  */
289 #define MC417_MIWR	0x8000
290 #define MC417_MIRD	0x4000
291 #define MC417_MICS	0x2000
292 #define MC417_MIRDY	0x1000
293 #define MC417_MIADDR	0x0F00
294 #define MC417_MIDATA	0x00FF
295 
296 
297 /* Bit definitions for MC417_CTL register ****
298  *bits 31-6   bits 5-4   bit 3    bits 2-1       Bit 0
299  *+--------+-------------+--------+--------------+------------+
300  *|Reserved|MC417_SPD_CTL|Reserved|MC417_GPIO_SEL|UART_GPIO_EN|
301  *+--------+-------------+--------+--------------+------------+
302  */
303 #define MC417_SPD_CTL(x)	(((x) << 4) & 0x00000030)
304 #define MC417_GPIO_SEL(x)	(((x) << 1) & 0x00000006)
305 #define MC417_UART_GPIO_EN	0x00000001
306 
307 /* Values for speed control */
308 #define MC417_SPD_CTL_SLOW	0x1
309 #define MC417_SPD_CTL_MEDIUM	0x0
310 #define MC417_SPD_CTL_FAST	0x3     /* b'1x, but we use b'11 */
311 
312 /* Values for GPIO select */
313 #define MC417_GPIO_SEL_GPIO3	0x3
314 #define MC417_GPIO_SEL_GPIO2	0x2
315 #define MC417_GPIO_SEL_GPIO1	0x1
316 #define MC417_GPIO_SEL_GPIO0	0x0
317 
318 
319 #define CX23417_GPIO_MASK 0xFC0003FF
320 
321 static int set_itvc_reg(struct cx231xx *dev, u32 gpio_direction, u32 value)
322 {
323 	int status = 0;
324 	u32 _gpio_direction = 0;
325 
326 	_gpio_direction = _gpio_direction & CX23417_GPIO_MASK;
327 	_gpio_direction = _gpio_direction | gpio_direction;
328 	status = cx231xx_send_gpio_cmd(dev, _gpio_direction,
329 			 (u8 *)&value, 4, 0, 0);
330 	return status;
331 }
332 
333 static int get_itvc_reg(struct cx231xx *dev, u32 gpio_direction, u32 *val_ptr)
334 {
335 	int status = 0;
336 	u32 _gpio_direction = 0;
337 
338 	_gpio_direction = _gpio_direction & CX23417_GPIO_MASK;
339 	_gpio_direction = _gpio_direction | gpio_direction;
340 
341 	status = cx231xx_send_gpio_cmd(dev, _gpio_direction,
342 		 (u8 *)val_ptr, 4, 0, 1);
343 	return status;
344 }
345 
346 static int wait_for_mci_complete(struct cx231xx *dev)
347 {
348 	u32 gpio;
349 	u32 gpio_direction = 0;
350 	u8 count = 0;
351 	get_itvc_reg(dev, gpio_direction, &gpio);
352 
353 	while (!(gpio&0x020000)) {
354 		msleep(10);
355 
356 		get_itvc_reg(dev, gpio_direction, &gpio);
357 
358 		if (count++ > 100) {
359 			dprintk(3, "ERROR: Timeout - gpio=%x\n", gpio);
360 			return -EIO;
361 		}
362 	}
363 	return 0;
364 }
365 
366 static int mc417_register_write(struct cx231xx *dev, u16 address, u32 value)
367 {
368 	u32 temp;
369 	int status = 0;
370 
371 	temp = 0x82 | MCI_REGISTER_DATA_BYTE0 | ((value & 0x000000FF) << 8);
372 	temp = temp << 10;
373 	status = set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
374 	if (status < 0)
375 		return status;
376 	temp = temp | (0x05 << 10);
377 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
378 
379 	/*write data byte 1;*/
380 	temp = 0x82 | MCI_REGISTER_DATA_BYTE1 | (value & 0x0000FF00);
381 	temp = temp << 10;
382 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
383 	temp = temp | (0x05 << 10);
384 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
385 
386 	/*write data byte 2;*/
387 	temp = 0x82 | MCI_REGISTER_DATA_BYTE2 | ((value & 0x00FF0000) >> 8);
388 	temp = temp << 10;
389 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
390 	temp = temp | (0x05 << 10);
391 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
392 
393 	/*write data byte 3;*/
394 	temp = 0x82 | MCI_REGISTER_DATA_BYTE3 | ((value & 0xFF000000) >> 16);
395 	temp = temp << 10;
396 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
397 	temp = temp | (0x05 << 10);
398 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
399 
400 	/*write address byte 0;*/
401 	temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE0 | ((address & 0x000000FF) << 8);
402 	temp = temp << 10;
403 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
404 	temp = temp | (0x05 << 10);
405 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
406 
407 	/*write address byte 1;*/
408 	temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE1 | (address & 0x0000FF00);
409 	temp = temp << 10;
410 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
411 	temp = temp | (0x05 << 10);
412 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
413 
414 	/*Write that the mode is write.*/
415 	temp = 0x82 | MCI_REGISTER_MODE | MCI_MODE_REGISTER_WRITE;
416 	temp = temp << 10;
417 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
418 	temp = temp | (0x05 << 10);
419 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
420 
421 	return wait_for_mci_complete(dev);
422 }
423 
424 static int mc417_register_read(struct cx231xx *dev, u16 address, u32 *value)
425 {
426 	/*write address byte 0;*/
427 	u32 temp;
428 	u32 return_value = 0;
429 	int ret = 0;
430 
431 	temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE0 | ((address & 0x00FF) << 8);
432 	temp = temp << 10;
433 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
434 	temp = temp | ((0x05) << 10);
435 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
436 
437 	/*write address byte 1;*/
438 	temp = 0x82 | MCI_REGISTER_ADDRESS_BYTE1 | (address & 0xFF00);
439 	temp = temp << 10;
440 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
441 	temp = temp | ((0x05) << 10);
442 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
443 
444 	/*write that the mode is read;*/
445 	temp = 0x82 | MCI_REGISTER_MODE | MCI_MODE_REGISTER_READ;
446 	temp = temp << 10;
447 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
448 	temp = temp | ((0x05) << 10);
449 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
450 
451 	/*wait for the MIRDY line to be asserted ,
452 	signalling that the read is done;*/
453 	ret = wait_for_mci_complete(dev);
454 
455 	/*switch the DATA- GPIO to input mode;*/
456 
457 	/*Read data byte 0;*/
458 	temp = (0x82 | MCI_REGISTER_DATA_BYTE0) << 10;
459 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
460 	temp = ((0x81 | MCI_REGISTER_DATA_BYTE0) << 10);
461 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
462 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
463 	return_value |= ((temp & 0x03FC0000) >> 18);
464 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
465 
466 	/* Read data byte 1;*/
467 	temp = (0x82 | MCI_REGISTER_DATA_BYTE1) << 10;
468 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
469 	temp = ((0x81 | MCI_REGISTER_DATA_BYTE1) << 10);
470 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
471 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
472 
473 	return_value |= ((temp & 0x03FC0000) >> 10);
474 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
475 
476 	/*Read data byte 2;*/
477 	temp = (0x82 | MCI_REGISTER_DATA_BYTE2) << 10;
478 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
479 	temp = ((0x81 | MCI_REGISTER_DATA_BYTE2) << 10);
480 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
481 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
482 	return_value |= ((temp & 0x03FC0000) >> 2);
483 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
484 
485 	/*Read data byte 3;*/
486 	temp = (0x82 | MCI_REGISTER_DATA_BYTE3) << 10;
487 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
488 	temp = ((0x81 | MCI_REGISTER_DATA_BYTE3) << 10);
489 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
490 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
491 	return_value |= ((temp & 0x03FC0000) << 6);
492 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
493 
494 	*value  = return_value;
495 	return ret;
496 }
497 
498 static int mc417_memory_write(struct cx231xx *dev, u32 address, u32 value)
499 {
500 	/*write data byte 0;*/
501 
502 	u32 temp;
503 	int ret = 0;
504 
505 	temp = 0x82 | MCI_MEMORY_DATA_BYTE0 | ((value & 0x000000FF) << 8);
506 	temp = temp << 10;
507 	ret = set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
508 	if (ret < 0)
509 		return ret;
510 	temp = temp | (0x05 << 10);
511 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
512 
513 	/*write data byte 1;*/
514 	temp = 0x82 | MCI_MEMORY_DATA_BYTE1 | (value & 0x0000FF00);
515 	temp = temp << 10;
516 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
517 	temp = temp | (0x05 << 10);
518 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
519 
520 	/*write data byte 2;*/
521 	temp = 0x82 | MCI_MEMORY_DATA_BYTE2 | ((value & 0x00FF0000) >> 8);
522 	temp = temp << 10;
523 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
524 	temp = temp | (0x05 << 10);
525 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
526 
527 	/*write data byte 3;*/
528 	temp = 0x82 | MCI_MEMORY_DATA_BYTE3 | ((value & 0xFF000000) >> 16);
529 	temp = temp << 10;
530 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
531 	temp = temp | (0x05 << 10);
532 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
533 
534 	/* write address byte 2;*/
535 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_WRITE |
536 		((address & 0x003F0000) >> 8);
537 	temp = temp << 10;
538 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
539 	temp = temp | (0x05 << 10);
540 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
541 
542 	/* write address byte 1;*/
543 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
544 	temp = temp << 10;
545 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
546 	temp = temp | (0x05 << 10);
547 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
548 
549 	/* write address byte 0;*/
550 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE0 | ((address & 0x00FF) << 8);
551 	temp = temp << 10;
552 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
553 	temp = temp | (0x05 << 10);
554 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
555 
556 	/*wait for MIRDY line;*/
557 	wait_for_mci_complete(dev);
558 
559 	return 0;
560 }
561 
562 static int mc417_memory_read(struct cx231xx *dev, u32 address, u32 *value)
563 {
564 	u32 temp = 0;
565 	u32 return_value = 0;
566 	int ret = 0;
567 
568 	/*write address byte 2;*/
569 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_READ |
570 		((address & 0x003F0000) >> 8);
571 	temp = temp << 10;
572 	ret = set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
573 	if (ret < 0)
574 		return ret;
575 	temp = temp | (0x05 << 10);
576 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
577 
578 	/*write address byte 1*/
579 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
580 	temp = temp << 10;
581 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
582 	temp = temp | (0x05 << 10);
583 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
584 
585 	/*write address byte 0*/
586 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE0 | ((address & 0x00FF) << 8);
587 	temp = temp << 10;
588 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
589 	temp = temp | (0x05 << 10);
590 	set_itvc_reg(dev, ITVC_WRITE_DIR, temp);
591 
592 	/*Wait for MIRDY line*/
593 	ret = wait_for_mci_complete(dev);
594 
595 
596 	/*Read data byte 3;*/
597 	temp = (0x82 | MCI_MEMORY_DATA_BYTE3) << 10;
598 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
599 	temp = ((0x81 | MCI_MEMORY_DATA_BYTE3) << 10);
600 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
601 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
602 	return_value |= ((temp & 0x03FC0000) << 6);
603 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
604 
605 	/*Read data byte 2;*/
606 	temp = (0x82 | MCI_MEMORY_DATA_BYTE2) << 10;
607 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
608 	temp = ((0x81 | MCI_MEMORY_DATA_BYTE2) << 10);
609 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
610 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
611 	return_value |= ((temp & 0x03FC0000) >> 2);
612 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
613 
614 	/* Read data byte 1;*/
615 	temp = (0x82 | MCI_MEMORY_DATA_BYTE1) << 10;
616 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
617 	temp = ((0x81 | MCI_MEMORY_DATA_BYTE1) << 10);
618 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
619 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
620 	return_value |= ((temp & 0x03FC0000) >> 10);
621 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
622 
623 	/*Read data byte 0;*/
624 	temp = (0x82 | MCI_MEMORY_DATA_BYTE0) << 10;
625 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
626 	temp = ((0x81 | MCI_MEMORY_DATA_BYTE0) << 10);
627 	set_itvc_reg(dev, ITVC_READ_DIR, temp);
628 	get_itvc_reg(dev, ITVC_READ_DIR, &temp);
629 	return_value |= ((temp & 0x03FC0000) >> 18);
630 	set_itvc_reg(dev, ITVC_READ_DIR, (0x87 << 10));
631 
632 	*value  = return_value;
633 	return ret;
634 }
635 
636 /* ------------------------------------------------------------------ */
637 
638 /* MPEG encoder API */
639 static char *cmd_to_str(int cmd)
640 {
641 	switch (cmd) {
642 	case CX2341X_ENC_PING_FW:
643 		return "PING_FW";
644 	case CX2341X_ENC_START_CAPTURE:
645 		return "START_CAPTURE";
646 	case CX2341X_ENC_STOP_CAPTURE:
647 		return "STOP_CAPTURE";
648 	case CX2341X_ENC_SET_AUDIO_ID:
649 		return "SET_AUDIO_ID";
650 	case CX2341X_ENC_SET_VIDEO_ID:
651 		return "SET_VIDEO_ID";
652 	case CX2341X_ENC_SET_PCR_ID:
653 		return "SET_PCR_PID";
654 	case CX2341X_ENC_SET_FRAME_RATE:
655 		return "SET_FRAME_RATE";
656 	case CX2341X_ENC_SET_FRAME_SIZE:
657 		return "SET_FRAME_SIZE";
658 	case CX2341X_ENC_SET_BIT_RATE:
659 		return "SET_BIT_RATE";
660 	case CX2341X_ENC_SET_GOP_PROPERTIES:
661 		return "SET_GOP_PROPERTIES";
662 	case CX2341X_ENC_SET_ASPECT_RATIO:
663 		return "SET_ASPECT_RATIO";
664 	case CX2341X_ENC_SET_DNR_FILTER_MODE:
665 		return "SET_DNR_FILTER_PROPS";
666 	case CX2341X_ENC_SET_DNR_FILTER_PROPS:
667 		return "SET_DNR_FILTER_PROPS";
668 	case CX2341X_ENC_SET_CORING_LEVELS:
669 		return "SET_CORING_LEVELS";
670 	case CX2341X_ENC_SET_SPATIAL_FILTER_TYPE:
671 		return "SET_SPATIAL_FILTER_TYPE";
672 	case CX2341X_ENC_SET_VBI_LINE:
673 		return "SET_VBI_LINE";
674 	case CX2341X_ENC_SET_STREAM_TYPE:
675 		return "SET_STREAM_TYPE";
676 	case CX2341X_ENC_SET_OUTPUT_PORT:
677 		return "SET_OUTPUT_PORT";
678 	case CX2341X_ENC_SET_AUDIO_PROPERTIES:
679 		return "SET_AUDIO_PROPERTIES";
680 	case CX2341X_ENC_HALT_FW:
681 		return "HALT_FW";
682 	case CX2341X_ENC_GET_VERSION:
683 		return "GET_VERSION";
684 	case CX2341X_ENC_SET_GOP_CLOSURE:
685 		return "SET_GOP_CLOSURE";
686 	case CX2341X_ENC_GET_SEQ_END:
687 		return "GET_SEQ_END";
688 	case CX2341X_ENC_SET_PGM_INDEX_INFO:
689 		return "SET_PGM_INDEX_INFO";
690 	case CX2341X_ENC_SET_VBI_CONFIG:
691 		return "SET_VBI_CONFIG";
692 	case CX2341X_ENC_SET_DMA_BLOCK_SIZE:
693 		return "SET_DMA_BLOCK_SIZE";
694 	case CX2341X_ENC_GET_PREV_DMA_INFO_MB_10:
695 		return "GET_PREV_DMA_INFO_MB_10";
696 	case CX2341X_ENC_GET_PREV_DMA_INFO_MB_9:
697 		return "GET_PREV_DMA_INFO_MB_9";
698 	case CX2341X_ENC_SCHED_DMA_TO_HOST:
699 		return "SCHED_DMA_TO_HOST";
700 	case CX2341X_ENC_INITIALIZE_INPUT:
701 		return "INITIALIZE_INPUT";
702 	case CX2341X_ENC_SET_FRAME_DROP_RATE:
703 		return "SET_FRAME_DROP_RATE";
704 	case CX2341X_ENC_PAUSE_ENCODER:
705 		return "PAUSE_ENCODER";
706 	case CX2341X_ENC_REFRESH_INPUT:
707 		return "REFRESH_INPUT";
708 	case CX2341X_ENC_SET_COPYRIGHT:
709 		return "SET_COPYRIGHT";
710 	case CX2341X_ENC_SET_EVENT_NOTIFICATION:
711 		return "SET_EVENT_NOTIFICATION";
712 	case CX2341X_ENC_SET_NUM_VSYNC_LINES:
713 		return "SET_NUM_VSYNC_LINES";
714 	case CX2341X_ENC_SET_PLACEHOLDER:
715 		return "SET_PLACEHOLDER";
716 	case CX2341X_ENC_MUTE_VIDEO:
717 		return "MUTE_VIDEO";
718 	case CX2341X_ENC_MUTE_AUDIO:
719 		return "MUTE_AUDIO";
720 	case CX2341X_ENC_MISC:
721 		return "MISC";
722 	default:
723 		return "UNKNOWN";
724 	}
725 }
726 
727 static int cx231xx_mbox_func(void *priv, u32 command, int in, int out,
728 			     u32 data[CX2341X_MBOX_MAX_DATA])
729 {
730 	struct cx231xx *dev = priv;
731 	unsigned long timeout;
732 	u32 value, flag, retval = 0;
733 	int i;
734 
735 	dprintk(3, "%s: command(0x%X) = %s\n", __func__, command,
736 		cmd_to_str(command));
737 
738 	/* this may not be 100% safe if we can't read any memory location
739 	   without side effects */
740 	mc417_memory_read(dev, dev->cx23417_mailbox - 4, &value);
741 	if (value != 0x12345678) {
742 		dprintk(3, "Firmware and/or mailbox pointer not initialized or corrupted, signature = 0x%x, cmd = %s\n",
743 			value, cmd_to_str(command));
744 		return -EIO;
745 	}
746 
747 	/* This read looks at 32 bits, but flag is only 8 bits.
748 	 * Seems we also bail if CMD or TIMEOUT bytes are set???
749 	 */
750 	mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
751 	if (flag) {
752 		dprintk(3, "ERROR: Mailbox appears to be in use (%x), cmd = %s\n",
753 				flag, cmd_to_str(command));
754 		return -EBUSY;
755 	}
756 
757 	flag |= 1; /* tell 'em we're working on it */
758 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
759 
760 	/* write command + args + fill remaining with zeros */
761 	/* command code */
762 	mc417_memory_write(dev, dev->cx23417_mailbox + 1, command);
763 	mc417_memory_write(dev, dev->cx23417_mailbox + 3,
764 		IVTV_API_STD_TIMEOUT); /* timeout */
765 	for (i = 0; i < in; i++) {
766 		mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, data[i]);
767 		dprintk(3, "API Input %d = %d\n", i, data[i]);
768 	}
769 	for (; i < CX2341X_MBOX_MAX_DATA; i++)
770 		mc417_memory_write(dev, dev->cx23417_mailbox + 4 + i, 0);
771 
772 	flag |= 3; /* tell 'em we're done writing */
773 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
774 
775 	/* wait for firmware to handle the API command */
776 	timeout = jiffies + msecs_to_jiffies(10);
777 	for (;;) {
778 		mc417_memory_read(dev, dev->cx23417_mailbox, &flag);
779 		if (0 != (flag & 4))
780 			break;
781 		if (time_after(jiffies, timeout)) {
782 			dprintk(3, "ERROR: API Mailbox timeout\n");
783 			return -EIO;
784 		}
785 		udelay(10);
786 	}
787 
788 	/* read output values */
789 	for (i = 0; i < out; i++) {
790 		mc417_memory_read(dev, dev->cx23417_mailbox + 4 + i, data + i);
791 		dprintk(3, "API Output %d = %d\n", i, data[i]);
792 	}
793 
794 	mc417_memory_read(dev, dev->cx23417_mailbox + 2, &retval);
795 	dprintk(3, "API result = %d\n", retval);
796 
797 	flag = 0;
798 	mc417_memory_write(dev, dev->cx23417_mailbox, flag);
799 
800 	return 0;
801 }
802 
803 /* We don't need to call the API often, so using just one
804  * mailbox will probably suffice
805  */
806 static int cx231xx_api_cmd(struct cx231xx *dev, u32 command,
807 		u32 inputcnt, u32 outputcnt, ...)
808 {
809 	u32 data[CX2341X_MBOX_MAX_DATA];
810 	va_list vargs;
811 	int i, err;
812 
813 	dprintk(3, "%s() cmds = 0x%08x\n", __func__, command);
814 
815 	va_start(vargs, outputcnt);
816 	for (i = 0; i < inputcnt; i++)
817 		data[i] = va_arg(vargs, int);
818 
819 	err = cx231xx_mbox_func(dev, command, inputcnt, outputcnt, data);
820 	for (i = 0; i < outputcnt; i++) {
821 		int *vptr = va_arg(vargs, int *);
822 		*vptr = data[i];
823 	}
824 	va_end(vargs);
825 
826 	return err;
827 }
828 
829 
830 static int cx231xx_find_mailbox(struct cx231xx *dev)
831 {
832 	u32 signature[4] = {
833 		0x12345678, 0x34567812, 0x56781234, 0x78123456
834 	};
835 	int signaturecnt = 0;
836 	u32 value;
837 	int i;
838 	int ret = 0;
839 
840 	dprintk(2, "%s()\n", __func__);
841 
842 	for (i = 0; i < 0x100; i++) {/*CX231xx_FIRM_IMAGE_SIZE*/
843 		ret = mc417_memory_read(dev, i, &value);
844 		if (ret < 0)
845 			return ret;
846 		if (value == signature[signaturecnt])
847 			signaturecnt++;
848 		else
849 			signaturecnt = 0;
850 		if (4 == signaturecnt) {
851 			dprintk(1, "Mailbox signature found at 0x%x\n", i + 1);
852 			return i + 1;
853 		}
854 	}
855 	dprintk(3, "Mailbox signature values not found!\n");
856 	return -EIO;
857 }
858 
859 static void mci_write_memory_to_gpio(struct cx231xx *dev, u32 address, u32 value,
860 		u32 *p_fw_image)
861 {
862 	u32 temp = 0;
863 	int i = 0;
864 
865 	temp = 0x82 | MCI_MEMORY_DATA_BYTE0 | ((value & 0x000000FF) << 8);
866 	temp = temp << 10;
867 	*p_fw_image = temp;
868 	p_fw_image++;
869 	temp = temp | (0x05 << 10);
870 	*p_fw_image = temp;
871 	p_fw_image++;
872 
873 	/*write data byte 1;*/
874 	temp = 0x82 | MCI_MEMORY_DATA_BYTE1 | (value & 0x0000FF00);
875 	temp = temp << 10;
876 	*p_fw_image = temp;
877 	p_fw_image++;
878 	temp = temp | (0x05 << 10);
879 	*p_fw_image = temp;
880 	p_fw_image++;
881 
882 	/*write data byte 2;*/
883 	temp = 0x82 | MCI_MEMORY_DATA_BYTE2 | ((value & 0x00FF0000) >> 8);
884 	temp = temp << 10;
885 	*p_fw_image = temp;
886 	p_fw_image++;
887 	temp = temp | (0x05 << 10);
888 	*p_fw_image = temp;
889 	p_fw_image++;
890 
891 	/*write data byte 3;*/
892 	temp = 0x82 | MCI_MEMORY_DATA_BYTE3 | ((value & 0xFF000000) >> 16);
893 	temp = temp << 10;
894 	*p_fw_image = temp;
895 	p_fw_image++;
896 	temp = temp | (0x05 << 10);
897 	*p_fw_image = temp;
898 	p_fw_image++;
899 
900 	/* write address byte 2;*/
901 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE2 | MCI_MODE_MEMORY_WRITE |
902 		((address & 0x003F0000) >> 8);
903 	temp = temp << 10;
904 	*p_fw_image = temp;
905 	p_fw_image++;
906 	temp = temp | (0x05 << 10);
907 	*p_fw_image = temp;
908 	p_fw_image++;
909 
910 	/* write address byte 1;*/
911 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE1 | (address & 0xFF00);
912 	temp = temp << 10;
913 	*p_fw_image = temp;
914 	p_fw_image++;
915 	temp = temp | (0x05 << 10);
916 	*p_fw_image = temp;
917 	p_fw_image++;
918 
919 	/* write address byte 0;*/
920 	temp = 0x82 | MCI_MEMORY_ADDRESS_BYTE0 | ((address & 0x00FF) << 8);
921 	temp = temp << 10;
922 	*p_fw_image = temp;
923 	p_fw_image++;
924 	temp = temp | (0x05 << 10);
925 	*p_fw_image = temp;
926 	p_fw_image++;
927 
928 	for (i = 0; i < 6; i++) {
929 		*p_fw_image = 0xFFFFFFFF;
930 		p_fw_image++;
931 	}
932 }
933 
934 
935 static int cx231xx_load_firmware(struct cx231xx *dev)
936 {
937 	static const unsigned char magic[8] = {
938 		0xa7, 0x0d, 0x00, 0x00, 0x66, 0xbb, 0x55, 0xaa
939 	};
940 	const struct firmware *firmware;
941 	int i, retval = 0;
942 	u32 value = 0;
943 	u32 gpio_output = 0;
944 	/*u32 checksum = 0;*/
945 	/*u32 *dataptr;*/
946 	u32 transfer_size = 0;
947 	u32 fw_data = 0;
948 	u32 address = 0;
949 	/*u32 current_fw[800];*/
950 	u32 *p_current_fw, *p_fw;
951 	u32 *p_fw_data;
952 	int frame = 0;
953 	u16 _buffer_size = 4096;
954 	u8 *p_buffer;
955 
956 	p_current_fw = vmalloc(1884180 * 4);
957 	p_fw = p_current_fw;
958 	if (p_current_fw == NULL) {
959 		dprintk(2, "FAIL!!!\n");
960 		return -ENOMEM;
961 	}
962 
963 	p_buffer = vmalloc(4096);
964 	if (p_buffer == NULL) {
965 		dprintk(2, "FAIL!!!\n");
966 		vfree(p_current_fw);
967 		return -ENOMEM;
968 	}
969 
970 	dprintk(2, "%s()\n", __func__);
971 
972 	/* Save GPIO settings before reset of APU */
973 	retval |= mc417_memory_read(dev, 0x9020, &gpio_output);
974 	retval |= mc417_memory_read(dev, 0x900C, &value);
975 
976 	retval  = mc417_register_write(dev,
977 		IVTV_REG_VPU, 0xFFFFFFED);
978 	retval |= mc417_register_write(dev,
979 		IVTV_REG_HW_BLOCKS, IVTV_CMD_HW_BLOCKS_RST);
980 	retval |= mc417_register_write(dev,
981 		IVTV_REG_ENC_SDRAM_REFRESH, 0x80000800);
982 	retval |= mc417_register_write(dev,
983 		IVTV_REG_ENC_SDRAM_PRECHARGE, 0x1A);
984 	retval |= mc417_register_write(dev,
985 		IVTV_REG_APU, 0);
986 
987 	if (retval != 0) {
988 		dev_err(dev->dev,
989 			"%s: Error with mc417_register_write\n", __func__);
990 		vfree(p_current_fw);
991 		vfree(p_buffer);
992 		return retval;
993 	}
994 
995 	retval = request_firmware(&firmware, CX231xx_FIRM_IMAGE_NAME,
996 				  dev->dev);
997 
998 	if (retval != 0) {
999 		dev_err(dev->dev,
1000 			"ERROR: Hotplug firmware request failed (%s).\n",
1001 			CX231xx_FIRM_IMAGE_NAME);
1002 		dev_err(dev->dev,
1003 			"Please fix your hotplug setup, the board will not work without firmware loaded!\n");
1004 		vfree(p_current_fw);
1005 		vfree(p_buffer);
1006 		return retval;
1007 	}
1008 
1009 	if (firmware->size != CX231xx_FIRM_IMAGE_SIZE) {
1010 		dev_err(dev->dev,
1011 			"ERROR: Firmware size mismatch (have %zd, expected %d)\n",
1012 			firmware->size, CX231xx_FIRM_IMAGE_SIZE);
1013 		release_firmware(firmware);
1014 		vfree(p_current_fw);
1015 		vfree(p_buffer);
1016 		return -EINVAL;
1017 	}
1018 
1019 	if (0 != memcmp(firmware->data, magic, 8)) {
1020 		dev_err(dev->dev,
1021 			"ERROR: Firmware magic mismatch, wrong file?\n");
1022 		release_firmware(firmware);
1023 		vfree(p_current_fw);
1024 		vfree(p_buffer);
1025 		return -EINVAL;
1026 	}
1027 
1028 	initGPIO(dev);
1029 
1030 	/* transfer to the chip */
1031 	dprintk(2, "Loading firmware to GPIO...\n");
1032 	p_fw_data = (u32 *)firmware->data;
1033 	dprintk(2, "firmware->size=%zd\n", firmware->size);
1034 	for (transfer_size = 0; transfer_size < firmware->size;
1035 		 transfer_size += 4) {
1036 		fw_data = *p_fw_data;
1037 
1038 		mci_write_memory_to_gpio(dev, address, fw_data, p_current_fw);
1039 		address = address + 1;
1040 		p_current_fw += 20;
1041 		p_fw_data += 1;
1042 	}
1043 
1044 	/*download the firmware by ep5-out*/
1045 
1046 	for (frame = 0; frame < (int)(CX231xx_FIRM_IMAGE_SIZE*20/_buffer_size);
1047 	     frame++) {
1048 		for (i = 0; i < _buffer_size; i++) {
1049 			*(p_buffer + i) = (u8)(*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x000000FF);
1050 			i++;
1051 			*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x0000FF00) >> 8);
1052 			i++;
1053 			*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0x00FF0000) >> 16);
1054 			i++;
1055 			*(p_buffer + i) = (u8)((*(p_fw + (frame * 128 * 8 + (i / 4))) & 0xFF000000) >> 24);
1056 		}
1057 		cx231xx_ep5_bulkout(dev, p_buffer, _buffer_size);
1058 	}
1059 
1060 	p_current_fw = p_fw;
1061 	vfree(p_current_fw);
1062 	p_current_fw = NULL;
1063 	uninitGPIO(dev);
1064 	release_firmware(firmware);
1065 	dprintk(1, "Firmware upload successful.\n");
1066 
1067 	retval |= mc417_register_write(dev, IVTV_REG_HW_BLOCKS,
1068 		IVTV_CMD_HW_BLOCKS_RST);
1069 	if (retval < 0) {
1070 		dev_err(dev->dev,
1071 			"%s: Error with mc417_register_write\n",
1072 			__func__);
1073 		return retval;
1074 	}
1075 	/* F/W power up disturbs the GPIOs, restore state */
1076 	retval |= mc417_register_write(dev, 0x9020, gpio_output);
1077 	retval |= mc417_register_write(dev, 0x900C, value);
1078 
1079 	retval |= mc417_register_read(dev, IVTV_REG_VPU, &value);
1080 	retval |= mc417_register_write(dev, IVTV_REG_VPU, value & 0xFFFFFFE8);
1081 
1082 	if (retval < 0) {
1083 		dev_err(dev->dev,
1084 			"%s: Error with mc417_register_write\n",
1085 			__func__);
1086 		return retval;
1087 	}
1088 	return 0;
1089 }
1090 
1091 static void cx231xx_417_check_encoder(struct cx231xx *dev)
1092 {
1093 	u32 status, seq;
1094 
1095 	status = 0;
1096 	seq = 0;
1097 	cx231xx_api_cmd(dev, CX2341X_ENC_GET_SEQ_END, 0, 2, &status, &seq);
1098 	dprintk(1, "%s() status = %d, seq = %d\n", __func__, status, seq);
1099 }
1100 
1101 static void cx231xx_codec_settings(struct cx231xx *dev)
1102 {
1103 	dprintk(1, "%s()\n", __func__);
1104 
1105 	/* assign frame size */
1106 	cx231xx_api_cmd(dev, CX2341X_ENC_SET_FRAME_SIZE, 2, 0,
1107 				dev->ts1.height, dev->ts1.width);
1108 
1109 	dev->mpeg_ctrl_handler.width = dev->ts1.width;
1110 	dev->mpeg_ctrl_handler.height = dev->ts1.height;
1111 
1112 	cx2341x_handler_setup(&dev->mpeg_ctrl_handler);
1113 
1114 	cx231xx_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 3, 1);
1115 	cx231xx_api_cmd(dev, CX2341X_ENC_MISC, 2, 0, 4, 1);
1116 }
1117 
1118 static int cx231xx_initialize_codec(struct cx231xx *dev)
1119 {
1120 	int version;
1121 	int retval;
1122 	u32 i;
1123 	u32 val = 0;
1124 
1125 	dprintk(1, "%s()\n", __func__);
1126 	cx231xx_disable656(dev);
1127 	retval = cx231xx_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0); /* ping */
1128 	if (retval < 0) {
1129 		dprintk(2, "%s: PING OK\n", __func__);
1130 		retval = cx231xx_load_firmware(dev);
1131 		if (retval < 0) {
1132 			dev_err(dev->dev,
1133 				"%s: f/w load failed\n", __func__);
1134 			return retval;
1135 		}
1136 		retval = cx231xx_find_mailbox(dev);
1137 		if (retval < 0) {
1138 			dev_err(dev->dev, "%s: mailbox < 0, error\n",
1139 				__func__);
1140 			return retval;
1141 		}
1142 		dev->cx23417_mailbox = retval;
1143 		retval = cx231xx_api_cmd(dev, CX2341X_ENC_PING_FW, 0, 0);
1144 		if (retval < 0) {
1145 			dev_err(dev->dev,
1146 				"ERROR: cx23417 firmware ping failed!\n");
1147 			return retval;
1148 		}
1149 		retval = cx231xx_api_cmd(dev, CX2341X_ENC_GET_VERSION, 0, 1,
1150 			&version);
1151 		if (retval < 0) {
1152 			dev_err(dev->dev,
1153 				"ERROR: cx23417 firmware get encoder: version failed!\n");
1154 			return retval;
1155 		}
1156 		dprintk(1, "cx23417 firmware version is 0x%08x\n", version);
1157 		msleep(200);
1158 	}
1159 
1160 	for (i = 0; i < 1; i++) {
1161 		retval = mc417_register_read(dev, 0x20f8, &val);
1162 		dprintk(3, "***before enable656() VIM Capture Lines = %d ***\n",
1163 				 val);
1164 		if (retval < 0)
1165 			return retval;
1166 	}
1167 
1168 	cx231xx_enable656(dev);
1169 
1170 	/* stop mpeg capture */
1171 	cx231xx_api_cmd(dev, CX2341X_ENC_STOP_CAPTURE, 3, 0, 1, 3, 4);
1172 
1173 	cx231xx_codec_settings(dev);
1174 	msleep(60);
1175 
1176 /*	cx231xx_api_cmd(dev, CX2341X_ENC_SET_NUM_VSYNC_LINES, 2, 0,
1177 		CX231xx_FIELD1_SAA7115, CX231xx_FIELD2_SAA7115);
1178 	cx231xx_api_cmd(dev, CX2341X_ENC_SET_PLACEHOLDER, 12, 0,
1179 		CX231xx_CUSTOM_EXTENSION_USR_DATA, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1180 		0, 0);
1181 */
1182 
1183 #if 0
1184 	/* TODO */
1185 	u32 data[7];
1186 
1187 	/* Setup to capture VBI */
1188 	data[0] = 0x0001BD00;
1189 	data[1] = 1;          /* frames per interrupt */
1190 	data[2] = 4;          /* total bufs */
1191 	data[3] = 0x91559155; /* start codes */
1192 	data[4] = 0x206080C0; /* stop codes */
1193 	data[5] = 6;          /* lines */
1194 	data[6] = 64;         /* BPL */
1195 
1196 	cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_CONFIG, 7, 0, data[0], data[1],
1197 		data[2], data[3], data[4], data[5], data[6]);
1198 
1199 	for (i = 2; i <= 24; i++) {
1200 		int valid;
1201 
1202 		valid = ((i >= 19) && (i <= 21));
1203 		cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0, i,
1204 				valid, 0 , 0, 0);
1205 		cx231xx_api_cmd(dev, CX2341X_ENC_SET_VBI_LINE, 5, 0,
1206 				i | 0x80000000, valid, 0, 0, 0);
1207 	}
1208 #endif
1209 /*	cx231xx_api_cmd(dev, CX2341X_ENC_MUTE_AUDIO, 1, 0, CX231xx_UNMUTE);
1210 	msleep(60);
1211 */
1212 	/* initialize the video input */
1213 	retval = cx231xx_api_cmd(dev, CX2341X_ENC_INITIALIZE_INPUT, 0, 0);
1214 	if (retval < 0)
1215 		return retval;
1216 	msleep(60);
1217 
1218 	/* Enable VIP style pixel invalidation so we work with scaled mode */
1219 	mc417_memory_write(dev, 2120, 0x00000080);
1220 
1221 	/* start capturing to the host interface */
1222 	retval = cx231xx_api_cmd(dev, CX2341X_ENC_START_CAPTURE, 2, 0,
1223 		CX231xx_MPEG_CAPTURE, CX231xx_RAW_BITS_NONE);
1224 	if (retval < 0)
1225 		return retval;
1226 	msleep(10);
1227 
1228 	for (i = 0; i < 1; i++) {
1229 		mc417_register_read(dev, 0x20f8, &val);
1230 		dprintk(3, "***VIM Capture Lines =%d ***\n", val);
1231 	}
1232 
1233 	return 0;
1234 }
1235 
1236 /* ------------------------------------------------------------------ */
1237 
1238 static int bb_buf_setup(struct videobuf_queue *q,
1239 	unsigned int *count, unsigned int *size)
1240 {
1241 	struct cx231xx_fh *fh = q->priv_data;
1242 
1243 	fh->dev->ts1.ts_packet_size  = mpeglinesize;
1244 	fh->dev->ts1.ts_packet_count = mpeglines;
1245 
1246 	*size = fh->dev->ts1.ts_packet_size * fh->dev->ts1.ts_packet_count;
1247 	*count = mpegbufs;
1248 
1249 	return 0;
1250 }
1251 
1252 static void free_buffer(struct videobuf_queue *vq, struct cx231xx_buffer *buf)
1253 {
1254 	struct cx231xx_fh *fh = vq->priv_data;
1255 	struct cx231xx *dev = fh->dev;
1256 	unsigned long flags = 0;
1257 
1258 	BUG_ON(in_interrupt());
1259 
1260 	spin_lock_irqsave(&dev->video_mode.slock, flags);
1261 	if (dev->USE_ISO) {
1262 		if (dev->video_mode.isoc_ctl.buf == buf)
1263 			dev->video_mode.isoc_ctl.buf = NULL;
1264 	} else {
1265 		if (dev->video_mode.bulk_ctl.buf == buf)
1266 			dev->video_mode.bulk_ctl.buf = NULL;
1267 	}
1268 	spin_unlock_irqrestore(&dev->video_mode.slock, flags);
1269 	videobuf_waiton(vq, &buf->vb, 0, 0);
1270 	videobuf_vmalloc_free(&buf->vb);
1271 	buf->vb.state = VIDEOBUF_NEEDS_INIT;
1272 }
1273 
1274 static void buffer_copy(struct cx231xx *dev, char *data, int len, struct urb *urb,
1275 		struct cx231xx_dmaqueue *dma_q)
1276 {
1277 	void *vbuf;
1278 	struct cx231xx_buffer *buf;
1279 	u32 tail_data = 0;
1280 	char *p_data;
1281 
1282 	if (dma_q->mpeg_buffer_done == 0) {
1283 		if (list_empty(&dma_q->active))
1284 			return;
1285 
1286 		buf = list_entry(dma_q->active.next,
1287 				struct cx231xx_buffer, vb.queue);
1288 		dev->video_mode.isoc_ctl.buf = buf;
1289 		dma_q->mpeg_buffer_done = 1;
1290 	}
1291 	/* Fill buffer */
1292 	buf = dev->video_mode.isoc_ctl.buf;
1293 	vbuf = videobuf_to_vmalloc(&buf->vb);
1294 
1295 	if ((dma_q->mpeg_buffer_completed+len) <
1296 			mpeglines*mpeglinesize) {
1297 		if (dma_q->add_ps_package_head ==
1298 				CX231XX_NEED_ADD_PS_PACKAGE_HEAD) {
1299 			memcpy(vbuf+dma_q->mpeg_buffer_completed,
1300 					dma_q->ps_head, 3);
1301 			dma_q->mpeg_buffer_completed =
1302 				dma_q->mpeg_buffer_completed + 3;
1303 			dma_q->add_ps_package_head =
1304 				CX231XX_NONEED_PS_PACKAGE_HEAD;
1305 		}
1306 		memcpy(vbuf+dma_q->mpeg_buffer_completed, data, len);
1307 		dma_q->mpeg_buffer_completed =
1308 			dma_q->mpeg_buffer_completed + len;
1309 	} else {
1310 		dma_q->mpeg_buffer_done = 0;
1311 
1312 		tail_data =
1313 			mpeglines*mpeglinesize - dma_q->mpeg_buffer_completed;
1314 		memcpy(vbuf+dma_q->mpeg_buffer_completed,
1315 				data, tail_data);
1316 
1317 		buf->vb.state = VIDEOBUF_DONE;
1318 		buf->vb.field_count++;
1319 		v4l2_get_timestamp(&buf->vb.ts);
1320 		list_del(&buf->vb.queue);
1321 		wake_up(&buf->vb.done);
1322 		dma_q->mpeg_buffer_completed = 0;
1323 
1324 		if (len - tail_data > 0) {
1325 			p_data = data + tail_data;
1326 			dma_q->left_data_count = len - tail_data;
1327 			memcpy(dma_q->p_left_data,
1328 					p_data, len - tail_data);
1329 		}
1330 	}
1331 }
1332 
1333 static void buffer_filled(char *data, int len, struct urb *urb,
1334 		struct cx231xx_dmaqueue *dma_q)
1335 {
1336 	void *vbuf;
1337 	struct cx231xx_buffer *buf;
1338 
1339 	if (list_empty(&dma_q->active))
1340 		return;
1341 
1342 	buf = list_entry(dma_q->active.next,
1343 			struct cx231xx_buffer, vb.queue);
1344 
1345 	/* Fill buffer */
1346 	vbuf = videobuf_to_vmalloc(&buf->vb);
1347 	memcpy(vbuf, data, len);
1348 	buf->vb.state = VIDEOBUF_DONE;
1349 	buf->vb.field_count++;
1350 	v4l2_get_timestamp(&buf->vb.ts);
1351 	list_del(&buf->vb.queue);
1352 	wake_up(&buf->vb.done);
1353 }
1354 
1355 static int cx231xx_isoc_copy(struct cx231xx *dev, struct urb *urb)
1356 {
1357 	struct cx231xx_dmaqueue *dma_q = urb->context;
1358 	unsigned char *p_buffer;
1359 	u32 buffer_size = 0;
1360 	u32 i = 0;
1361 
1362 	for (i = 0; i < urb->number_of_packets; i++) {
1363 		if (dma_q->left_data_count > 0) {
1364 			buffer_copy(dev, dma_q->p_left_data,
1365 				    dma_q->left_data_count, urb, dma_q);
1366 			dma_q->mpeg_buffer_completed = dma_q->left_data_count;
1367 			dma_q->left_data_count = 0;
1368 		}
1369 
1370 		p_buffer = urb->transfer_buffer +
1371 				urb->iso_frame_desc[i].offset;
1372 		buffer_size = urb->iso_frame_desc[i].actual_length;
1373 
1374 		if (buffer_size > 0)
1375 			buffer_copy(dev, p_buffer, buffer_size, urb, dma_q);
1376 	}
1377 
1378 	return 0;
1379 }
1380 
1381 static int cx231xx_bulk_copy(struct cx231xx *dev, struct urb *urb)
1382 {
1383 	struct cx231xx_dmaqueue *dma_q = urb->context;
1384 	unsigned char *p_buffer, *buffer;
1385 	u32 buffer_size = 0;
1386 
1387 	p_buffer = urb->transfer_buffer;
1388 	buffer_size = urb->actual_length;
1389 
1390 	buffer = kmalloc(buffer_size, GFP_ATOMIC);
1391 	if (!buffer)
1392 		return -ENOMEM;
1393 
1394 	memcpy(buffer, dma_q->ps_head, 3);
1395 	memcpy(buffer+3, p_buffer, buffer_size-3);
1396 	memcpy(dma_q->ps_head, p_buffer+buffer_size-3, 3);
1397 
1398 	p_buffer = buffer;
1399 	buffer_filled(p_buffer, buffer_size, urb, dma_q);
1400 
1401 	kfree(buffer);
1402 	return 0;
1403 }
1404 
1405 static int bb_buf_prepare(struct videobuf_queue *q,
1406 	struct videobuf_buffer *vb, enum v4l2_field field)
1407 {
1408 	struct cx231xx_fh *fh = q->priv_data;
1409 	struct cx231xx_buffer *buf =
1410 	    container_of(vb, struct cx231xx_buffer, vb);
1411 	struct cx231xx *dev = fh->dev;
1412 	int rc = 0, urb_init = 0;
1413 	int size = fh->dev->ts1.ts_packet_size * fh->dev->ts1.ts_packet_count;
1414 
1415 	if (0 != buf->vb.baddr  &&  buf->vb.bsize < size)
1416 		return -EINVAL;
1417 	buf->vb.width = fh->dev->ts1.ts_packet_size;
1418 	buf->vb.height = fh->dev->ts1.ts_packet_count;
1419 	buf->vb.size = size;
1420 	buf->vb.field = field;
1421 
1422 	if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
1423 		rc = videobuf_iolock(q, &buf->vb, NULL);
1424 		if (rc < 0)
1425 			goto fail;
1426 	}
1427 
1428 	if (dev->USE_ISO) {
1429 		if (!dev->video_mode.isoc_ctl.num_bufs)
1430 			urb_init = 1;
1431 	} else {
1432 		if (!dev->video_mode.bulk_ctl.num_bufs)
1433 			urb_init = 1;
1434 	}
1435 	dev_dbg(dev->dev,
1436 		"urb_init=%d dev->video_mode.max_pkt_size=%d\n",
1437 		urb_init, dev->video_mode.max_pkt_size);
1438 	dev->mode_tv = 1;
1439 
1440 	if (urb_init) {
1441 		rc = cx231xx_set_mode(dev, CX231XX_DIGITAL_MODE);
1442 		rc = cx231xx_unmute_audio(dev);
1443 		if (dev->USE_ISO) {
1444 			cx231xx_set_alt_setting(dev, INDEX_TS1, 4);
1445 			rc = cx231xx_init_isoc(dev, mpeglines,
1446 				       mpegbufs,
1447 				       dev->ts1_mode.max_pkt_size,
1448 				       cx231xx_isoc_copy);
1449 		} else {
1450 			cx231xx_set_alt_setting(dev, INDEX_TS1, 0);
1451 			rc = cx231xx_init_bulk(dev, mpeglines,
1452 				       mpegbufs,
1453 				       dev->ts1_mode.max_pkt_size,
1454 				       cx231xx_bulk_copy);
1455 		}
1456 		if (rc < 0)
1457 			goto fail;
1458 	}
1459 
1460 	buf->vb.state = VIDEOBUF_PREPARED;
1461 	return 0;
1462 
1463 fail:
1464 	free_buffer(q, buf);
1465 	return rc;
1466 }
1467 
1468 static void bb_buf_queue(struct videobuf_queue *q,
1469 	struct videobuf_buffer *vb)
1470 {
1471 	struct cx231xx_fh *fh = q->priv_data;
1472 
1473 	struct cx231xx_buffer *buf =
1474 	    container_of(vb, struct cx231xx_buffer, vb);
1475 	struct cx231xx *dev = fh->dev;
1476 	struct cx231xx_dmaqueue *vidq = &dev->video_mode.vidq;
1477 
1478 	buf->vb.state = VIDEOBUF_QUEUED;
1479 	list_add_tail(&buf->vb.queue, &vidq->active);
1480 
1481 }
1482 
1483 static void bb_buf_release(struct videobuf_queue *q,
1484 	struct videobuf_buffer *vb)
1485 {
1486 	struct cx231xx_buffer *buf =
1487 	    container_of(vb, struct cx231xx_buffer, vb);
1488 	/*struct cx231xx_fh *fh = q->priv_data;*/
1489 	/*struct cx231xx *dev = (struct cx231xx *)fh->dev;*/
1490 
1491 	free_buffer(q, buf);
1492 }
1493 
1494 static const struct videobuf_queue_ops cx231xx_qops = {
1495 	.buf_setup    = bb_buf_setup,
1496 	.buf_prepare  = bb_buf_prepare,
1497 	.buf_queue    = bb_buf_queue,
1498 	.buf_release  = bb_buf_release,
1499 };
1500 
1501 /* ------------------------------------------------------------------ */
1502 
1503 static int vidioc_g_pixelaspect(struct file *file, void *priv,
1504 				int type, struct v4l2_fract *f)
1505 {
1506 	struct cx231xx_fh *fh = priv;
1507 	struct cx231xx *dev = fh->dev;
1508 	bool is_50hz = dev->encodernorm.id & V4L2_STD_625_50;
1509 
1510 	if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1511 		return -EINVAL;
1512 
1513 	f->numerator = is_50hz ? 54 : 11;
1514 	f->denominator = is_50hz ? 59 : 10;
1515 
1516 	return 0;
1517 }
1518 
1519 static int vidioc_g_selection(struct file *file, void *priv,
1520 			      struct v4l2_selection *s)
1521 {
1522 	struct cx231xx_fh *fh = priv;
1523 	struct cx231xx *dev = fh->dev;
1524 
1525 	if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1526 		return -EINVAL;
1527 
1528 	switch (s->target) {
1529 	case V4L2_SEL_TGT_CROP_BOUNDS:
1530 	case V4L2_SEL_TGT_CROP_DEFAULT:
1531 		s->r.left = 0;
1532 		s->r.top = 0;
1533 		s->r.width = dev->ts1.width;
1534 		s->r.height = dev->ts1.height;
1535 		break;
1536 	default:
1537 		return -EINVAL;
1538 	}
1539 	return 0;
1540 }
1541 
1542 static int vidioc_g_std(struct file *file, void *fh0, v4l2_std_id *norm)
1543 {
1544 	struct cx231xx_fh  *fh  = file->private_data;
1545 	struct cx231xx *dev = fh->dev;
1546 
1547 	*norm = dev->encodernorm.id;
1548 	return 0;
1549 }
1550 
1551 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
1552 {
1553 	struct cx231xx_fh  *fh  = file->private_data;
1554 	struct cx231xx *dev = fh->dev;
1555 	unsigned int i;
1556 
1557 	for (i = 0; i < ARRAY_SIZE(cx231xx_tvnorms); i++)
1558 		if (id & cx231xx_tvnorms[i].id)
1559 			break;
1560 	if (i == ARRAY_SIZE(cx231xx_tvnorms))
1561 		return -EINVAL;
1562 	dev->encodernorm = cx231xx_tvnorms[i];
1563 
1564 	if (dev->encodernorm.id & 0xb000) {
1565 		dprintk(3, "encodernorm set to NTSC\n");
1566 		dev->norm = V4L2_STD_NTSC;
1567 		dev->ts1.height = 480;
1568 		cx2341x_handler_set_50hz(&dev->mpeg_ctrl_handler, false);
1569 	} else {
1570 		dprintk(3, "encodernorm set to PAL\n");
1571 		dev->norm = V4L2_STD_PAL_B;
1572 		dev->ts1.height = 576;
1573 		cx2341x_handler_set_50hz(&dev->mpeg_ctrl_handler, true);
1574 	}
1575 	call_all(dev, video, s_std, dev->norm);
1576 	/* do mode control overrides */
1577 	cx231xx_do_mode_ctrl_overrides(dev);
1578 
1579 	dprintk(3, "exit vidioc_s_std() i=0x%x\n", i);
1580 	return 0;
1581 }
1582 
1583 static int vidioc_s_ctrl(struct file *file, void *priv,
1584 				struct v4l2_control *ctl)
1585 {
1586 	struct cx231xx_fh  *fh  = file->private_data;
1587 	struct cx231xx *dev = fh->dev;
1588 	struct v4l2_subdev *sd;
1589 
1590 	dprintk(3, "enter vidioc_s_ctrl()\n");
1591 	/* Update the A/V core */
1592 	v4l2_device_for_each_subdev(sd, &dev->v4l2_dev)
1593 		v4l2_s_ctrl(NULL, sd->ctrl_handler, ctl);
1594 	dprintk(3, "exit vidioc_s_ctrl()\n");
1595 	return 0;
1596 }
1597 
1598 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1599 					struct v4l2_fmtdesc *f)
1600 {
1601 	if (f->index != 0)
1602 		return -EINVAL;
1603 
1604 	strscpy(f->description, "MPEG", sizeof(f->description));
1605 	f->pixelformat = V4L2_PIX_FMT_MPEG;
1606 
1607 	return 0;
1608 }
1609 
1610 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1611 				struct v4l2_format *f)
1612 {
1613 	struct cx231xx_fh  *fh  = file->private_data;
1614 	struct cx231xx *dev = fh->dev;
1615 
1616 	dprintk(3, "enter vidioc_g_fmt_vid_cap()\n");
1617 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
1618 	f->fmt.pix.bytesperline = 0;
1619 	f->fmt.pix.sizeimage = mpeglines * mpeglinesize;
1620 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1621 	f->fmt.pix.width = dev->ts1.width;
1622 	f->fmt.pix.height = dev->ts1.height;
1623 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1624 	dprintk(1, "VIDIOC_G_FMT: w: %d, h: %d\n",
1625 		dev->ts1.width, dev->ts1.height);
1626 	dprintk(3, "exit vidioc_g_fmt_vid_cap()\n");
1627 	return 0;
1628 }
1629 
1630 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1631 				struct v4l2_format *f)
1632 {
1633 	struct cx231xx_fh  *fh  = file->private_data;
1634 	struct cx231xx *dev = fh->dev;
1635 
1636 	dprintk(3, "enter vidioc_try_fmt_vid_cap()\n");
1637 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_MPEG;
1638 	f->fmt.pix.bytesperline = 0;
1639 	f->fmt.pix.sizeimage = mpeglines * mpeglinesize;
1640 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1641 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1642 	dprintk(1, "VIDIOC_TRY_FMT: w: %d, h: %d\n",
1643 		dev->ts1.width, dev->ts1.height);
1644 	dprintk(3, "exit vidioc_try_fmt_vid_cap()\n");
1645 	return 0;
1646 }
1647 
1648 static int vidioc_reqbufs(struct file *file, void *priv,
1649 				struct v4l2_requestbuffers *p)
1650 {
1651 	struct cx231xx_fh  *fh  = file->private_data;
1652 
1653 	return videobuf_reqbufs(&fh->vidq, p);
1654 }
1655 
1656 static int vidioc_querybuf(struct file *file, void *priv,
1657 				struct v4l2_buffer *p)
1658 {
1659 	struct cx231xx_fh  *fh  = file->private_data;
1660 
1661 	return videobuf_querybuf(&fh->vidq, p);
1662 }
1663 
1664 static int vidioc_qbuf(struct file *file, void *priv,
1665 				struct v4l2_buffer *p)
1666 {
1667 	struct cx231xx_fh  *fh  = file->private_data;
1668 
1669 	return videobuf_qbuf(&fh->vidq, p);
1670 }
1671 
1672 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1673 {
1674 	struct cx231xx_fh  *fh  = priv;
1675 
1676 	return videobuf_dqbuf(&fh->vidq, b, file->f_flags & O_NONBLOCK);
1677 }
1678 
1679 
1680 static int vidioc_streamon(struct file *file, void *priv,
1681 				enum v4l2_buf_type i)
1682 {
1683 	struct cx231xx_fh  *fh  = file->private_data;
1684 	struct cx231xx *dev = fh->dev;
1685 
1686 	dprintk(3, "enter vidioc_streamon()\n");
1687 	cx231xx_set_alt_setting(dev, INDEX_TS1, 0);
1688 	cx231xx_set_mode(dev, CX231XX_DIGITAL_MODE);
1689 	if (dev->USE_ISO)
1690 		cx231xx_init_isoc(dev, CX231XX_NUM_PACKETS,
1691 				CX231XX_NUM_BUFS,
1692 				dev->video_mode.max_pkt_size,
1693 				cx231xx_isoc_copy);
1694 	else {
1695 		cx231xx_init_bulk(dev, 320,
1696 				5,
1697 				dev->ts1_mode.max_pkt_size,
1698 				cx231xx_bulk_copy);
1699 	}
1700 	dprintk(3, "exit vidioc_streamon()\n");
1701 	return videobuf_streamon(&fh->vidq);
1702 }
1703 
1704 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1705 {
1706 	struct cx231xx_fh  *fh  = file->private_data;
1707 
1708 	return videobuf_streamoff(&fh->vidq);
1709 }
1710 
1711 static int vidioc_log_status(struct file *file, void *priv)
1712 {
1713 	struct cx231xx_fh  *fh  = priv;
1714 	struct cx231xx *dev = fh->dev;
1715 
1716 	call_all(dev, core, log_status);
1717 	return v4l2_ctrl_log_status(file, priv);
1718 }
1719 
1720 static int mpeg_open(struct file *file)
1721 {
1722 	struct video_device *vdev = video_devdata(file);
1723 	struct cx231xx *dev = video_drvdata(file);
1724 	struct cx231xx_fh *fh;
1725 
1726 	dprintk(2, "%s()\n", __func__);
1727 
1728 	if (mutex_lock_interruptible(&dev->lock))
1729 		return -ERESTARTSYS;
1730 
1731 	/* allocate + initialize per filehandle data */
1732 	fh = kzalloc(sizeof(*fh), GFP_KERNEL);
1733 	if (NULL == fh) {
1734 		mutex_unlock(&dev->lock);
1735 		return -ENOMEM;
1736 	}
1737 
1738 	file->private_data = fh;
1739 	v4l2_fh_init(&fh->fh, vdev);
1740 	fh->dev = dev;
1741 
1742 
1743 	videobuf_queue_vmalloc_init(&fh->vidq, &cx231xx_qops,
1744 			    NULL, &dev->video_mode.slock,
1745 			    V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FIELD_INTERLACED,
1746 			    sizeof(struct cx231xx_buffer), fh, &dev->lock);
1747 /*
1748 	videobuf_queue_sg_init(&fh->vidq, &cx231xx_qops,
1749 			    dev->dev, &dev->ts1.slock,
1750 			    V4L2_BUF_TYPE_VIDEO_CAPTURE,
1751 			    V4L2_FIELD_INTERLACED,
1752 			    sizeof(struct cx231xx_buffer),
1753 			    fh, &dev->lock);
1754 */
1755 
1756 	cx231xx_set_alt_setting(dev, INDEX_VANC, 1);
1757 	cx231xx_set_gpio_value(dev, 2, 0);
1758 
1759 	cx231xx_initialize_codec(dev);
1760 
1761 	mutex_unlock(&dev->lock);
1762 	v4l2_fh_add(&fh->fh);
1763 	cx231xx_start_TS1(dev);
1764 
1765 	return 0;
1766 }
1767 
1768 static int mpeg_release(struct file *file)
1769 {
1770 	struct cx231xx_fh  *fh  = file->private_data;
1771 	struct cx231xx *dev = fh->dev;
1772 
1773 	dprintk(3, "mpeg_release()! dev=0x%p\n", dev);
1774 
1775 	mutex_lock(&dev->lock);
1776 
1777 	cx231xx_stop_TS1(dev);
1778 
1779 	/* do this before setting alternate! */
1780 	if (dev->USE_ISO)
1781 		cx231xx_uninit_isoc(dev);
1782 	else
1783 		cx231xx_uninit_bulk(dev);
1784 	cx231xx_set_mode(dev, CX231XX_SUSPEND);
1785 
1786 	cx231xx_api_cmd(fh->dev, CX2341X_ENC_STOP_CAPTURE, 3, 0,
1787 			CX231xx_END_NOW, CX231xx_MPEG_CAPTURE,
1788 			CX231xx_RAW_BITS_NONE);
1789 
1790 	/* FIXME: Review this crap */
1791 	/* Shut device down on last close */
1792 	if (atomic_cmpxchg(&fh->v4l_reading, 1, 0) == 1) {
1793 		if (atomic_dec_return(&dev->v4l_reader_count) == 0) {
1794 			/* stop mpeg capture */
1795 
1796 			msleep(500);
1797 			cx231xx_417_check_encoder(dev);
1798 
1799 		}
1800 	}
1801 
1802 	if (fh->vidq.streaming)
1803 		videobuf_streamoff(&fh->vidq);
1804 	if (fh->vidq.reading)
1805 		videobuf_read_stop(&fh->vidq);
1806 
1807 	videobuf_mmap_free(&fh->vidq);
1808 	v4l2_fh_del(&fh->fh);
1809 	v4l2_fh_exit(&fh->fh);
1810 	kfree(fh);
1811 	mutex_unlock(&dev->lock);
1812 	return 0;
1813 }
1814 
1815 static ssize_t mpeg_read(struct file *file, char __user *data,
1816 	size_t count, loff_t *ppos)
1817 {
1818 	struct cx231xx_fh *fh = file->private_data;
1819 	struct cx231xx *dev = fh->dev;
1820 
1821 	/* Deal w/ A/V decoder * and mpeg encoder sync issues. */
1822 	/* Start mpeg encoder on first read. */
1823 	if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
1824 		if (atomic_inc_return(&dev->v4l_reader_count) == 1) {
1825 			if (cx231xx_initialize_codec(dev) < 0)
1826 				return -EINVAL;
1827 		}
1828 	}
1829 
1830 	return videobuf_read_stream(&fh->vidq, data, count, ppos, 0,
1831 				    file->f_flags & O_NONBLOCK);
1832 }
1833 
1834 static __poll_t mpeg_poll(struct file *file,
1835 	struct poll_table_struct *wait)
1836 {
1837 	__poll_t req_events = poll_requested_events(wait);
1838 	struct cx231xx_fh *fh = file->private_data;
1839 	struct cx231xx *dev = fh->dev;
1840 	__poll_t res = 0;
1841 
1842 	if (v4l2_event_pending(&fh->fh))
1843 		res |= EPOLLPRI;
1844 	else
1845 		poll_wait(file, &fh->fh.wait, wait);
1846 
1847 	if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
1848 		return res;
1849 
1850 	mutex_lock(&dev->lock);
1851 	res |= videobuf_poll_stream(file, &fh->vidq, wait);
1852 	mutex_unlock(&dev->lock);
1853 	return res;
1854 }
1855 
1856 static int mpeg_mmap(struct file *file, struct vm_area_struct *vma)
1857 {
1858 	struct cx231xx_fh *fh = file->private_data;
1859 
1860 	dprintk(2, "%s()\n", __func__);
1861 
1862 	return videobuf_mmap_mapper(&fh->vidq, vma);
1863 }
1864 
1865 static const struct v4l2_file_operations mpeg_fops = {
1866 	.owner	       = THIS_MODULE,
1867 	.open	       = mpeg_open,
1868 	.release       = mpeg_release,
1869 	.read	       = mpeg_read,
1870 	.poll          = mpeg_poll,
1871 	.mmap	       = mpeg_mmap,
1872 	.unlocked_ioctl = video_ioctl2,
1873 };
1874 
1875 static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
1876 	.vidioc_s_std		 = vidioc_s_std,
1877 	.vidioc_g_std		 = vidioc_g_std,
1878 	.vidioc_g_tuner          = cx231xx_g_tuner,
1879 	.vidioc_s_tuner          = cx231xx_s_tuner,
1880 	.vidioc_g_frequency      = cx231xx_g_frequency,
1881 	.vidioc_s_frequency      = cx231xx_s_frequency,
1882 	.vidioc_enum_input	 = cx231xx_enum_input,
1883 	.vidioc_g_input		 = cx231xx_g_input,
1884 	.vidioc_s_input		 = cx231xx_s_input,
1885 	.vidioc_s_ctrl		 = vidioc_s_ctrl,
1886 	.vidioc_g_pixelaspect	 = vidioc_g_pixelaspect,
1887 	.vidioc_g_selection	 = vidioc_g_selection,
1888 	.vidioc_querycap	 = cx231xx_querycap,
1889 	.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1890 	.vidioc_g_fmt_vid_cap	 = vidioc_g_fmt_vid_cap,
1891 	.vidioc_try_fmt_vid_cap	 = vidioc_try_fmt_vid_cap,
1892 	.vidioc_s_fmt_vid_cap	 = vidioc_try_fmt_vid_cap,
1893 	.vidioc_reqbufs		 = vidioc_reqbufs,
1894 	.vidioc_querybuf	 = vidioc_querybuf,
1895 	.vidioc_qbuf		 = vidioc_qbuf,
1896 	.vidioc_dqbuf		 = vidioc_dqbuf,
1897 	.vidioc_streamon	 = vidioc_streamon,
1898 	.vidioc_streamoff	 = vidioc_streamoff,
1899 	.vidioc_log_status	 = vidioc_log_status,
1900 #ifdef CONFIG_VIDEO_ADV_DEBUG
1901 	.vidioc_g_register	 = cx231xx_g_register,
1902 	.vidioc_s_register	 = cx231xx_s_register,
1903 #endif
1904 	.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1905 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1906 };
1907 
1908 static struct video_device cx231xx_mpeg_template = {
1909 	.name          = "cx231xx",
1910 	.fops          = &mpeg_fops,
1911 	.ioctl_ops     = &mpeg_ioctl_ops,
1912 	.minor         = -1,
1913 	.tvnorms       = V4L2_STD_ALL,
1914 };
1915 
1916 void cx231xx_417_unregister(struct cx231xx *dev)
1917 {
1918 	dprintk(1, "%s()\n", __func__);
1919 	dprintk(3, "%s()\n", __func__);
1920 
1921 	if (video_is_registered(&dev->v4l_device)) {
1922 		video_unregister_device(&dev->v4l_device);
1923 		v4l2_ctrl_handler_free(&dev->mpeg_ctrl_handler.hdl);
1924 	}
1925 }
1926 
1927 static int cx231xx_s_video_encoding(struct cx2341x_handler *cxhdl, u32 val)
1928 {
1929 	struct cx231xx *dev = container_of(cxhdl, struct cx231xx, mpeg_ctrl_handler);
1930 	int is_mpeg1 = val == V4L2_MPEG_VIDEO_ENCODING_MPEG_1;
1931 	struct v4l2_subdev_format format = {
1932 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
1933 	};
1934 
1935 	/* fix videodecoder resolution */
1936 	format.format.width = cxhdl->width / (is_mpeg1 ? 2 : 1);
1937 	format.format.height = cxhdl->height;
1938 	format.format.code = MEDIA_BUS_FMT_FIXED;
1939 	v4l2_subdev_call(dev->sd_cx25840, pad, set_fmt, NULL, &format);
1940 	return 0;
1941 }
1942 
1943 static int cx231xx_s_audio_sampling_freq(struct cx2341x_handler *cxhdl, u32 idx)
1944 {
1945 	static const u32 freqs[3] = { 44100, 48000, 32000 };
1946 	struct cx231xx *dev = container_of(cxhdl, struct cx231xx, mpeg_ctrl_handler);
1947 
1948 	/* The audio clock of the digitizer must match the codec sample
1949 	   rate otherwise you get some very strange effects. */
1950 	if (idx < ARRAY_SIZE(freqs))
1951 		call_all(dev, audio, s_clock_freq, freqs[idx]);
1952 	return 0;
1953 }
1954 
1955 static const struct cx2341x_handler_ops cx231xx_ops = {
1956 	/* needed for the video clock freq */
1957 	.s_audio_sampling_freq = cx231xx_s_audio_sampling_freq,
1958 	/* needed for setting up the video resolution */
1959 	.s_video_encoding = cx231xx_s_video_encoding,
1960 };
1961 
1962 static void cx231xx_video_dev_init(
1963 	struct cx231xx *dev,
1964 	struct usb_device *usbdev,
1965 	struct video_device *vfd,
1966 	const struct video_device *template,
1967 	const char *type)
1968 {
1969 	dprintk(1, "%s()\n", __func__);
1970 	*vfd = *template;
1971 	snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)", dev->name,
1972 		type, cx231xx_boards[dev->model].name);
1973 
1974 	vfd->v4l2_dev = &dev->v4l2_dev;
1975 	vfd->lock = &dev->lock;
1976 	vfd->release = video_device_release_empty;
1977 	vfd->ctrl_handler = &dev->mpeg_ctrl_handler.hdl;
1978 	video_set_drvdata(vfd, dev);
1979 	if (dev->tuner_type == TUNER_ABSENT) {
1980 		v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
1981 		v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
1982 		v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
1983 		v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
1984 	}
1985 }
1986 
1987 int cx231xx_417_register(struct cx231xx *dev)
1988 {
1989 	/* FIXME: Port1 hardcoded here */
1990 	int err = -ENODEV;
1991 	struct cx231xx_tsport *tsport = &dev->ts1;
1992 
1993 	dprintk(1, "%s()\n", __func__);
1994 
1995 	/* Set default TV standard */
1996 	dev->encodernorm = cx231xx_tvnorms[0];
1997 
1998 	if (dev->encodernorm.id & V4L2_STD_525_60)
1999 		tsport->height = 480;
2000 	else
2001 		tsport->height = 576;
2002 
2003 	tsport->width = 720;
2004 	err = cx2341x_handler_init(&dev->mpeg_ctrl_handler, 50);
2005 	if (err) {
2006 		dprintk(3, "%s: can't init cx2341x controls\n", dev->name);
2007 		return err;
2008 	}
2009 	dev->mpeg_ctrl_handler.func = cx231xx_mbox_func;
2010 	dev->mpeg_ctrl_handler.priv = dev;
2011 	dev->mpeg_ctrl_handler.ops = &cx231xx_ops;
2012 	if (dev->sd_cx25840)
2013 		v4l2_ctrl_add_handler(&dev->mpeg_ctrl_handler.hdl,
2014 				dev->sd_cx25840->ctrl_handler, NULL, false);
2015 	if (dev->mpeg_ctrl_handler.hdl.error) {
2016 		err = dev->mpeg_ctrl_handler.hdl.error;
2017 		dprintk(3, "%s: can't add cx25840 controls\n", dev->name);
2018 		v4l2_ctrl_handler_free(&dev->mpeg_ctrl_handler.hdl);
2019 		return err;
2020 	}
2021 	dev->norm = V4L2_STD_NTSC;
2022 
2023 	dev->mpeg_ctrl_handler.port = CX2341X_PORT_SERIAL;
2024 	cx2341x_handler_set_50hz(&dev->mpeg_ctrl_handler, false);
2025 
2026 	/* Allocate and initialize V4L video device */
2027 	cx231xx_video_dev_init(dev, dev->udev,
2028 			&dev->v4l_device, &cx231xx_mpeg_template, "mpeg");
2029 	err = video_register_device(&dev->v4l_device,
2030 		VFL_TYPE_GRABBER, -1);
2031 	if (err < 0) {
2032 		dprintk(3, "%s: can't register mpeg device\n", dev->name);
2033 		v4l2_ctrl_handler_free(&dev->mpeg_ctrl_handler.hdl);
2034 		return err;
2035 	}
2036 
2037 	dprintk(3, "%s: registered device video%d [mpeg]\n",
2038 	       dev->name, dev->v4l_device.num);
2039 
2040 	return 0;
2041 }
2042 
2043 MODULE_FIRMWARE(CX231xx_FIRM_IMAGE_NAME);
2044