V4L/DVB (10956): cx231xx: First series of manual CodingStyle fixes
[safe/jmp/linux-2.6] / drivers / media / video / cx231xx / cx231xx-video.c
1 /*
2    cx231xx-video.c - driver for Conexant Cx23100/101/102
3                      USB video capture devices
4
5    Copyright (C) 2008 <srinivasa.deevi at conexant dot com>
6         Based on em28xx driver
7         Based on cx23885 driver
8         Based on cx88 driver
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include <linux/init.h>
26 #include <linux/list.h>
27 #include <linux/module.h>
28 #include <linux/kernel.h>
29 #include <linux/bitmap.h>
30 #include <linux/usb.h>
31 #include <linux/i2c.h>
32 #include <linux/version.h>
33 #include <linux/mm.h>
34 #include <linux/mutex.h>
35
36 #include <media/v4l2-common.h>
37 #include <media/v4l2-ioctl.h>
38 #include <media/v4l2-chip-ident.h>
39 #include <media/msp3400.h>
40 #include <media/tuner.h>
41
42 #include "dvb_frontend.h"
43
44 #include "cx231xx.h"
45 #include "cx231xx-vbi.h"
46
47 #define DRIVER_AUTHOR   "Srinivasa Deevi <srinivasa.deevi@conexant.com>"
48 #define DRIVER_DESC     "Conexant cx231xx based USB video device driver"
49
50 #define cx231xx_videodbg(fmt, arg...) do {\
51         if (video_debug) \
52                 printk(KERN_INFO "%s %s :"fmt, \
53                          dev->name, __func__ , ##arg); } while (0)
54
55 static unsigned int isoc_debug;
56 module_param(isoc_debug, int, 0644);
57 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
58
59 #define cx231xx_isocdbg(fmt, arg...) \
60 do {\
61         if (isoc_debug) { \
62                 printk(KERN_INFO "%s %s :"fmt, \
63                          dev->name, __func__ , ##arg); \
64         } \
65   } while (0)
66
67 MODULE_AUTHOR(DRIVER_AUTHOR);
68 MODULE_DESCRIPTION(DRIVER_DESC);
69 MODULE_LICENSE("GPL");
70
71 static unsigned int card[]     = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
72 static unsigned int video_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
73 static unsigned int vbi_nr[]   = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
74 static unsigned int radio_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
75
76 module_param_array(card, int, NULL, 0444);
77 module_param_array(video_nr, int, NULL, 0444);
78 module_param_array(vbi_nr, int, NULL, 0444);
79 module_param_array(radio_nr, int, NULL, 0444);
80
81 MODULE_PARM_DESC(card, "card type");
82 MODULE_PARM_DESC(video_nr, "video device numbers");
83 MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
84 MODULE_PARM_DESC(radio_nr, "radio device numbers");
85
86 static unsigned int video_debug;
87 module_param(video_debug, int, 0644);
88 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
89
90 /* supported video standards */
91 static struct cx231xx_fmt format[] = {
92         {
93          .name = "16bpp YUY2, 4:2:2, packed",
94          .fourcc = V4L2_PIX_FMT_YUYV,
95          .depth = 16,
96          .reg = 0,
97          },
98 };
99
100 /* supported controls */
101 /* Common to all boards */
102
103 /* ------------------------------------------------------------------- */
104
105 static const struct v4l2_queryctrl no_ctl = {
106         .name = "42",
107         .flags = V4L2_CTRL_FLAG_DISABLED,
108 };
109
110 static struct cx231xx_ctrl cx231xx_ctls[] = {
111         /* --- video --- */
112         {
113                 .v = {
114                         .id = V4L2_CID_BRIGHTNESS,
115                         .name = "Brightness",
116                         .minimum = 0x00,
117                         .maximum = 0xff,
118                         .step = 1,
119                         .default_value = 0x7f,
120                         .type = V4L2_CTRL_TYPE_INTEGER,
121                 },
122                 .off = 128,
123                 .reg = LUMA_CTRL,
124                 .mask = 0x00ff,
125                 .shift = 0,
126         }, {
127                 .v = {
128                         .id = V4L2_CID_CONTRAST,
129                         .name = "Contrast",
130                         .minimum = 0,
131                         .maximum = 0xff,
132                         .step = 1,
133                         .default_value = 0x3f,
134                         .type = V4L2_CTRL_TYPE_INTEGER,
135                 },
136                 .off = 0,
137                 .reg = LUMA_CTRL,
138                 .mask = 0xff00,
139                 .shift = 8,
140         }, {
141                 .v = {
142                         .id = V4L2_CID_HUE,
143                         .name = "Hue",
144                         .minimum = 0,
145                         .maximum = 0xff,
146                         .step = 1,
147                         .default_value = 0x7f,
148                         .type = V4L2_CTRL_TYPE_INTEGER,
149                 },
150                 .off = 128,
151                 .reg = CHROMA_CTRL,
152                 .mask = 0xff0000,
153                 .shift = 16,
154         }, {
155         /* strictly, this only describes only U saturation.
156         * V saturation is handled specially through code.
157         */
158                 .v = {
159                         .id = V4L2_CID_SATURATION,
160                         .name = "Saturation",
161                         .minimum = 0,
162                         .maximum = 0xff,
163                         .step = 1,
164                         .default_value = 0x7f,
165                         .type = V4L2_CTRL_TYPE_INTEGER,
166                 },
167                 .off = 0,
168                 .reg = CHROMA_CTRL,
169                 .mask = 0x00ff,
170                 .shift = 0,
171         }, {
172                 /* --- audio --- */
173                 .v = {
174                         .id = V4L2_CID_AUDIO_MUTE,
175                         .name = "Mute",
176                         .minimum = 0,
177                         .maximum = 1,
178                         .default_value = 1,
179                         .type = V4L2_CTRL_TYPE_BOOLEAN,
180                 },
181                 .reg = PATH1_CTL1,
182                 .mask = (0x1f << 24),
183                 .shift = 24,
184         }, {
185                 .v = {
186                         .id = V4L2_CID_AUDIO_VOLUME,
187                         .name = "Volume",
188                         .minimum = 0,
189                         .maximum = 0x3f,
190                         .step = 1,
191                         .default_value = 0x3f,
192                         .type = V4L2_CTRL_TYPE_INTEGER,
193                 },
194                 .reg = PATH1_VOL_CTL,
195                 .mask = 0xff,
196                 .shift = 0,
197         }
198 };
199 static const int CX231XX_CTLS = ARRAY_SIZE(cx231xx_ctls);
200
201 static const u32 cx231xx_user_ctrls[] = {
202         V4L2_CID_USER_CLASS,
203         V4L2_CID_BRIGHTNESS,
204         V4L2_CID_CONTRAST,
205         V4L2_CID_SATURATION,
206         V4L2_CID_HUE,
207         V4L2_CID_AUDIO_VOLUME,
208 #if 0
209         V4L2_CID_AUDIO_BALANCE,
210 #endif
211         V4L2_CID_AUDIO_MUTE,
212         0
213 };
214
215 static const u32 *ctrl_classes[] = {
216         cx231xx_user_ctrls,
217         NULL
218 };
219
220 /* ------------------------------------------------------------------
221         Video buffer and parser functions
222    ------------------------------------------------------------------*/
223
224 /*
225  * Announces that a buffer were filled and request the next
226  */
227 static inline void buffer_filled(struct cx231xx *dev,
228                                  struct cx231xx_dmaqueue *dma_q,
229                                  struct cx231xx_buffer *buf)
230 {
231         /* Advice that buffer was filled */
232         cx231xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
233         buf->vb.state = VIDEOBUF_DONE;
234         buf->vb.field_count++;
235         do_gettimeofday(&buf->vb.ts);
236
237         dev->video_mode.isoc_ctl.buf = NULL;
238
239         list_del(&buf->vb.queue);
240         wake_up(&buf->vb.done);
241 }
242
243 static inline void print_err_status(struct cx231xx *dev, int packet, int status)
244 {
245         char *errmsg = "Unknown";
246
247         switch (status) {
248         case -ENOENT:
249                 errmsg = "unlinked synchronuously";
250                 break;
251         case -ECONNRESET:
252                 errmsg = "unlinked asynchronuously";
253                 break;
254         case -ENOSR:
255                 errmsg = "Buffer error (overrun)";
256                 break;
257         case -EPIPE:
258                 errmsg = "Stalled (device not responding)";
259                 break;
260         case -EOVERFLOW:
261                 errmsg = "Babble (bad cable?)";
262                 break;
263         case -EPROTO:
264                 errmsg = "Bit-stuff error (bad cable?)";
265                 break;
266         case -EILSEQ:
267                 errmsg = "CRC/Timeout (could be anything)";
268                 break;
269         case -ETIME:
270                 errmsg = "Device does not respond";
271                 break;
272         }
273         if (packet < 0) {
274                 cx231xx_isocdbg("URB status %d [%s].\n", status, errmsg);
275         } else {
276                 cx231xx_isocdbg("URB packet %d, status %d [%s].\n",
277                                 packet, status, errmsg);
278         }
279 }
280
281 /*
282  * video-buf generic routine to get the next available buffer
283  */
284 static inline void get_next_buf(struct cx231xx_dmaqueue *dma_q,
285                                 struct cx231xx_buffer **buf)
286 {
287         struct cx231xx_video_mode *vmode =
288             container_of(dma_q, struct cx231xx_video_mode, vidq);
289         struct cx231xx *dev = container_of(vmode, struct cx231xx, video_mode);
290
291         char *outp;
292
293         if (list_empty(&dma_q->active)) {
294                 cx231xx_isocdbg("No active queue to serve\n");
295                 dev->video_mode.isoc_ctl.buf = NULL;
296                 *buf = NULL;
297                 return;
298         }
299
300         /* Get the next buffer */
301         *buf = list_entry(dma_q->active.next, struct cx231xx_buffer, vb.queue);
302
303         /* Cleans up buffer - Usefull for testing for frame/URB loss */
304         outp = videobuf_to_vmalloc(&(*buf)->vb);
305         memset(outp, 0, (*buf)->vb.size);
306
307         dev->video_mode.isoc_ctl.buf = *buf;
308
309         return;
310 }
311
312 /*
313  * Controls the isoc copy of each urb packet
314  */
315 static inline int cx231xx_isoc_copy(struct cx231xx *dev, struct urb *urb)
316 {
317         struct cx231xx_buffer *buf;
318         struct cx231xx_dmaqueue *dma_q = urb->context;
319         unsigned char *outp = NULL;
320         int i, rc = 1;
321         unsigned char *p_buffer;
322         u32 bytes_parsed = 0, buffer_size = 0;
323         u8 sav_eav = 0;
324
325         if (!dev)
326                 return 0;
327
328         if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED))
329                 return 0;
330
331         if (urb->status < 0) {
332                 print_err_status(dev, -1, urb->status);
333                 if (urb->status == -ENOENT)
334                         return 0;
335         }
336
337         buf = dev->video_mode.isoc_ctl.buf;
338         if (buf != NULL)
339                 outp = videobuf_to_vmalloc(&buf->vb);
340
341         for (i = 0; i < urb->number_of_packets; i++) {
342                 int status = urb->iso_frame_desc[i].status;
343
344                 if (status < 0) {
345                         print_err_status(dev, i, status);
346                         if (urb->iso_frame_desc[i].status != -EPROTO)
347                                 continue;
348                 }
349
350                 if (urb->iso_frame_desc[i].actual_length <= 0) {
351                         /* cx231xx_isocdbg("packet %d is empty",i); - spammy */
352                         continue;
353                 }
354                 if (urb->iso_frame_desc[i].actual_length >
355                     dev->video_mode.max_pkt_size) {
356                         cx231xx_isocdbg("packet bigger than packet size");
357                         continue;
358                 }
359
360                 /*  get buffer pointer and length */
361                 p_buffer = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
362                 buffer_size = urb->iso_frame_desc[i].actual_length;
363                 bytes_parsed = 0;
364
365                 if (dma_q->is_partial_line) {
366                         /* Handle the case where we were working on a partial line */
367                         sav_eav = dma_q->last_sav;
368                 } else {
369                         /* Check for a SAV/EAV overlapping the buffer boundary */
370                         sav_eav =
371                             cx231xx_find_boundary_SAV_EAV(p_buffer,
372                                                           dma_q->partial_buf,
373                                                           &bytes_parsed);
374                 }
375
376                 sav_eav &= 0xF0;
377                 /* Get the first line if we have some portion of an SAV/EAV from
378                    the last buffer or a partial line  */
379                 if (sav_eav) {
380                         bytes_parsed += cx231xx_get_video_line(dev, dma_q,
381                                                 sav_eav,        /* SAV/EAV */
382                                                 p_buffer + bytes_parsed,        /* p_buffer */
383                                                 buffer_size - bytes_parsed);    /* buffer size */
384                 }
385
386                 /* Now parse data that is completely in this buffer */
387                 /* dma_q->is_partial_line = 0;  */
388
389                 while (bytes_parsed < buffer_size) {
390                         u32 bytes_used = 0;
391
392                         sav_eav = cx231xx_find_next_SAV_EAV(p_buffer + bytes_parsed,    /* p_buffer */
393                                                 buffer_size - bytes_parsed,     /* buffer size */
394                                                 &bytes_used);   /* Receives bytes used to get SAV/EAV */
395
396                         bytes_parsed += bytes_used;
397
398                         sav_eav &= 0xF0;
399                         if (sav_eav && (bytes_parsed < buffer_size)) {
400                                 bytes_parsed += cx231xx_get_video_line(dev,
401                                                 dma_q, sav_eav, /* SAV/EAV */
402                                                 p_buffer + bytes_parsed,        /* p_buffer */
403                                                 buffer_size - bytes_parsed);    /* buffer size */
404                         }
405                 }
406
407                 /* Save the last four bytes of the buffer so we can check the
408                    buffer boundary condition next time */
409                 memcpy(dma_q->partial_buf, p_buffer + buffer_size - 4, 4);
410                 bytes_parsed = 0;
411
412         }
413         return rc;
414 }
415
416 u8 cx231xx_find_boundary_SAV_EAV(u8 *p_buffer, u8 *partial_buf,
417                                  u32 *p_bytes_used)
418 {
419         u32 bytes_used;
420         u8 boundary_bytes[8];
421         u8 sav_eav = 0;
422
423         *p_bytes_used = 0;
424
425         /* Create an array of the last 4 bytes of the last buffer and the first
426            4 bytes of the current buffer. */
427
428         memcpy(boundary_bytes, partial_buf, 4);
429         memcpy(boundary_bytes + 4, p_buffer, 4);
430
431         /* Check for the SAV/EAV in the boundary buffer */
432         sav_eav = cx231xx_find_next_SAV_EAV((u8 *)&boundary_bytes, 8,
433                                             &bytes_used);
434
435         if (sav_eav) {
436                 /* found a boundary SAV/EAV.  Updates the bytes used to reflect
437                    only those used in the new buffer */
438                 *p_bytes_used = bytes_used - 4;
439         }
440
441         return sav_eav;
442 }
443
444 u8 cx231xx_find_next_SAV_EAV(u8 *p_buffer, u32 buffer_size, u32 *p_bytes_used)
445 {
446         u32 i;
447         u8 sav_eav = 0;
448
449         /*
450          * Don't search if the buffer size is less than 4.  It causes a page
451          * fault since buffer_size - 4 evaluates to a large number in that
452          * case.
453          */
454         if (buffer_size < 4) {
455                 *p_bytes_used = buffer_size;
456                 return 0;
457         }
458
459         for (i = 0; i < (buffer_size - 3); i++) {
460
461                 if ((p_buffer[i] == 0xFF) &&
462                     (p_buffer[i + 1] == 0x00) && (p_buffer[i + 2] == 0x00)) {
463
464                         *p_bytes_used = i + 4;
465                         sav_eav = p_buffer[i + 3];
466                         return sav_eav;
467                 }
468         }
469
470         *p_bytes_used = buffer_size;
471         return 0;
472 }
473
474 u32 cx231xx_get_video_line(struct cx231xx *dev,
475                            struct cx231xx_dmaqueue *dma_q, u8 sav_eav,
476                            u8 *p_buffer, u32 buffer_size)
477 {
478         u32 bytes_copied = 0;
479         int current_field = -1;
480
481         switch (sav_eav) {
482         case SAV_ACTIVE_VIDEO_FIELD1:
483                 /* looking for skipped line which occurred in PAL 720x480 mode.
484                    In this case, there will be no active data contained
485                    between the SAV and EAV */
486                 if ((buffer_size > 3) && (p_buffer[0] == 0xFF) &&
487                     (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) &&
488                     ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) ||
489                      (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) ||
490                      (p_buffer[3] == EAV_VBLANK_FIELD1) ||
491                      (p_buffer[3] == EAV_VBLANK_FIELD2)))
492                         return bytes_copied;
493                 current_field = 1;
494                 break;
495
496         case SAV_ACTIVE_VIDEO_FIELD2:
497                 /* looking for skipped line which occurred in PAL 720x480 mode.
498                    In this case, there will be no active data contained between
499                    the SAV and EAV */
500                 if ((buffer_size > 3) && (p_buffer[0] == 0xFF) &&
501                     (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) &&
502                     ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) ||
503                      (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) ||
504                      (p_buffer[3] == EAV_VBLANK_FIELD1)       ||
505                      (p_buffer[3] == EAV_VBLANK_FIELD2)))
506                         return bytes_copied;
507                 current_field = 2;
508                 break;
509         }
510
511         dma_q->last_sav = sav_eav;
512
513         bytes_copied = cx231xx_copy_video_line(dev, dma_q, p_buffer,
514                                                buffer_size, current_field);
515
516         return bytes_copied;
517 }
518
519 u32 cx231xx_copy_video_line(struct cx231xx *dev,
520                             struct cx231xx_dmaqueue *dma_q, u8 *p_line,
521                             u32 length, int field_number)
522 {
523         u32 bytes_to_copy;
524         struct cx231xx_buffer *buf;
525         u32 _line_size = dev->width * 2;
526
527         if (dma_q->current_field != field_number)
528                 cx231xx_reset_video_buffer(dev, dma_q);
529
530         /* get the buffer pointer */
531         buf = dev->video_mode.isoc_ctl.buf;
532
533         /* Remember the field number for next time */
534         dma_q->current_field = field_number;
535
536         bytes_to_copy = dma_q->bytes_left_in_line;
537         if (bytes_to_copy > length)
538                 bytes_to_copy = length;
539
540         if (dma_q->lines_completed >= dma_q->lines_per_field) {
541                 dma_q->bytes_left_in_line -= bytes_to_copy;
542                 dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0) ?
543                                           0 : 1;
544                 return 0;
545         }
546
547         dma_q->is_partial_line = 1;
548
549         /* If we don't have a buffer, just return the number of bytes we would
550            have copied if we had a buffer. */
551         if (!buf) {
552                 dma_q->bytes_left_in_line -= bytes_to_copy;
553                 dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0)
554                                          ? 0 : 1;
555                 return bytes_to_copy;
556         }
557
558         /* copy the data to video buffer */
559         cx231xx_do_copy(dev, dma_q, p_line, bytes_to_copy);
560
561         dma_q->pos += bytes_to_copy;
562         dma_q->bytes_left_in_line -= bytes_to_copy;
563
564         if (dma_q->bytes_left_in_line == 0) {
565                 dma_q->bytes_left_in_line = _line_size;
566                 dma_q->lines_completed++;
567                 dma_q->is_partial_line = 0;
568
569                 if (cx231xx_is_buffer_done(dev, dma_q) && buf) {
570                         buffer_filled(dev, dma_q, buf);
571
572                         dma_q->pos = 0;
573                         buf = NULL;
574                         dma_q->lines_completed = 0;
575                 }
576         }
577
578         return bytes_to_copy;
579 }
580
581 void cx231xx_reset_video_buffer(struct cx231xx *dev,
582                                 struct cx231xx_dmaqueue *dma_q)
583 {
584         struct cx231xx_buffer *buf;
585
586         /* handle the switch from field 1 to field 2 */
587         if (dma_q->current_field == 1) {
588                 if (dma_q->lines_completed >= dma_q->lines_per_field)
589                         dma_q->field1_done = 1;
590                 else
591                         dma_q->field1_done = 0;
592         }
593
594         buf = dev->video_mode.isoc_ctl.buf;
595
596         if (buf == NULL) {
597                 u8 *outp = NULL;
598                 /* first try to get the buffer */
599                 get_next_buf(dma_q, &buf);
600
601                 if (buf)
602                         outp = videobuf_to_vmalloc(&buf->vb);
603
604                 dma_q->pos = 0;
605                 dma_q->field1_done = 0;
606                 dma_q->current_field = -1;
607         }
608
609         /* reset the counters */
610         dma_q->bytes_left_in_line = dev->width << 1;
611         dma_q->lines_completed = 0;
612 }
613
614 int cx231xx_do_copy(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q,
615                     u8 *p_buffer, u32 bytes_to_copy)
616 {
617         u8 *p_out_buffer = NULL;
618         u32 current_line_bytes_copied = 0;
619         struct cx231xx_buffer *buf;
620         u32 _line_size = dev->width << 1;
621         void *startwrite;
622         int offset, lencopy;
623
624         buf = dev->video_mode.isoc_ctl.buf;
625
626         if (buf == NULL)
627                 return -1;
628
629         p_out_buffer = videobuf_to_vmalloc(&buf->vb);
630
631         current_line_bytes_copied = _line_size - dma_q->bytes_left_in_line;
632
633         /* Offset field 2 one line from the top of the buffer */
634         offset = (dma_q->current_field == 1) ? 0 : _line_size;
635
636         /* Offset for field 2 */
637         startwrite = p_out_buffer + offset;
638
639         /* lines already completed in the current field */
640         startwrite += (dma_q->lines_completed * _line_size * 2);
641
642         /* bytes already completed in the current line */
643         startwrite += current_line_bytes_copied;
644
645         lencopy = dma_q->bytes_left_in_line > bytes_to_copy ?
646                   bytes_to_copy : dma_q->bytes_left_in_line;
647
648         if ((u8 *)(startwrite + lencopy) > (u8 *)(p_out_buffer + buf->vb.size))
649                 return 0;
650
651         /* The below copies the UYVY data straight into video buffer */
652         cx231xx_swab((u16 *) p_buffer, (u16 *) startwrite, (u16) lencopy);
653
654         return 0;
655 }
656
657 void cx231xx_swab(u16 *from, u16 *to, u16 len)
658 {
659         u16 i;
660
661         if (len <= 0)
662                 return;
663
664         for (i = 0; i < len / 2; i++)
665                 to[i] = (from[i] << 8) | (from[i] >> 8);
666 }
667
668 u8 cx231xx_is_buffer_done(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q)
669 {
670         u8 buffer_complete = 0;
671
672         /* Dual field stream */
673         buffer_complete = ((dma_q->current_field == 2) &&
674                            (dma_q->lines_completed >= dma_q->lines_per_field) &&
675                             dma_q->field1_done);
676
677         return buffer_complete;
678 }
679
680 /* ------------------------------------------------------------------
681         Videobuf operations
682    ------------------------------------------------------------------*/
683
684 static int
685 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
686 {
687         struct cx231xx_fh *fh = vq->priv_data;
688         struct cx231xx *dev = fh->dev;
689         struct v4l2_frequency f;
690
691         *size = (fh->dev->width * fh->dev->height * dev->format->depth + 7)>>3;
692         if (0 == *count)
693                 *count = CX231XX_DEF_BUF;
694
695         if (*count < CX231XX_MIN_BUF)
696                 *count = CX231XX_MIN_BUF;
697
698         /* Ask tuner to go to analog mode */
699         memset(&f, 0, sizeof(f));
700         f.frequency = dev->ctl_freq;
701         f.type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
702
703         cx231xx_i2c_call_clients(&dev->i2c_bus[1], VIDIOC_S_FREQUENCY, &f);
704
705         return 0;
706 }
707
708 /* This is called *without* dev->slock held; please keep it that way */
709 static void free_buffer(struct videobuf_queue *vq, struct cx231xx_buffer *buf)
710 {
711         struct cx231xx_fh *fh = vq->priv_data;
712         struct cx231xx *dev = fh->dev;
713         unsigned long flags = 0;
714
715         if (in_interrupt())
716                 BUG();
717
718         /* We used to wait for the buffer to finish here, but this didn't work
719            because, as we were keeping the state as VIDEOBUF_QUEUED,
720            videobuf_queue_cancel marked it as finished for us.
721            (Also, it could wedge forever if the hardware was misconfigured.)
722
723            This should be safe; by the time we get here, the buffer isn't
724            queued anymore. If we ever start marking the buffers as
725            VIDEOBUF_ACTIVE, it won't be, though.
726          */
727         spin_lock_irqsave(&dev->video_mode.slock, flags);
728         if (dev->video_mode.isoc_ctl.buf == buf)
729                 dev->video_mode.isoc_ctl.buf = NULL;
730         spin_unlock_irqrestore(&dev->video_mode.slock, flags);
731
732         videobuf_vmalloc_free(&buf->vb);
733         buf->vb.state = VIDEOBUF_NEEDS_INIT;
734 }
735
736 static int
737 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
738                enum v4l2_field field)
739 {
740         struct cx231xx_fh *fh = vq->priv_data;
741         struct cx231xx_buffer *buf =
742             container_of(vb, struct cx231xx_buffer, vb);
743         struct cx231xx *dev = fh->dev;
744         int rc = 0, urb_init = 0;
745
746         /* The only currently supported format is 16 bits/pixel */
747         buf->vb.size = (fh->dev->width * fh->dev->height * dev->format->depth
748                         + 7) >> 3;
749         if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
750                 return -EINVAL;
751
752         buf->vb.width = dev->width;
753         buf->vb.height = dev->height;
754         buf->vb.field = field;
755
756         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
757                 rc = videobuf_iolock(vq, &buf->vb, NULL);
758                 if (rc < 0)
759                         goto fail;
760         }
761
762         if (!dev->video_mode.isoc_ctl.num_bufs)
763                 urb_init = 1;
764
765         if (urb_init) {
766                 rc = cx231xx_init_isoc(dev, CX231XX_NUM_PACKETS,
767                                        CX231XX_NUM_BUFS,
768                                        dev->video_mode.max_pkt_size,
769                                        cx231xx_isoc_copy);
770                 if (rc < 0)
771                         goto fail;
772         }
773
774         buf->vb.state = VIDEOBUF_PREPARED;
775         return 0;
776
777 fail:
778         free_buffer(vq, buf);
779         return rc;
780 }
781
782 static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
783 {
784         struct cx231xx_buffer *buf =
785             container_of(vb, struct cx231xx_buffer, vb);
786         struct cx231xx_fh *fh = vq->priv_data;
787         struct cx231xx *dev = fh->dev;
788         struct cx231xx_dmaqueue *vidq = &dev->video_mode.vidq;
789
790         buf->vb.state = VIDEOBUF_QUEUED;
791         list_add_tail(&buf->vb.queue, &vidq->active);
792
793 }
794
795 static void buffer_release(struct videobuf_queue *vq,
796                            struct videobuf_buffer *vb)
797 {
798         struct cx231xx_buffer *buf =
799             container_of(vb, struct cx231xx_buffer, vb);
800         struct cx231xx_fh *fh = vq->priv_data;
801         struct cx231xx *dev = (struct cx231xx *)fh->dev;
802
803         cx231xx_isocdbg("cx231xx: called buffer_release\n");
804
805         free_buffer(vq, buf);
806 }
807
808 static struct videobuf_queue_ops cx231xx_video_qops = {
809         .buf_setup = buffer_setup,
810         .buf_prepare = buffer_prepare,
811         .buf_queue = buffer_queue,
812         .buf_release = buffer_release,
813 };
814
815 /*********************  v4l2 interface  **************************************/
816
817 void video_mux(struct cx231xx *dev, int index)
818 {
819
820         struct v4l2_routing route;
821
822         route.input = INPUT(index)->vmux;
823         route.output = 0;
824         dev->video_input = index;
825         dev->ctl_ainput = INPUT(index)->amux;
826
827         cx231xx_set_video_input_mux(dev, index);
828
829         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_INT_S_VIDEO_ROUTING,
830                                  &route);
831
832         cx231xx_set_audio_input(dev, dev->ctl_ainput);
833
834         cx231xx_info("video_mux : %d\n", index);
835
836         /* do mode control overrides if required */
837         cx231xx_do_mode_ctrl_overrides(dev);
838 }
839
840 /* Usage lock check functions */
841 static int res_get(struct cx231xx_fh *fh)
842 {
843         struct cx231xx *dev = fh->dev;
844         int rc = 0;
845
846         /* This instance already has stream_on */
847         if (fh->stream_on)
848                 return rc;
849
850         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
851                 if (dev->stream_on)
852                         return -EBUSY;
853                 dev->stream_on = 1;
854         } else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
855                 if (dev->vbi_stream_on)
856                         return -EBUSY;
857                 dev->vbi_stream_on = 1;
858         } else
859                 return -EINVAL;
860
861         fh->stream_on = 1;
862
863         return rc;
864 }
865
866 static int res_check(struct cx231xx_fh *fh)
867 {
868         return fh->stream_on;
869 }
870
871 static void res_free(struct cx231xx_fh *fh)
872 {
873         struct cx231xx *dev = fh->dev;
874
875         fh->stream_on = 0;
876
877         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
878                 dev->stream_on = 0;
879         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
880                 dev->vbi_stream_on = 0;
881 }
882
883 static int check_dev(struct cx231xx *dev)
884 {
885         if (dev->state & DEV_DISCONNECTED) {
886                 cx231xx_errdev("v4l2 ioctl: device not present\n");
887                 return -ENODEV;
888         }
889
890         if (dev->state & DEV_MISCONFIGURED) {
891                 cx231xx_errdev("v4l2 ioctl: device is misconfigured; "
892                                "close and open it again\n");
893                 return -EIO;
894         }
895         return 0;
896 }
897
898 void get_scale(struct cx231xx *dev,
899                unsigned int width, unsigned int height,
900                unsigned int *hscale, unsigned int *vscale)
901 {
902         unsigned int maxw = norm_maxw(dev);
903         unsigned int maxh = norm_maxh(dev);
904
905         *hscale = (((unsigned long)maxw) << 12) / width - 4096L;
906         if (*hscale >= 0x4000)
907                 *hscale = 0x3fff;
908
909         *vscale = (((unsigned long)maxh) << 12) / height - 4096L;
910         if (*vscale >= 0x4000)
911                 *vscale = 0x3fff;
912
913         dev->hscale = *hscale;
914         dev->vscale = *vscale;
915
916 }
917
918 /* ------------------------------------------------------------------
919         IOCTL vidioc handling
920    ------------------------------------------------------------------*/
921
922 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
923                                 struct v4l2_format *f)
924 {
925         struct cx231xx_fh *fh = priv;
926         struct cx231xx *dev = fh->dev;
927
928         mutex_lock(&dev->lock);
929
930         f->fmt.pix.width = dev->width;
931         f->fmt.pix.height = dev->height;
932         f->fmt.pix.pixelformat = dev->format->fourcc;;
933         f->fmt.pix.bytesperline = (dev->width * dev->format->depth + 7) >> 3;;
934         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * dev->height;
935         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
936
937         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
938
939         mutex_unlock(&dev->lock);
940
941         return 0;
942 }
943
944 static struct cx231xx_fmt *format_by_fourcc(unsigned int fourcc)
945 {
946         unsigned int i;
947
948         for (i = 0; i < ARRAY_SIZE(format); i++)
949                 if (format[i].fourcc == fourcc)
950                         return &format[i];
951
952         return NULL;
953 }
954
955 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
956                                   struct v4l2_format *f)
957 {
958         struct cx231xx_fh *fh = priv;
959         struct cx231xx *dev = fh->dev;
960         int width = f->fmt.pix.width;
961         int height = f->fmt.pix.height;
962         unsigned int maxw = norm_maxw(dev);
963         unsigned int maxh = norm_maxh(dev);
964         unsigned int hscale, vscale;
965         struct cx231xx_fmt *fmt;
966
967         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
968         if (!fmt) {
969                 cx231xx_videodbg("Fourcc format (%08x) invalid.\n",
970                                  f->fmt.pix.pixelformat);
971                 return -EINVAL;
972         }
973
974         /* width must even because of the YUYV format
975            height must be even because of interlacing */
976         height &= 0xfffe;
977         width &= 0xfffe;
978
979         if (unlikely(height < 32))
980                 height = 32;
981         if (unlikely(height > maxh))
982                 height = maxh;
983         if (unlikely(width < 48))
984                 width = 48;
985         if (unlikely(width > maxw))
986                 width = maxw;
987
988         get_scale(dev, width, height, &hscale, &vscale);
989
990         width = (((unsigned long)maxw) << 12) / (hscale + 4096L);
991         height = (((unsigned long)maxh) << 12) / (vscale + 4096L);
992
993         f->fmt.pix.width = width;
994         f->fmt.pix.height = height;
995         f->fmt.pix.pixelformat = fmt->fourcc;
996         f->fmt.pix.bytesperline = (dev->width * fmt->depth + 7) >> 3;
997         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
998         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
999         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1000
1001         return 0;
1002 }
1003
1004 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1005                                 struct v4l2_format *f)
1006 {
1007         struct cx231xx_fh *fh = priv;
1008         struct cx231xx *dev = fh->dev;
1009         int rc;
1010         struct cx231xx_fmt *fmt;
1011
1012         rc = check_dev(dev);
1013         if (rc < 0)
1014                 return rc;
1015
1016         mutex_lock(&dev->lock);
1017
1018         vidioc_try_fmt_vid_cap(file, priv, f);
1019
1020         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1021         if (!fmt) {
1022                 rc = -EINVAL;
1023                 goto out;
1024         }
1025
1026         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
1027                 cx231xx_errdev("%s queue busy\n", __func__);
1028                 rc = -EBUSY;
1029                 goto out;
1030         }
1031
1032         if (dev->stream_on && !fh->stream_on) {
1033                 cx231xx_errdev("%s device in use by another fh\n", __func__);
1034                 rc = -EBUSY;
1035                 goto out;
1036         }
1037
1038         /* set new image size */
1039         dev->width = f->fmt.pix.width;
1040         dev->height = f->fmt.pix.height;
1041         dev->format = fmt;
1042         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
1043
1044         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_S_FMT, f);
1045
1046         /* Set the correct alternate setting for this resolution */
1047         cx231xx_resolution_set(dev);
1048
1049 out:
1050         mutex_unlock(&dev->lock);
1051         return rc;
1052 }
1053
1054 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id * id)
1055 {
1056         struct cx231xx_fh *fh = priv;
1057         struct cx231xx *dev = fh->dev;
1058
1059         *id = dev->norm;
1060         return 0;
1061 }
1062
1063 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id * norm)
1064 {
1065         struct cx231xx_fh *fh = priv;
1066         struct cx231xx *dev = fh->dev;
1067         struct v4l2_format f;
1068         int rc;
1069
1070         rc = check_dev(dev);
1071         if (rc < 0)
1072                 return rc;
1073
1074         cx231xx_info("vidioc_s_std : 0x%x\n", (unsigned int)*norm);
1075
1076         mutex_lock(&dev->lock);
1077         dev->norm = *norm;
1078
1079         /* Adjusts width/height, if needed */
1080         f.fmt.pix.width = dev->width;
1081         f.fmt.pix.height = dev->height;
1082         vidioc_try_fmt_vid_cap(file, priv, &f);
1083
1084         /* set new image size */
1085         dev->width = f.fmt.pix.width;
1086         dev->height = f.fmt.pix.height;
1087         get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale);
1088
1089         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_S_STD, &dev->norm);
1090
1091         mutex_unlock(&dev->lock);
1092
1093         cx231xx_resolution_set(dev);
1094
1095         /* do mode control overrides */
1096         cx231xx_do_mode_ctrl_overrides(dev);
1097
1098         return 0;
1099 }
1100
1101 static const char *iname[] = {
1102         [CX231XX_VMUX_COMPOSITE1] = "Composite1",
1103         [CX231XX_VMUX_SVIDEO]     = "S-Video",
1104         [CX231XX_VMUX_TELEVISION] = "Television",
1105         [CX231XX_VMUX_CABLE]      = "Cable TV",
1106         [CX231XX_VMUX_DVB]        = "DVB",
1107         [CX231XX_VMUX_DEBUG]      = "for debug only",
1108 };
1109
1110 static int vidioc_enum_input(struct file *file, void *priv,
1111                              struct v4l2_input *i)
1112 {
1113         struct cx231xx_fh *fh = priv;
1114         struct cx231xx *dev = fh->dev;
1115         unsigned int n;
1116
1117         n = i->index;
1118         if (n >= MAX_CX231XX_INPUT)
1119                 return -EINVAL;
1120         if (0 == INPUT(n)->type)
1121                 return -EINVAL;
1122
1123         i->index = n;
1124         i->type = V4L2_INPUT_TYPE_CAMERA;
1125
1126         strcpy(i->name, iname[INPUT(n)->type]);
1127
1128         if ((CX231XX_VMUX_TELEVISION == INPUT(n)->type) ||
1129             (CX231XX_VMUX_CABLE == INPUT(n)->type))
1130                 i->type = V4L2_INPUT_TYPE_TUNER;
1131
1132         i->std = dev->vdev->tvnorms;
1133
1134         return 0;
1135 }
1136
1137 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1138 {
1139         struct cx231xx_fh *fh = priv;
1140         struct cx231xx *dev = fh->dev;
1141
1142         *i = dev->video_input;
1143
1144         return 0;
1145 }
1146
1147 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1148 {
1149         struct cx231xx_fh *fh = priv;
1150         struct cx231xx *dev = fh->dev;
1151         int rc;
1152
1153         rc = check_dev(dev);
1154         if (rc < 0)
1155                 return rc;
1156
1157         if (i >= MAX_CX231XX_INPUT)
1158                 return -EINVAL;
1159         if (0 == INPUT(i)->type)
1160                 return -EINVAL;
1161
1162         mutex_lock(&dev->lock);
1163
1164         video_mux(dev, i);
1165
1166         mutex_unlock(&dev->lock);
1167         return 0;
1168 }
1169
1170 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1171 {
1172         struct cx231xx_fh *fh = priv;
1173         struct cx231xx *dev = fh->dev;
1174
1175         switch (a->index) {
1176         case CX231XX_AMUX_VIDEO:
1177                 strcpy(a->name, "Television");
1178                 break;
1179         case CX231XX_AMUX_LINE_IN:
1180                 strcpy(a->name, "Line In");
1181                 break;
1182         default:
1183                 return -EINVAL;
1184         }
1185
1186         a->index = dev->ctl_ainput;
1187         a->capability = V4L2_AUDCAP_STEREO;
1188
1189         return 0;
1190 }
1191
1192 static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a)
1193 {
1194         struct cx231xx_fh *fh = priv;
1195         struct cx231xx *dev = fh->dev;
1196         int status = 0;
1197
1198         /* Doesn't allow manual routing */
1199         if (a->index != dev->ctl_ainput)
1200                 return -EINVAL;
1201
1202         dev->ctl_ainput = INPUT(a->index)->amux;
1203         status = cx231xx_set_audio_input(dev, dev->ctl_ainput);
1204
1205         return status;
1206 }
1207
1208 static int vidioc_queryctrl(struct file *file, void *priv,
1209                             struct v4l2_queryctrl *qc)
1210 {
1211         struct cx231xx_fh *fh = priv;
1212         struct cx231xx *dev = fh->dev;
1213         int id = qc->id;
1214         int i;
1215         int rc;
1216
1217         rc = check_dev(dev);
1218         if (rc < 0)
1219                 return rc;
1220
1221         qc->id = v4l2_ctrl_next(ctrl_classes, qc->id);
1222         if (unlikely(qc->id == 0))
1223                 return -EINVAL;
1224
1225         memset(qc, 0, sizeof(*qc));
1226
1227         qc->id = id;
1228
1229         if (qc->id < V4L2_CID_BASE || qc->id >= V4L2_CID_LASTP1)
1230                 return -EINVAL;
1231
1232         for (i = 0; i < CX231XX_CTLS; i++)
1233                 if (cx231xx_ctls[i].v.id == qc->id)
1234                         break;
1235
1236         if (i == CX231XX_CTLS) {
1237                 *qc = no_ctl;
1238                 return 0;
1239         }
1240         *qc = cx231xx_ctls[i].v;
1241
1242         mutex_lock(&dev->lock);
1243         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_QUERYCTRL, qc);
1244         mutex_unlock(&dev->lock);
1245
1246         if (qc->type)
1247                 return 0;
1248         else
1249                 return -EINVAL;
1250 }
1251
1252 static int vidioc_g_ctrl(struct file *file, void *priv,
1253                          struct v4l2_control *ctrl)
1254 {
1255         struct cx231xx_fh *fh = priv;
1256         struct cx231xx *dev = fh->dev;
1257         int rc;
1258
1259         rc = check_dev(dev);
1260         if (rc < 0)
1261                 return rc;
1262
1263         mutex_lock(&dev->lock);
1264
1265         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_G_CTRL, ctrl);
1266
1267         mutex_unlock(&dev->lock);
1268         return rc;
1269 }
1270
1271 static int vidioc_s_ctrl(struct file *file, void *priv,
1272                          struct v4l2_control *ctrl)
1273 {
1274         struct cx231xx_fh *fh = priv;
1275         struct cx231xx *dev = fh->dev;
1276         int rc;
1277
1278         rc = check_dev(dev);
1279         if (rc < 0)
1280                 return rc;
1281
1282         mutex_lock(&dev->lock);
1283
1284         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_S_CTRL, ctrl);
1285
1286         mutex_unlock(&dev->lock);
1287         return rc;
1288 }
1289
1290 static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1291 {
1292         struct cx231xx_fh *fh = priv;
1293         struct cx231xx *dev = fh->dev;
1294         int rc;
1295
1296         rc = check_dev(dev);
1297         if (rc < 0)
1298                 return rc;
1299
1300         if (0 != t->index)
1301                 return -EINVAL;
1302
1303         strcpy(t->name, "Tuner");
1304
1305         t->type = V4L2_TUNER_ANALOG_TV;
1306         t->capability = V4L2_TUNER_CAP_NORM;
1307         t->rangehigh = 0xffffffffUL;
1308         t->signal = 0xffff;     /* LOCKED */
1309
1310         return 0;
1311 }
1312
1313 static int vidioc_s_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1314 {
1315         struct cx231xx_fh *fh = priv;
1316         struct cx231xx *dev = fh->dev;
1317         int rc;
1318
1319         rc = check_dev(dev);
1320         if (rc < 0)
1321                 return rc;
1322
1323         if (0 != t->index)
1324                 return -EINVAL;
1325 #if 0
1326         mutex_lock(&dev->lock);
1327
1328         cx231xx_i2c_call_clients(&dev->i2c_bus[1], VIDIOC_S_TUNER, t);
1329
1330         mutex_unlock(&dev->lock);
1331 #endif
1332         return 0;
1333 }
1334
1335 static int vidioc_g_frequency(struct file *file, void *priv,
1336                               struct v4l2_frequency *f)
1337 {
1338         struct cx231xx_fh *fh = priv;
1339         struct cx231xx *dev = fh->dev;
1340
1341         mutex_lock(&dev->lock);
1342         f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
1343         f->frequency = dev->ctl_freq;
1344
1345         cx231xx_i2c_call_clients(&dev->i2c_bus[1], VIDIOC_G_FREQUENCY, f);
1346
1347         mutex_unlock(&dev->lock);
1348
1349         return 0;
1350 }
1351
1352 static int vidioc_s_frequency(struct file *file, void *priv,
1353                               struct v4l2_frequency *f)
1354 {
1355         struct cx231xx_fh *fh = priv;
1356         struct cx231xx *dev = fh->dev;
1357         int rc;
1358
1359         rc = check_dev(dev);
1360         if (rc < 0)
1361                 return rc;
1362
1363         if (0 != f->tuner)
1364                 return -EINVAL;
1365
1366         if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
1367                 return -EINVAL;
1368         if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
1369                 return -EINVAL;
1370
1371         /* set pre channel change settings in DIF first */
1372         rc = cx231xx_tuner_pre_channel_change(dev);
1373
1374         mutex_lock(&dev->lock);
1375
1376         dev->ctl_freq = f->frequency;
1377
1378         if (dev->tuner_type == TUNER_XC5000) {
1379                 if (dev->cx231xx_set_analog_freq != NULL)
1380                         dev->cx231xx_set_analog_freq(dev, f->frequency);
1381         } else {
1382                 cx231xx_i2c_call_clients(&dev->i2c_bus[1],
1383                                          VIDIOC_S_FREQUENCY, f);
1384         }
1385
1386         mutex_unlock(&dev->lock);
1387
1388         /* set post channel change settings in DIF first */
1389         rc = cx231xx_tuner_post_channel_change(dev);
1390
1391         cx231xx_info("Set New FREQUENCY to %d\n", f->frequency);
1392
1393         return rc;
1394 }
1395
1396 #ifdef CONFIG_VIDEO_ADV_DEBUG
1397
1398 /*
1399   -R, --list-registers=type=<host/i2cdrv/i2caddr>,chip=<chip>[,min=<addr>,max=<addr>]
1400                      dump registers from <min> to <max> [VIDIOC_DBG_G_REGISTER]
1401   -r, --set-register=type=<host/i2cdrv/i2caddr>,chip=<chip>,reg=<addr>,val=<val>
1402                      set the register [VIDIOC_DBG_S_REGISTER]
1403
1404   if type == host, then <chip> is the hosts chip ID (default 0)
1405   if type == i2cdrv (default), then <chip> is the I2C driver name or ID
1406   if type == i2caddr, then <chip> is the 7-bit I2C address
1407 */
1408
1409 static int vidioc_g_register(struct file *file, void *priv,
1410                              struct v4l2_dbg_register *reg)
1411 {
1412         struct cx231xx_fh *fh = priv;
1413         struct cx231xx *dev = fh->dev;
1414         int ret = 0;
1415         u8 value[4] = { 0, 0, 0, 0 };
1416         u32 data = 0;
1417
1418         switch (reg->match.type) {
1419         case V4L2_CHIP_MATCH_HOST:
1420                 switch (reg->match.addr) {
1421                 case 0: /* Cx231xx - internal registers */
1422                         ret = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER,
1423                                                   (u16)reg->reg, value, 4);
1424                         reg->val = value[0] | value[1] << 8 |
1425                                    value[2] << 16 | value[3] << 24;
1426                         break;
1427                 case 1: /* Colibri - read byte */
1428                         ret = cx231xx_read_i2c_data(dev, Colibri_DEVICE_ADDRESS,
1429                                                   (u16)reg->reg, 2, &data, 1);
1430                         reg->val = le32_to_cpu(data & 0xff);
1431                         break;
1432                 case 14:        /* Colibri - read dword */
1433                         ret = cx231xx_read_i2c_data(dev, Colibri_DEVICE_ADDRESS,
1434                                                   (u16)reg->reg, 2, &data, 4);
1435                         reg->val = le32_to_cpu(data);
1436                         break;
1437                 case 2: /* Hammerhead - read byte */
1438                         ret = cx231xx_read_i2c_data(dev, HAMMERHEAD_I2C_ADDRESS,
1439                                                   (u16)reg->reg, 2, &data, 1);
1440                         reg->val = le32_to_cpu(data & 0xff);
1441                         break;
1442                 case 24:        /* Hammerhead - read dword */
1443                         ret = cx231xx_read_i2c_data(dev, HAMMERHEAD_I2C_ADDRESS,
1444                                                   (u16)reg->reg, 2, &data, 4);
1445                         reg->val = le32_to_cpu(data);
1446                         break;
1447                 case 3: /* flatiron - read byte */
1448                         ret = cx231xx_read_i2c_data(dev,
1449                                                     Flatrion_DEVICE_ADDRESS,
1450                                                     (u16)reg->reg, 1,
1451                                                     &data, 1);
1452                         reg->val = le32_to_cpu(data & 0xff);
1453                         break;
1454                 case 34:        /* flatiron - read dword */
1455                         ret =
1456                             cx231xx_read_i2c_data(dev, Flatrion_DEVICE_ADDRESS,
1457                                                   (u16)reg->reg, 1, &data, 4);
1458                         reg->val = le32_to_cpu(data);
1459                         break;
1460                 }
1461                 return ret < 0 ? ret : 0;
1462
1463         case V4L2_CHIP_MATCH_I2C_DRIVER:
1464                 cx231xx_i2c_call_clients(&dev->i2c_bus[0],
1465                                          VIDIOC_DBG_G_REGISTER, reg);
1466                 return 0;
1467         case V4L2_CHIP_MATCH_I2C_ADDR:
1468                 /* Not supported yet */
1469                 return -EINVAL;
1470         default:
1471                 if (!v4l2_chip_match_host(&reg->match))
1472                         return -EINVAL;
1473         }
1474
1475         mutex_lock(&dev->lock);
1476         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_DBG_G_REGISTER, reg);
1477         mutex_unlock(&dev->lock);
1478
1479         return ret;
1480 }
1481
1482 static int vidioc_s_register(struct file *file, void *priv,
1483                              struct v4l2_dbg_register *reg)
1484 {
1485         struct cx231xx_fh *fh = priv;
1486         struct cx231xx *dev = fh->dev;
1487         int ret = 0;
1488         __le64 buf;
1489         u32 value;
1490         u8 data[4] = { 0, 0, 0, 0 };
1491
1492         buf = cpu_to_le64(reg->val);
1493
1494         switch (reg->match.type) {
1495         case V4L2_CHIP_MATCH_HOST:
1496                 {
1497                         value = (u32) buf & 0xffffffff;
1498
1499                         switch (reg->match.addr) {
1500                         case 0: /* cx231xx internal registers */
1501                                 data[0] = (u8) value;
1502                                 data[1] = (u8) (value >> 8);
1503                                 data[2] = (u8) (value >> 16);
1504                                 data[3] = (u8) (value >> 24);
1505                                 ret = cx231xx_write_ctrl_reg(dev,
1506                                                            VRT_SET_REGISTER,
1507                                                            (u16)reg->reg, data,
1508                                                            4);
1509                                 break;
1510                         case 1: /* Colibri - read byte */
1511                                 ret = cx231xx_write_i2c_data(dev,
1512                                                         Colibri_DEVICE_ADDRESS,
1513                                                         (u16)reg->reg, 2,
1514                                                         value, 1);
1515                                 break;
1516                         case 14:        /* Colibri - read dword */
1517                                 ret = cx231xx_write_i2c_data(dev,
1518                                                         Colibri_DEVICE_ADDRESS,
1519                                                         (u16)reg->reg, 2,
1520                                                         value, 4);
1521                                 break;
1522                         case 2: /* Hammerhead - read byte */
1523                                 ret =
1524                                     cx231xx_write_i2c_data(dev,
1525                                                         HAMMERHEAD_I2C_ADDRESS,
1526                                                         (u16)reg->reg, 2,
1527                                                         value, 1);
1528                                 break;
1529                         case 24:        /* Hammerhead - read dword */
1530                                 ret =
1531                                     cx231xx_write_i2c_data(dev,
1532                                                         HAMMERHEAD_I2C_ADDRESS,
1533                                                         (u16)reg->reg, 2,
1534                                                         value, 4);
1535                                 break;
1536                         case 3: /* flatiron - read byte */
1537                                 ret =
1538                                     cx231xx_write_i2c_data(dev,
1539                                                         Flatrion_DEVICE_ADDRESS,
1540                                                         (u16)reg->reg, 1,
1541                                                         value, 1);
1542                                 break;
1543                         case 34:        /* flatiron - read dword */
1544                                 ret =
1545                                     cx231xx_write_i2c_data(dev,
1546                                                         Flatrion_DEVICE_ADDRESS,
1547                                                         (u16)reg->reg, 1,
1548                                                         value, 4);
1549                                 break;
1550                         }
1551                 }
1552                 return ret < 0 ? ret : 0;
1553
1554         default:
1555                 break;
1556         }
1557
1558         mutex_lock(&dev->lock);
1559
1560         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_DBG_S_REGISTER, reg);
1561
1562         mutex_unlock(&dev->lock);
1563
1564         return ret;
1565 }
1566 #endif
1567
1568 static int vidioc_cropcap(struct file *file, void *priv,
1569                           struct v4l2_cropcap *cc)
1570 {
1571         struct cx231xx_fh *fh = priv;
1572         struct cx231xx *dev = fh->dev;
1573
1574         if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1575                 return -EINVAL;
1576
1577         cc->bounds.left = 0;
1578         cc->bounds.top = 0;
1579         cc->bounds.width = dev->width;
1580         cc->bounds.height = dev->height;
1581         cc->defrect = cc->bounds;
1582         cc->pixelaspect.numerator = 54; /* 4:3 FIXME: remove magic numbers */
1583         cc->pixelaspect.denominator = 59;
1584
1585         return 0;
1586 }
1587
1588 static int vidioc_streamon(struct file *file, void *priv,
1589                            enum v4l2_buf_type type)
1590 {
1591         struct cx231xx_fh *fh = priv;
1592         struct cx231xx *dev = fh->dev;
1593         int rc;
1594
1595         rc = check_dev(dev);
1596         if (rc < 0)
1597                 return rc;
1598
1599         mutex_lock(&dev->lock);
1600         rc = res_get(fh);
1601
1602         if (likely(rc >= 0))
1603                 rc = videobuf_streamon(&fh->vb_vidq);
1604
1605         mutex_unlock(&dev->lock);
1606
1607         return rc;
1608 }
1609
1610 static int vidioc_streamoff(struct file *file, void *priv,
1611                             enum v4l2_buf_type type)
1612 {
1613         struct cx231xx_fh *fh = priv;
1614         struct cx231xx *dev = fh->dev;
1615         int rc;
1616
1617         rc = check_dev(dev);
1618         if (rc < 0)
1619                 return rc;
1620
1621         if ((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
1622             (fh->type != V4L2_BUF_TYPE_VBI_CAPTURE))
1623                 return -EINVAL;
1624         if (type != fh->type)
1625                 return -EINVAL;
1626
1627         mutex_lock(&dev->lock);
1628
1629         videobuf_streamoff(&fh->vb_vidq);
1630         res_free(fh);
1631
1632         mutex_unlock(&dev->lock);
1633
1634         return 0;
1635 }
1636
1637 static int vidioc_querycap(struct file *file, void *priv,
1638                            struct v4l2_capability *cap)
1639 {
1640         struct cx231xx_fh *fh = priv;
1641         struct cx231xx *dev = fh->dev;
1642
1643         strlcpy(cap->driver, "cx231xx", sizeof(cap->driver));
1644         strlcpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card));
1645         strlcpy(cap->bus_info, dev_name(&dev->udev->dev),
1646                 sizeof(cap->bus_info));
1647
1648         cap->version = CX231XX_VERSION_CODE;
1649
1650         cap->capabilities = V4L2_CAP_VBI_CAPTURE |
1651 #if 0
1652             V4L2_CAP_SLICED_VBI_CAPTURE |
1653 #endif
1654             V4L2_CAP_VIDEO_CAPTURE |
1655             V4L2_CAP_AUDIO | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1656
1657         if (dev->tuner_type != TUNER_ABSENT)
1658                 cap->capabilities |= V4L2_CAP_TUNER;
1659
1660         return 0;
1661 }
1662
1663 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
1664                                    struct v4l2_fmtdesc *f)
1665 {
1666         if (unlikely(f->index >= ARRAY_SIZE(format)))
1667                 return -EINVAL;
1668
1669         strlcpy(f->description, format[f->index].name, sizeof(f->description));
1670         f->pixelformat = format[f->index].fourcc;
1671
1672         return 0;
1673 }
1674
1675 /* Sliced VBI ioctls */
1676 static int vidioc_g_fmt_sliced_vbi_cap(struct file *file, void *priv,
1677                                        struct v4l2_format *f)
1678 {
1679         struct cx231xx_fh *fh = priv;
1680         struct cx231xx *dev = fh->dev;
1681         int rc;
1682
1683         rc = check_dev(dev);
1684         if (rc < 0)
1685                 return rc;
1686
1687         mutex_lock(&dev->lock);
1688
1689         f->fmt.sliced.service_set = 0;
1690
1691         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_G_FMT, f);
1692
1693         if (f->fmt.sliced.service_set == 0)
1694                 rc = -EINVAL;
1695
1696         mutex_unlock(&dev->lock);
1697         return rc;
1698 }
1699
1700 static int vidioc_try_set_sliced_vbi_cap(struct file *file, void *priv,
1701                                          struct v4l2_format *f)
1702 {
1703         struct cx231xx_fh *fh = priv;
1704         struct cx231xx *dev = fh->dev;
1705         int rc;
1706
1707         rc = check_dev(dev);
1708         if (rc < 0)
1709                 return rc;
1710
1711         mutex_lock(&dev->lock);
1712         cx231xx_i2c_call_clients(&dev->i2c_bus[0], VIDIOC_G_FMT, f);
1713         mutex_unlock(&dev->lock);
1714
1715         if (f->fmt.sliced.service_set == 0)
1716                 return -EINVAL;
1717
1718         return 0;
1719 }
1720
1721 /* RAW VBI ioctls */
1722
1723 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1724                                 struct v4l2_format *f)
1725 {
1726         struct cx231xx_fh *fh = priv;
1727         struct cx231xx *dev = fh->dev;
1728
1729         f->fmt.vbi.sampling_rate = (dev->norm & V4L2_STD_625_50) ?
1730             35468950 : 28636363;
1731         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1732         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1733         f->fmt.vbi.offset = 64 * 4;
1734         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1735             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1736         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1737             PAL_VBI_LINES : NTSC_VBI_LINES;
1738         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1739             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1740         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1741
1742         return 0;
1743
1744 }
1745
1746 static int vidioc_try_fmt_vbi_cap(struct file *file, void *priv,
1747                                   struct v4l2_format *f)
1748 {
1749         struct cx231xx_fh *fh = priv;
1750         struct cx231xx *dev = fh->dev;
1751
1752         if (dev->vbi_stream_on && !fh->stream_on) {
1753                 cx231xx_errdev("%s device in use by another fh\n", __func__);
1754                 return -EBUSY;
1755         }
1756
1757         f->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1758         f->fmt.vbi.sampling_rate = (dev->norm & V4L2_STD_625_50) ?
1759             35468950 : 28636363;
1760         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1761         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1762         f->fmt.vbi.offset = 244;
1763         f->fmt.vbi.flags = 0;
1764         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1765             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1766         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1767             PAL_VBI_LINES : NTSC_VBI_LINES;
1768         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1769             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1770         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1771
1772         return 0;
1773
1774 }
1775
1776 static int vidioc_reqbufs(struct file *file, void *priv,
1777                           struct v4l2_requestbuffers *rb)
1778 {
1779         struct cx231xx_fh *fh = priv;
1780         struct cx231xx *dev = fh->dev;
1781         int rc;
1782
1783         rc = check_dev(dev);
1784         if (rc < 0)
1785                 return rc;
1786
1787         return videobuf_reqbufs(&fh->vb_vidq, rb);
1788 }
1789
1790 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *b)
1791 {
1792         struct cx231xx_fh *fh = priv;
1793         struct cx231xx *dev = fh->dev;
1794         int rc;
1795
1796         rc = check_dev(dev);
1797         if (rc < 0)
1798                 return rc;
1799
1800         return videobuf_querybuf(&fh->vb_vidq, b);
1801 }
1802
1803 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1804 {
1805         struct cx231xx_fh *fh = priv;
1806         struct cx231xx *dev = fh->dev;
1807         int rc;
1808
1809         rc = check_dev(dev);
1810         if (rc < 0)
1811                 return rc;
1812
1813         return videobuf_qbuf(&fh->vb_vidq, b);
1814 }
1815
1816 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1817 {
1818         struct cx231xx_fh *fh = priv;
1819         struct cx231xx *dev = fh->dev;
1820         int rc;
1821
1822         rc = check_dev(dev);
1823         if (rc < 0)
1824                 return rc;
1825
1826         return videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK);
1827 }
1828
1829 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1830 static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
1831 {
1832         struct cx231xx_fh *fh = priv;
1833
1834         return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
1835 }
1836 #endif
1837
1838 /* ----------------------------------------------------------- */
1839 /* RADIO ESPECIFIC IOCTLS                                      */
1840 /* ----------------------------------------------------------- */
1841
1842 static int radio_querycap(struct file *file, void *priv,
1843                           struct v4l2_capability *cap)
1844 {
1845         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1846
1847         strlcpy(cap->driver, "cx231xx", sizeof(cap->driver));
1848         strlcpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card));
1849         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
1850
1851         cap->version = CX231XX_VERSION_CODE;
1852         cap->capabilities = V4L2_CAP_TUNER;
1853         return 0;
1854 }
1855
1856 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1857 {
1858         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1859
1860         if (unlikely(t->index > 0))
1861                 return -EINVAL;
1862
1863         strcpy(t->name, "Radio");
1864         t->type = V4L2_TUNER_RADIO;
1865
1866         mutex_lock(&dev->lock);
1867         cx231xx_i2c_call_clients(&dev->i2c_bus[1], VIDIOC_G_TUNER, t);
1868         mutex_unlock(&dev->lock);
1869
1870         return 0;
1871 }
1872
1873 static int radio_enum_input(struct file *file, void *priv, struct v4l2_input *i)
1874 {
1875         if (i->index != 0)
1876                 return -EINVAL;
1877         strcpy(i->name, "Radio");
1878         i->type = V4L2_INPUT_TYPE_TUNER;
1879
1880         return 0;
1881 }
1882
1883 static int radio_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1884 {
1885         if (unlikely(a->index))
1886                 return -EINVAL;
1887
1888         strcpy(a->name, "Radio");
1889         return 0;
1890 }
1891
1892 static int radio_s_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1893 {
1894         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1895
1896         if (0 != t->index)
1897                 return -EINVAL;
1898
1899         mutex_lock(&dev->lock);
1900         cx231xx_i2c_call_clients(&dev->i2c_bus[1], VIDIOC_S_TUNER, t);
1901         mutex_unlock(&dev->lock);
1902
1903         return 0;
1904 }
1905
1906 static int radio_s_audio(struct file *file, void *fh, struct v4l2_audio *a)
1907 {
1908         return 0;
1909 }
1910
1911 static int radio_s_input(struct file *file, void *fh, unsigned int i)
1912 {
1913         return 0;
1914 }
1915
1916 static int radio_queryctrl(struct file *file, void *priv,
1917                            struct v4l2_queryctrl *c)
1918 {
1919         int i;
1920
1921         if (c->id < V4L2_CID_BASE || c->id >= V4L2_CID_LASTP1)
1922                 return -EINVAL;
1923         if (c->id == V4L2_CID_AUDIO_MUTE) {
1924                 for (i = 0; i < CX231XX_CTLS; i++)
1925                         if (cx231xx_ctls[i].v.id == c->id)
1926                                 break;
1927                 *c = cx231xx_ctls[i].v;
1928         } else
1929                 *c = no_ctl;
1930         return 0;
1931 }
1932
1933 /*
1934  * cx231xx_v4l2_open()
1935  * inits the device and starts isoc transfer
1936  */
1937 static int cx231xx_v4l2_open(struct file *filp)
1938 {
1939         int minor = video_devdata(filp)->minor;
1940         int errCode = 0, radio = 0;
1941         struct cx231xx *dev = NULL;
1942         struct cx231xx_fh *fh;
1943         enum v4l2_buf_type fh_type = 0;
1944
1945         dev = cx231xx_get_device(minor, &fh_type, &radio);
1946         if (NULL == dev)
1947                 return -ENODEV;
1948
1949         mutex_lock(&dev->lock);
1950
1951         cx231xx_videodbg("open minor=%d type=%s users=%d\n",
1952                          minor, v4l2_type_names[fh_type], dev->users);
1953
1954 #if 0
1955         errCode = cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1956         if (errCode < 0) {
1957                 cx231xx_errdev
1958                     ("Device locked on digital mode. Can't open analog\n");
1959                 mutex_unlock(&dev->lock);
1960                 return -EBUSY;
1961         }
1962 #endif
1963
1964         fh = kzalloc(sizeof(struct cx231xx_fh), GFP_KERNEL);
1965         if (!fh) {
1966                 cx231xx_errdev("cx231xx-video.c: Out of memory?!\n");
1967                 mutex_unlock(&dev->lock);
1968                 return -ENOMEM;
1969         }
1970         fh->dev = dev;
1971         fh->radio = radio;
1972         fh->type = fh_type;
1973         filp->private_data = fh;
1974
1975         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1976                 dev->width = norm_maxw(dev);
1977                 dev->height = norm_maxh(dev);
1978                 dev->hscale = 0;
1979                 dev->vscale = 0;
1980
1981                 /* Power up in Analog TV mode */
1982                 cx231xx_set_power_mode(dev, POLARIS_AVMODE_ANALOGT_TV);
1983
1984 #if 0
1985                 cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1986 #endif
1987                 cx231xx_resolution_set(dev);
1988
1989                 /* set video alternate setting */
1990                 cx231xx_set_video_alternate(dev);
1991
1992                 /* Needed, since GPIO might have disabled power of
1993                    some i2c device */
1994                 cx231xx_config_i2c(dev);
1995
1996                 /* device needs to be initialized before isoc transfer */
1997                 dev->video_input = dev->video_input > 2 ? 2 : dev->video_input;
1998                 video_mux(dev, dev->video_input);
1999
2000         }
2001         if (fh->radio) {
2002                 cx231xx_videodbg("video_open: setting radio device\n");
2003
2004                 /* cx231xx_start_radio(dev); */
2005
2006                 cx231xx_i2c_call_clients(&dev->i2c_bus[1], AUDC_SET_RADIO,
2007                                          NULL);
2008         }
2009
2010         dev->users++;
2011
2012         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
2013                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_video_qops,
2014                                             NULL, &dev->video_mode.slock,
2015                                             fh->type, V4L2_FIELD_INTERLACED,
2016                                             sizeof(struct cx231xx_buffer), fh);
2017         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
2018                 /* Set the required alternate setting  VBI interface works in
2019                    Bulk mode only */
2020                 cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
2021
2022                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_vbi_qops,
2023                                             NULL, &dev->vbi_mode.slock,
2024                                             fh->type, V4L2_FIELD_SEQ_TB,
2025                                             sizeof(struct cx231xx_buffer), fh);
2026         }
2027
2028         mutex_unlock(&dev->lock);
2029
2030         return errCode;
2031 }
2032
2033 /*
2034  * cx231xx_realease_resources()
2035  * unregisters the v4l2,i2c and usb devices
2036  * called when the device gets disconected or at module unload
2037 */
2038 void cx231xx_release_analog_resources(struct cx231xx *dev)
2039 {
2040
2041         /*FIXME: I2C IR should be disconnected */
2042
2043         if (dev->radio_dev) {
2044                 if (-1 != dev->radio_dev->minor)
2045                         video_unregister_device(dev->radio_dev);
2046                 else
2047                         video_device_release(dev->radio_dev);
2048                 dev->radio_dev = NULL;
2049         }
2050         if (dev->vbi_dev) {
2051                 cx231xx_info("V4L2 device /dev/vbi%d deregistered\n",
2052                              dev->vbi_dev->num);
2053                 if (-1 != dev->vbi_dev->minor)
2054                         video_unregister_device(dev->vbi_dev);
2055                 else
2056                         video_device_release(dev->vbi_dev);
2057                 dev->vbi_dev = NULL;
2058         }
2059         if (dev->vdev) {
2060                 cx231xx_info("V4L2 device /dev/video%d deregistered\n",
2061                              dev->vdev->num);
2062                 if (-1 != dev->vdev->minor)
2063                         video_unregister_device(dev->vdev);
2064                 else
2065                         video_device_release(dev->vdev);
2066                 dev->vdev = NULL;
2067         }
2068 }
2069
2070 /*
2071  * cx231xx_v4l2_close()
2072  * stops streaming and deallocates all resources allocated by the v4l2
2073  * calls and ioctls
2074  */
2075 static int cx231xx_v4l2_close(struct file *filp)
2076 {
2077         struct cx231xx_fh *fh = filp->private_data;
2078         struct cx231xx *dev = fh->dev;
2079
2080         cx231xx_videodbg("users=%d\n", dev->users);
2081
2082         mutex_lock(&dev->lock);
2083
2084         if (res_check(fh))
2085                 res_free(fh);
2086
2087         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
2088                 videobuf_stop(&fh->vb_vidq);
2089                 videobuf_mmap_free(&fh->vb_vidq);
2090
2091                 /* the device is already disconnect,
2092                    free the remaining resources */
2093                 if (dev->state & DEV_DISCONNECTED) {
2094                         cx231xx_release_resources(dev);
2095                         mutex_unlock(&dev->lock);
2096                         kfree(dev);
2097                         return 0;
2098                 }
2099
2100                 /* do this before setting alternate! */
2101                 cx231xx_uninit_vbi_isoc(dev);
2102
2103                 /* set alternate 0 */
2104                 if (!dev->vbi_or_sliced_cc_mode)
2105                         cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
2106                 else
2107                         cx231xx_set_alt_setting(dev, INDEX_HANC, 0);
2108
2109                 kfree(fh);
2110                 dev->users--;
2111                 wake_up_interruptible_nr(&dev->open, 1);
2112                 mutex_unlock(&dev->lock);
2113                 return 0;
2114         }
2115
2116         if (dev->users == 1) {
2117                 videobuf_stop(&fh->vb_vidq);
2118                 videobuf_mmap_free(&fh->vb_vidq);
2119
2120                 /* the device is already disconnect,
2121                    free the remaining resources */
2122                 if (dev->state & DEV_DISCONNECTED) {
2123                         cx231xx_release_resources(dev);
2124                         mutex_unlock(&dev->lock);
2125                         kfree(dev);
2126                         return 0;
2127                 }
2128
2129                 /* Save some power by putting tuner to sleep */
2130                 cx231xx_i2c_call_clients(&dev->i2c_bus[1], TUNER_SET_STANDBY,
2131                                          NULL);
2132
2133                 /* do this before setting alternate! */
2134                 cx231xx_uninit_isoc(dev);
2135                 cx231xx_set_mode(dev, CX231XX_SUSPEND);
2136
2137                 /* set alternate 0 */
2138                 cx231xx_set_alt_setting(dev, INDEX_VIDEO, 0);
2139         }
2140         kfree(fh);
2141         dev->users--;
2142         wake_up_interruptible_nr(&dev->open, 1);
2143         mutex_unlock(&dev->lock);
2144         return 0;
2145 }
2146
2147 /*
2148  * cx231xx_v4l2_read()
2149  * will allocate buffers when called for the first time
2150  */
2151 static ssize_t
2152 cx231xx_v4l2_read(struct file *filp, char __user *buf, size_t count,
2153                   loff_t *pos)
2154 {
2155         struct cx231xx_fh *fh = filp->private_data;
2156         struct cx231xx *dev = fh->dev;
2157         int rc;
2158
2159         rc = check_dev(dev);
2160         if (rc < 0)
2161                 return rc;
2162
2163         if ((fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
2164             (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)) {
2165                 mutex_lock(&dev->lock);
2166                 rc = res_get(fh);
2167                 mutex_unlock(&dev->lock);
2168
2169                 if (unlikely(rc < 0))
2170                         return rc;
2171
2172                 return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
2173                                             filp->f_flags & O_NONBLOCK);
2174         }
2175         return 0;
2176 }
2177
2178 /*
2179  * cx231xx_v4l2_poll()
2180  * will allocate buffers when called for the first time
2181  */
2182 static unsigned int cx231xx_v4l2_poll(struct file *filp, poll_table * wait)
2183 {
2184         struct cx231xx_fh *fh = filp->private_data;
2185         struct cx231xx *dev = fh->dev;
2186         int rc;
2187
2188         rc = check_dev(dev);
2189         if (rc < 0)
2190                 return rc;
2191
2192         mutex_lock(&dev->lock);
2193         rc = res_get(fh);
2194         mutex_unlock(&dev->lock);
2195
2196         if (unlikely(rc < 0))
2197                 return POLLERR;
2198
2199         if ((V4L2_BUF_TYPE_VIDEO_CAPTURE == fh->type) ||
2200             (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type))
2201                 return videobuf_poll_stream(filp, &fh->vb_vidq, wait);
2202         else
2203                 return POLLERR;
2204 }
2205
2206 /*
2207  * cx231xx_v4l2_mmap()
2208  */
2209 static int cx231xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
2210 {
2211         struct cx231xx_fh *fh = filp->private_data;
2212         struct cx231xx *dev = fh->dev;
2213         int rc;
2214
2215         rc = check_dev(dev);
2216         if (rc < 0)
2217                 return rc;
2218
2219         mutex_lock(&dev->lock);
2220         rc = res_get(fh);
2221         mutex_unlock(&dev->lock);
2222
2223         if (unlikely(rc < 0))
2224                 return rc;
2225
2226         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
2227
2228         cx231xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
2229                          (unsigned long)vma->vm_start,
2230                          (unsigned long)vma->vm_end -
2231                          (unsigned long)vma->vm_start, rc);
2232
2233         return rc;
2234 }
2235
2236 static const struct v4l2_file_operations cx231xx_v4l_fops = {
2237         .owner   = THIS_MODULE,
2238         .open    = cx231xx_v4l2_open,
2239         .release = cx231xx_v4l2_close,
2240         .read    = cx231xx_v4l2_read,
2241         .poll    = cx231xx_v4l2_poll,
2242         .mmap    = cx231xx_v4l2_mmap,
2243         .ioctl   = video_ioctl2,
2244 };
2245
2246 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2247         .vidioc_querycap               = vidioc_querycap,
2248         .vidioc_enum_fmt_vid_cap       = vidioc_enum_fmt_vid_cap,
2249         .vidioc_g_fmt_vid_cap          = vidioc_g_fmt_vid_cap,
2250         .vidioc_try_fmt_vid_cap        = vidioc_try_fmt_vid_cap,
2251         .vidioc_s_fmt_vid_cap          = vidioc_s_fmt_vid_cap,
2252         .vidioc_g_fmt_vbi_cap          = vidioc_g_fmt_vbi_cap,
2253         .vidioc_try_fmt_vbi_cap        = vidioc_try_fmt_vbi_cap,
2254         .vidioc_s_fmt_vbi_cap          = vidioc_try_fmt_vbi_cap,
2255         .vidioc_g_audio                =  vidioc_g_audio,
2256         .vidioc_s_audio                = vidioc_s_audio,
2257         .vidioc_cropcap                = vidioc_cropcap,
2258         .vidioc_g_fmt_sliced_vbi_cap   = vidioc_g_fmt_sliced_vbi_cap,
2259         .vidioc_try_fmt_sliced_vbi_cap = vidioc_try_set_sliced_vbi_cap,
2260         .vidioc_reqbufs                = vidioc_reqbufs,
2261         .vidioc_querybuf               = vidioc_querybuf,
2262         .vidioc_qbuf                   = vidioc_qbuf,
2263         .vidioc_dqbuf                  = vidioc_dqbuf,
2264         .vidioc_s_std                  = vidioc_s_std,
2265         .vidioc_g_std                  = vidioc_g_std,
2266         .vidioc_enum_input             = vidioc_enum_input,
2267         .vidioc_g_input                = vidioc_g_input,
2268         .vidioc_s_input                = vidioc_s_input,
2269         .vidioc_queryctrl              = vidioc_queryctrl,
2270         .vidioc_g_ctrl                 = vidioc_g_ctrl,
2271         .vidioc_s_ctrl                 = vidioc_s_ctrl,
2272         .vidioc_streamon               = vidioc_streamon,
2273         .vidioc_streamoff              = vidioc_streamoff,
2274         .vidioc_g_tuner                = vidioc_g_tuner,
2275         .vidioc_s_tuner                = vidioc_s_tuner,
2276         .vidioc_g_frequency            = vidioc_g_frequency,
2277         .vidioc_s_frequency            = vidioc_s_frequency,
2278 #ifdef CONFIG_VIDEO_ADV_DEBUG
2279         .vidioc_g_register             = vidioc_g_register,
2280         .vidioc_s_register             = vidioc_s_register,
2281 #endif
2282 #ifdef CONFIG_VIDEO_V4L1_COMPAT
2283         .vidiocgmbuf                   = vidiocgmbuf,
2284 #endif
2285 };
2286
2287 static struct video_device cx231xx_vbi_template;
2288
2289 static const struct video_device cx231xx_video_template = {
2290         .fops         = &cx231xx_v4l_fops,
2291         .release      = video_device_release,
2292         .ioctl_ops    = &video_ioctl_ops,
2293         .minor        = -1,
2294         .tvnorms      = V4L2_STD_ALL,
2295         .current_norm = V4L2_STD_PAL,
2296 };
2297
2298 static const struct v4l2_file_operations radio_fops = {
2299         .owner   = THIS_MODULE,
2300         .open   = cx231xx_v4l2_open,
2301         .release = cx231xx_v4l2_close,
2302         .ioctl   = video_ioctl2,
2303 };
2304
2305 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2306         .vidioc_querycap    = radio_querycap,
2307         .vidioc_g_tuner     = radio_g_tuner,
2308         .vidioc_enum_input  = radio_enum_input,
2309         .vidioc_g_audio     = radio_g_audio,
2310         .vidioc_s_tuner     = radio_s_tuner,
2311         .vidioc_s_audio     = radio_s_audio,
2312         .vidioc_s_input     = radio_s_input,
2313         .vidioc_queryctrl   = radio_queryctrl,
2314         .vidioc_g_ctrl      = vidioc_g_ctrl,
2315         .vidioc_s_ctrl      = vidioc_s_ctrl,
2316         .vidioc_g_frequency = vidioc_g_frequency,
2317         .vidioc_s_frequency = vidioc_s_frequency,
2318 #ifdef CONFIG_VIDEO_ADV_DEBUG
2319         .vidioc_g_register  = vidioc_g_register,
2320         .vidioc_s_register  = vidioc_s_register,
2321 #endif
2322 };
2323
2324 static struct video_device cx231xx_radio_template = {
2325         .name      = "cx231xx-radio",
2326         .fops      = &radio_fops,
2327         .ioctl_ops = &radio_ioctl_ops,
2328         .minor     = -1,
2329 };
2330
2331 /******************************** usb interface ******************************/
2332
2333 static struct video_device *cx231xx_vdev_init(struct cx231xx *dev, const struct video_device
2334                                               *template, const char *type_name)
2335 {
2336         struct video_device *vfd;
2337
2338         vfd = video_device_alloc();
2339         if (NULL == vfd)
2340                 return NULL;
2341
2342         *vfd = *template;
2343         vfd->minor = -1;
2344         vfd->parent = &dev->udev->dev;
2345         vfd->release = video_device_release;
2346         vfd->debug = video_debug;
2347
2348         snprintf(vfd->name, sizeof(vfd->name), "%s %s", dev->name, type_name);
2349
2350         return vfd;
2351 }
2352
2353 int cx231xx_register_analog_devices(struct cx231xx *dev)
2354 {
2355         int ret;
2356
2357         cx231xx_info("%s()\n", __func__);
2358
2359         cx231xx_info("%s: v4l2 driver version %d.%d.%d\n",
2360                      dev->name,
2361                      (CX231XX_VERSION_CODE >> 16) & 0xff,
2362                      (CX231XX_VERSION_CODE >> 8) & 0xff,
2363                      CX231XX_VERSION_CODE & 0xff);
2364
2365         /* set default norm */
2366         /*dev->norm = cx231xx_video_template.current_norm; */
2367         dev->width = norm_maxw(dev);
2368         dev->height = norm_maxh(dev);
2369         dev->interlaced = 0;
2370         dev->hscale = 0;
2371         dev->vscale = 0;
2372
2373         /* Analog specific initialization */
2374         dev->format = &format[0];
2375         /* video_mux(dev, dev->video_input); */
2376
2377         /* Audio defaults */
2378         dev->mute = 1;
2379         dev->volume = 0x1f;
2380
2381         /* enable vbi capturing */
2382         /* write code here...  */
2383
2384         /* allocate and fill video video_device struct */
2385         dev->vdev = cx231xx_vdev_init(dev, &cx231xx_video_template, "video");
2386         if (!dev->vdev) {
2387                 cx231xx_errdev("cannot allocate video_device.\n");
2388                 return -ENODEV;
2389         }
2390
2391         /* register v4l2 video video_device */
2392         ret = video_register_device(dev->vdev, VFL_TYPE_GRABBER,
2393                                     video_nr[dev->devno]);
2394         if (ret) {
2395                 cx231xx_errdev("unable to register video device (error=%i).\n",
2396                                ret);
2397                 return ret;
2398         }
2399
2400         cx231xx_info("%s/0: registered device video%d [v4l2]\n",
2401                      dev->name, dev->vdev->num);
2402
2403         /* Initialize VBI template */
2404         memcpy(&cx231xx_vbi_template, &cx231xx_video_template,
2405                sizeof(cx231xx_vbi_template));
2406         strcpy(cx231xx_vbi_template.name, "cx231xx-vbi");
2407
2408         /* Allocate and fill vbi video_device struct */
2409         dev->vbi_dev = cx231xx_vdev_init(dev, &cx231xx_vbi_template, "vbi");
2410
2411         /* register v4l2 vbi video_device */
2412         ret = video_register_device(dev->vbi_dev, VFL_TYPE_VBI,
2413                                     vbi_nr[dev->devno]);
2414         if (ret < 0) {
2415                 cx231xx_errdev("unable to register vbi device\n");
2416                 return ret;
2417         }
2418
2419         cx231xx_info("%s/0: registered device vbi%d\n",
2420                      dev->name, dev->vbi_dev->num);
2421
2422         if (cx231xx_boards[dev->model].radio.type == CX231XX_RADIO) {
2423                 dev->radio_dev = cx231xx_vdev_init(dev, &cx231xx_radio_template,
2424                                                    "radio");
2425                 if (!dev->radio_dev) {
2426                         cx231xx_errdev("cannot allocate video_device.\n");
2427                         return -ENODEV;
2428                 }
2429                 ret = video_register_device(dev->radio_dev, VFL_TYPE_RADIO,
2430                                             radio_nr[dev->devno]);
2431                 if (ret < 0) {
2432                         cx231xx_errdev("can't register radio device\n");
2433                         return ret;
2434                 }
2435                 cx231xx_info("Registered radio device as /dev/radio%d\n",
2436                              dev->radio_dev->num);
2437         }
2438
2439         cx231xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n",
2440                      dev->vdev->num, dev->vbi_dev->num);
2441
2442         return 0;
2443 }