Merge branch 'devicetree/merge' into spi/merge
[pandora-kernel.git] / drivers / media / video / tlg2300 / pd-video.c
1 #include <linux/fs.h>
2 #include <linux/vmalloc.h>
3 #include <linux/videodev2.h>
4 #include <linux/usb.h>
5 #include <linux/mm.h>
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8
9 #include <media/v4l2-ioctl.h>
10 #include <media/v4l2-dev.h>
11
12 #include "pd-common.h"
13 #include "vendorcmds.h"
14
15 #ifdef CONFIG_PM
16 static int pm_video_suspend(struct poseidon *pd);
17 static int pm_video_resume(struct poseidon *pd);
18 #endif
19 static void iso_bubble_handler(struct work_struct *w);
20
21 static int usb_transfer_mode;
22 module_param(usb_transfer_mode, int, 0644);
23 MODULE_PARM_DESC(usb_transfer_mode, "0 = Bulk, 1 = Isochronous");
24
25 static const struct poseidon_format poseidon_formats[] = {
26         { "YUV 422", V4L2_PIX_FMT_YUYV, 16, 0},
27         { "RGB565", V4L2_PIX_FMT_RGB565, 16, 0},
28 };
29
30 static const struct poseidon_tvnorm poseidon_tvnorms[] = {
31         { V4L2_STD_PAL_D, "PAL-D",  TLG_TUNE_VSTD_PAL_D },
32         { V4L2_STD_PAL_B, "PAL-B",  TLG_TUNE_VSTD_PAL_B },
33         { V4L2_STD_PAL_G, "PAL-G",  TLG_TUNE_VSTD_PAL_G },
34         { V4L2_STD_PAL_H, "PAL-H",  TLG_TUNE_VSTD_PAL_H },
35         { V4L2_STD_PAL_I, "PAL-I",  TLG_TUNE_VSTD_PAL_I },
36         { V4L2_STD_PAL_M, "PAL-M",  TLG_TUNE_VSTD_PAL_M },
37         { V4L2_STD_PAL_N, "PAL-N",  TLG_TUNE_VSTD_PAL_N_COMBO },
38         { V4L2_STD_PAL_Nc, "PAL-Nc", TLG_TUNE_VSTD_PAL_N_COMBO },
39         { V4L2_STD_NTSC_M, "NTSC-M", TLG_TUNE_VSTD_NTSC_M },
40         { V4L2_STD_NTSC_M_JP, "NTSC-JP", TLG_TUNE_VSTD_NTSC_M_J },
41         { V4L2_STD_SECAM_B, "SECAM-B", TLG_TUNE_VSTD_SECAM_B },
42         { V4L2_STD_SECAM_D, "SECAM-D", TLG_TUNE_VSTD_SECAM_D },
43         { V4L2_STD_SECAM_G, "SECAM-G", TLG_TUNE_VSTD_SECAM_G },
44         { V4L2_STD_SECAM_H, "SECAM-H", TLG_TUNE_VSTD_SECAM_H },
45         { V4L2_STD_SECAM_K, "SECAM-K", TLG_TUNE_VSTD_SECAM_K },
46         { V4L2_STD_SECAM_K1, "SECAM-K1", TLG_TUNE_VSTD_SECAM_K1 },
47         { V4L2_STD_SECAM_L, "SECAM-L", TLG_TUNE_VSTD_SECAM_L },
48         { V4L2_STD_SECAM_LC, "SECAM-LC", TLG_TUNE_VSTD_SECAM_L1 },
49 };
50 static const unsigned int POSEIDON_TVNORMS = ARRAY_SIZE(poseidon_tvnorms);
51
52 struct pd_audio_mode {
53         u32 tlg_audio_mode;
54         u32 v4l2_audio_sub;
55         u32 v4l2_audio_mode;
56 };
57
58 static const struct pd_audio_mode pd_audio_modes[] = {
59         { TLG_TUNE_TVAUDIO_MODE_MONO, V4L2_TUNER_SUB_MONO,
60                 V4L2_TUNER_MODE_MONO },
61         { TLG_TUNE_TVAUDIO_MODE_STEREO, V4L2_TUNER_SUB_STEREO,
62                 V4L2_TUNER_MODE_STEREO },
63         { TLG_TUNE_TVAUDIO_MODE_LANG_A, V4L2_TUNER_SUB_LANG1,
64                 V4L2_TUNER_MODE_LANG1 },
65         { TLG_TUNE_TVAUDIO_MODE_LANG_B, V4L2_TUNER_SUB_LANG2,
66                 V4L2_TUNER_MODE_LANG2 },
67         { TLG_TUNE_TVAUDIO_MODE_LANG_C, V4L2_TUNER_SUB_LANG1,
68                 V4L2_TUNER_MODE_LANG1_LANG2 }
69 };
70 static const unsigned int POSEIDON_AUDIOMODS = ARRAY_SIZE(pd_audio_modes);
71
72 struct pd_input {
73         char *name;
74         uint32_t tlg_src;
75 };
76
77 static const struct pd_input pd_inputs[] = {
78         { "TV Antenna", TLG_SIG_SRC_ANTENNA },
79         { "TV Cable", TLG_SIG_SRC_CABLE },
80         { "TV SVideo", TLG_SIG_SRC_SVIDEO },
81         { "TV Composite", TLG_SIG_SRC_COMPOSITE }
82 };
83 static const unsigned int POSEIDON_INPUTS = ARRAY_SIZE(pd_inputs);
84
85 struct poseidon_control {
86         struct v4l2_queryctrl v4l2_ctrl;
87         enum cmd_custom_param_id vc_id;
88 };
89
90 static struct poseidon_control controls[] = {
91         {
92                 { V4L2_CID_BRIGHTNESS, V4L2_CTRL_TYPE_INTEGER,
93                         "brightness", 0, 10000, 1, 100, 0, },
94                 CUST_PARM_ID_BRIGHTNESS_CTRL
95         }, {
96                 { V4L2_CID_CONTRAST, V4L2_CTRL_TYPE_INTEGER,
97                         "contrast", 0, 10000, 1, 100, 0, },
98                 CUST_PARM_ID_CONTRAST_CTRL,
99         }, {
100                 { V4L2_CID_HUE, V4L2_CTRL_TYPE_INTEGER,
101                         "hue", 0, 10000, 1, 100, 0, },
102                 CUST_PARM_ID_HUE_CTRL,
103         }, {
104                 { V4L2_CID_SATURATION, V4L2_CTRL_TYPE_INTEGER,
105                         "saturation", 0, 10000, 1, 100, 0, },
106                 CUST_PARM_ID_SATURATION_CTRL,
107         },
108 };
109
110 struct video_std_to_audio_std {
111         v4l2_std_id     video_std;
112         int             audio_std;
113 };
114
115 static const struct video_std_to_audio_std video_to_audio_map[] = {
116         /* country : { 27, 32, 33, 34, 36, 44, 45, 46, 47, 48, 64,
117                         65, 86, 351, 352, 353, 354, 358, 372, 852, 972 } */
118         { (V4L2_STD_PAL_I | V4L2_STD_PAL_B | V4L2_STD_PAL_D |
119                 V4L2_STD_SECAM_L | V4L2_STD_SECAM_D), TLG_TUNE_ASTD_NICAM },
120
121         /* country : { 1, 52, 54, 55, 886 } */
122         {V4L2_STD_NTSC_M | V4L2_STD_PAL_N | V4L2_STD_PAL_M, TLG_TUNE_ASTD_BTSC},
123
124         /* country : { 81 } */
125         { V4L2_STD_NTSC_M_JP, TLG_TUNE_ASTD_EIAJ },
126
127         /* other country : TLG_TUNE_ASTD_A2 */
128 };
129 static const unsigned int map_size = ARRAY_SIZE(video_to_audio_map);
130
131 static int get_audio_std(v4l2_std_id v4l2_std)
132 {
133         int i = 0;
134
135         for (; i < map_size; i++) {
136                 if (v4l2_std & video_to_audio_map[i].video_std)
137                         return video_to_audio_map[i].audio_std;
138         }
139         return TLG_TUNE_ASTD_A2;
140 }
141
142 static int vidioc_querycap(struct file *file, void *fh,
143                         struct v4l2_capability *cap)
144 {
145         struct front_face *front = fh;
146         struct poseidon *p = front->pd;
147
148         logs(front);
149
150         strcpy(cap->driver, "tele-video");
151         strcpy(cap->card, "Telegent Poseidon");
152         usb_make_path(p->udev, cap->bus_info, sizeof(cap->bus_info));
153         cap->version = KERNEL_VERSION(0, 0, 1);
154         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TUNER |
155                                 V4L2_CAP_AUDIO | V4L2_CAP_STREAMING |
156                                 V4L2_CAP_READWRITE | V4L2_CAP_VBI_CAPTURE;
157         return 0;
158 }
159
160 /*====================================================================*/
161 static void init_copy(struct video_data *video, bool index)
162 {
163         struct front_face *front = video->front;
164
165         video->field_count      = index;
166         video->lines_copied     = 0;
167         video->prev_left        = 0 ;
168         video->dst              = (char *)videobuf_to_vmalloc(front->curr_frame)
169                                         + index * video->lines_size;
170         video->vbi->copied      = 0; /* set it here */
171 }
172
173 static bool get_frame(struct front_face *front, int *need_init)
174 {
175         struct videobuf_buffer *vb = front->curr_frame;
176
177         if (vb)
178                 return true;
179
180         spin_lock(&front->queue_lock);
181         if (!list_empty(&front->active)) {
182                 vb = list_entry(front->active.next,
183                                struct videobuf_buffer, queue);
184                 if (need_init)
185                         *need_init = 1;
186                 front->curr_frame = vb;
187                 list_del_init(&vb->queue);
188         }
189         spin_unlock(&front->queue_lock);
190
191         return !!vb;
192 }
193
194 /* check if the video's buffer is ready */
195 static bool get_video_frame(struct front_face *front, struct video_data *video)
196 {
197         int need_init = 0;
198         bool ret = true;
199
200         ret = get_frame(front, &need_init);
201         if (ret && need_init)
202                 init_copy(video, 0);
203         return ret;
204 }
205
206 static void submit_frame(struct front_face *front)
207 {
208         struct videobuf_buffer *vb = front->curr_frame;
209
210         if (vb == NULL)
211                 return;
212
213         front->curr_frame       = NULL;
214         vb->state               = VIDEOBUF_DONE;
215         vb->field_count++;
216         do_gettimeofday(&vb->ts);
217
218         wake_up(&vb->done);
219 }
220
221 /*
222  * A frame is composed of two fields. If we receive all the two fields,
223  * call the  submit_frame() to submit the whole frame to applications.
224  */
225 static void end_field(struct video_data *video)
226 {
227         /* logs(video->front); */
228         if (1 == video->field_count)
229                 submit_frame(video->front);
230         else
231                 init_copy(video, 1);
232 }
233
234 static void copy_video_data(struct video_data *video, char *src,
235                                 unsigned int count)
236 {
237 #define copy_data(len)  \
238         do { \
239                 if (++video->lines_copied > video->lines_per_field) \
240                         goto overflow; \
241                 memcpy(video->dst, src, len);\
242                 video->dst += len + video->lines_size; \
243                 src += len; \
244                 count -= len; \
245          } while (0)
246
247         while (count && count >= video->lines_size) {
248                 if (video->prev_left) {
249                         copy_data(video->prev_left);
250                         video->prev_left = 0;
251                         continue;
252                 }
253                 copy_data(video->lines_size);
254         }
255         if (count && count < video->lines_size) {
256                 memcpy(video->dst, src, count);
257
258                 video->prev_left = video->lines_size - count;
259                 video->dst += count;
260         }
261         return;
262
263 overflow:
264         end_field(video);
265 }
266
267 static void check_trailer(struct video_data *video, char *src, int count)
268 {
269         struct vbi_data *vbi = video->vbi;
270         int offset; /* trailer's offset */
271         char *buf;
272
273         offset = (video->context.pix.sizeimage / 2 + vbi->vbi_size / 2)
274                 - (vbi->copied + video->lines_size * video->lines_copied);
275         if (video->prev_left)
276                 offset -= (video->lines_size - video->prev_left);
277
278         if (offset > count || offset <= 0)
279                 goto short_package;
280
281         buf = src + offset;
282
283         /* trailer : (VFHS) + U32 + U32 + field_num */
284         if (!strncmp(buf, "VFHS", 4)) {
285                 int field_num = *((u32 *)(buf + 12));
286
287                 if ((field_num & 1) ^ video->field_count) {
288                         init_copy(video, video->field_count);
289                         return;
290                 }
291                 copy_video_data(video, src, offset);
292         }
293 short_package:
294         end_field(video);
295 }
296
297 /* ==========  Check this more carefully! =========== */
298 static inline void copy_vbi_data(struct vbi_data *vbi,
299                                 char *src, unsigned int count)
300 {
301         struct front_face *front = vbi->front;
302
303         if (front && get_frame(front, NULL)) {
304                 char *buf = videobuf_to_vmalloc(front->curr_frame);
305
306                 if (vbi->video->field_count)
307                         buf += (vbi->vbi_size / 2);
308                 memcpy(buf + vbi->copied, src, count);
309         }
310         vbi->copied += count;
311 }
312
313 /*
314  * Copy the normal data (VBI or VIDEO) without the trailer.
315  * VBI is not interlaced, while VIDEO is interlaced.
316  */
317 static inline void copy_vbi_video_data(struct video_data *video,
318                                 char *src, unsigned int count)
319 {
320         struct vbi_data *vbi = video->vbi;
321         unsigned int vbi_delta = (vbi->vbi_size / 2) - vbi->copied;
322
323         if (vbi_delta >= count) {
324                 copy_vbi_data(vbi, src, count);
325         } else {
326                 if (vbi_delta) {
327                         copy_vbi_data(vbi, src, vbi_delta);
328
329                         /* we receive the two fields of the VBI*/
330                         if (vbi->front && video->field_count)
331                                 submit_frame(vbi->front);
332                 }
333                 copy_video_data(video, src + vbi_delta, count - vbi_delta);
334         }
335 }
336
337 static void urb_complete_bulk(struct urb *urb)
338 {
339         struct front_face *front = urb->context;
340         struct video_data *video = &front->pd->video_data;
341         char *src = (char *)urb->transfer_buffer;
342         int count = urb->actual_length;
343         int ret = 0;
344
345         if (!video->is_streaming || urb->status) {
346                 if (urb->status == -EPROTO)
347                         goto resend_it;
348                 return;
349         }
350         if (!get_video_frame(front, video))
351                 goto resend_it;
352
353         if (count == urb->transfer_buffer_length)
354                 copy_vbi_video_data(video, src, count);
355         else
356                 check_trailer(video, src, count);
357
358 resend_it:
359         ret = usb_submit_urb(urb, GFP_ATOMIC);
360         if (ret)
361                 log(" submit failed: error %d", ret);
362 }
363
364 /************************* for ISO *********************/
365 #define GET_SUCCESS             (0)
366 #define GET_TRAILER             (1)
367 #define GET_TOO_MUCH_BUBBLE     (2)
368 #define GET_NONE                (3)
369 static int get_chunk(int start, struct urb *urb,
370                         int *head, int *tail, int *bubble_err)
371 {
372         struct usb_iso_packet_descriptor *pkt = NULL;
373         int ret = GET_SUCCESS;
374
375         for (*head = *tail = -1; start < urb->number_of_packets; start++) {
376                 pkt = &urb->iso_frame_desc[start];
377
378                 /* handle the bubble of the Hub */
379                 if (-EOVERFLOW == pkt->status) {
380                         if (++*bubble_err > urb->number_of_packets / 3)
381                                 return GET_TOO_MUCH_BUBBLE;
382                         continue;
383                 }
384
385                 /* This is the gap */
386                 if (pkt->status || pkt->actual_length <= 0
387                                 || pkt->actual_length > ISO_PKT_SIZE) {
388                         if (*head != -1)
389                                 break;
390                         continue;
391                 }
392
393                 /* a good isochronous packet */
394                 if (pkt->actual_length == ISO_PKT_SIZE) {
395                         if (*head == -1)
396                                 *head = start;
397                         *tail = start;
398                         continue;
399                 }
400
401                 /* trailer is here */
402                 if (pkt->actual_length < ISO_PKT_SIZE) {
403                         if (*head == -1) {
404                                 *head = start;
405                                 *tail = start;
406                                 return GET_TRAILER;
407                         }
408                         break;
409                 }
410         }
411
412         if (*head == -1 && *tail == -1)
413                 ret = GET_NONE;
414         return ret;
415 }
416
417 /*
418  * |__|------|___|-----|_______|
419  *       ^          ^
420  *       |          |
421  *      gap        gap
422  */
423 static void urb_complete_iso(struct urb *urb)
424 {
425         struct front_face *front = urb->context;
426         struct video_data *video = &front->pd->video_data;
427         int bubble_err = 0, head = 0, tail = 0;
428         char *src = (char *)urb->transfer_buffer;
429         int ret = 0;
430
431         if (!video->is_streaming)
432                 return;
433
434         do {
435                 if (!get_video_frame(front, video))
436                         goto out;
437
438                 switch (get_chunk(head, urb, &head, &tail, &bubble_err)) {
439                 case GET_SUCCESS:
440                         copy_vbi_video_data(video, src + (head * ISO_PKT_SIZE),
441                                         (tail - head + 1) * ISO_PKT_SIZE);
442                         break;
443                 case GET_TRAILER:
444                         check_trailer(video, src + (head * ISO_PKT_SIZE),
445                                         ISO_PKT_SIZE);
446                         break;
447                 case GET_NONE:
448                         goto out;
449                 case GET_TOO_MUCH_BUBBLE:
450                         log("\t We got too much bubble");
451                         schedule_work(&video->bubble_work);
452                         return;
453                 }
454         } while (head = tail + 1, head < urb->number_of_packets);
455
456 out:
457         ret = usb_submit_urb(urb, GFP_ATOMIC);
458         if (ret)
459                 log("usb_submit_urb err : %d", ret);
460 }
461 /*============================= [  end  ] =====================*/
462
463 static int prepare_iso_urb(struct video_data *video)
464 {
465         struct usb_device *udev = video->pd->udev;
466         int i;
467
468         if (video->urb_array[0])
469                 return 0;
470
471         for (i = 0; i < SBUF_NUM; i++) {
472                 struct urb *urb;
473                 void *mem;
474                 int j;
475
476                 urb = usb_alloc_urb(PK_PER_URB, GFP_KERNEL);
477                 if (urb == NULL)
478                         goto out;
479
480                 video->urb_array[i] = urb;
481                 mem = usb_alloc_coherent(udev,
482                                          ISO_PKT_SIZE * PK_PER_URB,
483                                          GFP_KERNEL,
484                                          &urb->transfer_dma);
485
486                 urb->complete   = urb_complete_iso;     /* handler */
487                 urb->dev        = udev;
488                 urb->context    = video->front;
489                 urb->pipe       = usb_rcvisocpipe(udev,
490                                                 video->endpoint_addr);
491                 urb->interval   = 1;
492                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
493                 urb->number_of_packets  = PK_PER_URB;
494                 urb->transfer_buffer    = mem;
495                 urb->transfer_buffer_length = PK_PER_URB * ISO_PKT_SIZE;
496
497                 for (j = 0; j < PK_PER_URB; j++) {
498                         urb->iso_frame_desc[j].offset = ISO_PKT_SIZE * j;
499                         urb->iso_frame_desc[j].length = ISO_PKT_SIZE;
500                 }
501         }
502         return 0;
503 out:
504         for (; i > 0; i--)
505                 ;
506         return -ENOMEM;
507 }
508
509 /* return the succeeded number of the allocation */
510 int alloc_bulk_urbs_generic(struct urb **urb_array, int num,
511                         struct usb_device *udev, u8 ep_addr,
512                         int buf_size, gfp_t gfp_flags,
513                         usb_complete_t complete_fn, void *context)
514 {
515         int i = 0;
516
517         for (; i < num; i++) {
518                 void *mem;
519                 struct urb *urb = usb_alloc_urb(0, gfp_flags);
520                 if (urb == NULL)
521                         return i;
522
523                 mem = usb_alloc_coherent(udev, buf_size, gfp_flags,
524                                          &urb->transfer_dma);
525                 if (mem == NULL) {
526                         usb_free_urb(urb);
527                         return i;
528                 }
529
530                 usb_fill_bulk_urb(urb, udev, usb_rcvbulkpipe(udev, ep_addr),
531                                 mem, buf_size, complete_fn, context);
532                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
533                 urb_array[i] = urb;
534         }
535         return i;
536 }
537
538 void free_all_urb_generic(struct urb **urb_array, int num)
539 {
540         int i;
541         struct urb *urb;
542
543         for (i = 0; i < num; i++) {
544                 urb = urb_array[i];
545                 if (urb) {
546                         usb_free_coherent(urb->dev,
547                                         urb->transfer_buffer_length,
548                                         urb->transfer_buffer,
549                                         urb->transfer_dma);
550                         usb_free_urb(urb);
551                         urb_array[i] = NULL;
552                 }
553         }
554 }
555
556 static int prepare_bulk_urb(struct video_data *video)
557 {
558         if (video->urb_array[0])
559                 return 0;
560
561         alloc_bulk_urbs_generic(video->urb_array, SBUF_NUM,
562                         video->pd->udev, video->endpoint_addr,
563                         0x2000, GFP_KERNEL,
564                         urb_complete_bulk, video->front);
565         return 0;
566 }
567
568 /* free the URBs */
569 static void free_all_urb(struct video_data *video)
570 {
571         free_all_urb_generic(video->urb_array, SBUF_NUM);
572 }
573
574 static void pd_buf_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
575 {
576         videobuf_vmalloc_free(vb);
577         vb->state = VIDEOBUF_NEEDS_INIT;
578 }
579
580 static void pd_buf_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
581 {
582         struct front_face *front = q->priv_data;
583         vb->state = VIDEOBUF_QUEUED;
584         list_add_tail(&vb->queue, &front->active);
585 }
586
587 static int pd_buf_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
588                            enum v4l2_field field)
589 {
590         struct front_face *front = q->priv_data;
591         int rc;
592
593         switch (front->type) {
594         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
595                 if (VIDEOBUF_NEEDS_INIT == vb->state) {
596                         struct v4l2_pix_format *pix;
597
598                         pix = &front->pd->video_data.context.pix;
599                         vb->size        = pix->sizeimage; /* real frame size */
600                         vb->width       = pix->width;
601                         vb->height      = pix->height;
602                         rc = videobuf_iolock(q, vb, NULL);
603                         if (rc < 0)
604                                 return rc;
605                 }
606                 break;
607         case V4L2_BUF_TYPE_VBI_CAPTURE:
608                 if (VIDEOBUF_NEEDS_INIT == vb->state) {
609                         vb->size        = front->pd->vbi_data.vbi_size;
610                         rc = videobuf_iolock(q, vb, NULL);
611                         if (rc < 0)
612                                 return rc;
613                 }
614                 break;
615         default:
616                 return -EINVAL;
617         }
618         vb->field = field;
619         vb->state = VIDEOBUF_PREPARED;
620         return 0;
621 }
622
623 static int fire_all_urb(struct video_data *video)
624 {
625         int i, ret;
626
627         video->is_streaming = 1;
628
629         for (i = 0; i < SBUF_NUM; i++) {
630                 ret = usb_submit_urb(video->urb_array[i], GFP_KERNEL);
631                 if (ret)
632                         log("(%d) failed: error %d", i, ret);
633         }
634         return ret;
635 }
636
637 static int start_video_stream(struct poseidon *pd)
638 {
639         struct video_data *video = &pd->video_data;
640         s32 cmd_status;
641
642         send_set_req(pd, TAKE_REQUEST, 0, &cmd_status);
643         send_set_req(pd, PLAY_SERVICE, TLG_TUNE_PLAY_SVC_START, &cmd_status);
644
645         if (pd->cur_transfer_mode) {
646                 prepare_iso_urb(video);
647                 INIT_WORK(&video->bubble_work, iso_bubble_handler);
648         } else {
649                 /* The bulk mode does not need a bubble handler */
650                 prepare_bulk_urb(video);
651         }
652         fire_all_urb(video);
653         return 0;
654 }
655
656 static int pd_buf_setup(struct videobuf_queue *q, unsigned int *count,
657                        unsigned int *size)
658 {
659         struct front_face *front = q->priv_data;
660         struct poseidon *pd     = front->pd;
661
662         switch (front->type) {
663         default:
664                 return -EINVAL;
665         case V4L2_BUF_TYPE_VIDEO_CAPTURE: {
666                 struct video_data *video = &pd->video_data;
667                 struct v4l2_pix_format *pix = &video->context.pix;
668
669                 *size = PAGE_ALIGN(pix->sizeimage);/* page aligned frame size */
670                 if (*count < 4)
671                         *count = 4;
672                 if (1) {
673                         /* same in different altersetting */
674                         video->endpoint_addr    = 0x82;
675                         video->vbi              = &pd->vbi_data;
676                         video->vbi->video       = video;
677                         video->pd               = pd;
678                         video->lines_per_field  = pix->height / 2;
679                         video->lines_size       = pix->width * 2;
680                         video->front            = front;
681                 }
682                 return start_video_stream(pd);
683         }
684
685         case V4L2_BUF_TYPE_VBI_CAPTURE: {
686                 struct vbi_data *vbi = &pd->vbi_data;
687
688                 *size = PAGE_ALIGN(vbi->vbi_size);
689                 log("size : %d", *size);
690                 if (*count == 0)
691                         *count = 4;
692         }
693                 break;
694         }
695         return 0;
696 }
697
698 static struct videobuf_queue_ops pd_video_qops = {
699         .buf_setup      = pd_buf_setup,
700         .buf_prepare    = pd_buf_prepare,
701         .buf_queue      = pd_buf_queue,
702         .buf_release    = pd_buf_release,
703 };
704
705 static int vidioc_enum_fmt(struct file *file, void *fh,
706                                 struct v4l2_fmtdesc *f)
707 {
708         if (ARRAY_SIZE(poseidon_formats) <= f->index)
709                 return -EINVAL;
710         f->type         = V4L2_BUF_TYPE_VIDEO_CAPTURE;
711         f->flags        = 0;
712         f->pixelformat  = poseidon_formats[f->index].fourcc;
713         strcpy(f->description, poseidon_formats[f->index].name);
714         return 0;
715 }
716
717 static int vidioc_g_fmt(struct file *file, void *fh, struct v4l2_format *f)
718 {
719         struct front_face *front = fh;
720         struct poseidon *pd = front->pd;
721
722         logs(front);
723         f->fmt.pix = pd->video_data.context.pix;
724         return 0;
725 }
726
727 static int vidioc_try_fmt(struct file *file, void *fh,
728                 struct v4l2_format *f)
729 {
730         return 0;
731 }
732
733 /*
734  * VLC calls VIDIOC_S_STD before VIDIOC_S_FMT, while
735  * Mplayer calls them in the reverse order.
736  */
737 static int pd_vidioc_s_fmt(struct poseidon *pd, struct v4l2_pix_format *pix)
738 {
739         struct video_data *video        = &pd->video_data;
740         struct running_context *context = &video->context;
741         struct v4l2_pix_format *pix_def = &context->pix;
742         s32 ret = 0, cmd_status = 0, vid_resol;
743
744         /* set the pixel format to firmware */
745         if (pix->pixelformat == V4L2_PIX_FMT_RGB565) {
746                 vid_resol = TLG_TUNER_VID_FORMAT_RGB_565;
747         } else {
748                 pix->pixelformat = V4L2_PIX_FMT_YUYV;
749                 vid_resol = TLG_TUNER_VID_FORMAT_YUV;
750         }
751         ret = send_set_req(pd, VIDEO_STREAM_FMT_SEL,
752                                 vid_resol, &cmd_status);
753
754         /* set the resolution to firmware */
755         vid_resol = TLG_TUNE_VID_RES_720;
756         switch (pix->width) {
757         case 704:
758                 vid_resol = TLG_TUNE_VID_RES_704;
759                 break;
760         default:
761                 pix->width = 720;
762         case 720:
763                 break;
764         }
765         ret |= send_set_req(pd, VIDEO_ROSOLU_SEL,
766                                 vid_resol, &cmd_status);
767         if (ret || cmd_status) {
768                 mutex_unlock(&pd->lock);
769                 return -EBUSY;
770         }
771
772         pix_def->pixelformat = pix->pixelformat; /* save it */
773         pix->height = (context->tvnormid & V4L2_STD_525_60) ?  480 : 576;
774
775         /* Compare with the default setting */
776         if ((pix_def->width != pix->width)
777                 || (pix_def->height != pix->height)) {
778                 pix_def->width          = pix->width;
779                 pix_def->height         = pix->height;
780                 pix_def->bytesperline   = pix->width * 2;
781                 pix_def->sizeimage      = pix->width * pix->height * 2;
782         }
783         *pix = *pix_def;
784
785         return 0;
786 }
787
788 static int vidioc_s_fmt(struct file *file, void *fh, struct v4l2_format *f)
789 {
790         struct front_face *front        = fh;
791         struct poseidon *pd             = front->pd;
792
793         logs(front);
794         /* stop VBI here */
795         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != f->type)
796                 return -EINVAL;
797
798         mutex_lock(&pd->lock);
799         if (pd->file_for_stream == NULL)
800                 pd->file_for_stream = file;
801         else if (file != pd->file_for_stream) {
802                 mutex_unlock(&pd->lock);
803                 return -EINVAL;
804         }
805
806         pd_vidioc_s_fmt(pd, &f->fmt.pix);
807         mutex_unlock(&pd->lock);
808         return 0;
809 }
810
811 static int vidioc_g_fmt_vbi(struct file *file, void *fh,
812                                struct v4l2_format *v4l2_f)
813 {
814         struct front_face *front        = fh;
815         struct poseidon *pd             = front->pd;
816         struct v4l2_vbi_format *vbi_fmt = &v4l2_f->fmt.vbi;
817
818         vbi_fmt->samples_per_line       = 720 * 2;
819         vbi_fmt->sampling_rate          = 6750000 * 4;
820         vbi_fmt->sample_format          = V4L2_PIX_FMT_GREY;
821         vbi_fmt->offset                 = 64 * 4;  /*FIXME: why offset */
822         if (pd->video_data.context.tvnormid & V4L2_STD_525_60) {
823                 vbi_fmt->start[0] = 10;
824                 vbi_fmt->start[1] = 264;
825                 vbi_fmt->count[0] = V4L_NTSC_VBI_LINES;
826                 vbi_fmt->count[1] = V4L_NTSC_VBI_LINES;
827         } else {
828                 vbi_fmt->start[0] = 6;
829                 vbi_fmt->start[1] = 314;
830                 vbi_fmt->count[0] = V4L_PAL_VBI_LINES;
831                 vbi_fmt->count[1] = V4L_PAL_VBI_LINES;
832         }
833         vbi_fmt->flags = V4L2_VBI_UNSYNC;
834         logs(front);
835         return 0;
836 }
837
838 static int set_std(struct poseidon *pd, v4l2_std_id *norm)
839 {
840         struct video_data *video = &pd->video_data;
841         struct vbi_data *vbi    = &pd->vbi_data;
842         struct running_context *context;
843         struct v4l2_pix_format *pix;
844         s32 i, ret = 0, cmd_status, param;
845         int height;
846
847         for (i = 0; i < POSEIDON_TVNORMS; i++) {
848                 if (*norm & poseidon_tvnorms[i].v4l2_id) {
849                         param = poseidon_tvnorms[i].tlg_tvnorm;
850                         log("name : %s", poseidon_tvnorms[i].name);
851                         goto found;
852                 }
853         }
854         return -EINVAL;
855 found:
856         mutex_lock(&pd->lock);
857         ret = send_set_req(pd, VIDEO_STD_SEL, param, &cmd_status);
858         if (ret || cmd_status)
859                 goto out;
860
861         /* Set vbi size and check the height of the frame */
862         context = &video->context;
863         context->tvnormid = poseidon_tvnorms[i].v4l2_id;
864         if (context->tvnormid & V4L2_STD_525_60) {
865                 vbi->vbi_size = V4L_NTSC_VBI_FRAMESIZE;
866                 height = 480;
867         } else {
868                 vbi->vbi_size = V4L_PAL_VBI_FRAMESIZE;
869                 height = 576;
870         }
871
872         pix = &context->pix;
873         if (pix->height != height) {
874                 pix->height     = height;
875                 pix->sizeimage  = pix->width * pix->height * 2;
876         }
877
878 out:
879         mutex_unlock(&pd->lock);
880         return ret;
881 }
882
883 static int vidioc_s_std(struct file *file, void *fh, v4l2_std_id *norm)
884 {
885         struct front_face *front = fh;
886         logs(front);
887         return set_std(front->pd, norm);
888 }
889
890 static int vidioc_enum_input(struct file *file, void *fh, struct v4l2_input *in)
891 {
892         struct front_face *front = fh;
893
894         if (in->index < 0 || in->index >= POSEIDON_INPUTS)
895                 return -EINVAL;
896         strcpy(in->name, pd_inputs[in->index].name);
897         in->type  = V4L2_INPUT_TYPE_TUNER;
898
899         /*
900          * the audio input index mixed with this video input,
901          * Poseidon only have one audio/video, set to "0"
902          */
903         in->audioset    = 0;
904         in->tuner       = 0;
905         in->std         = V4L2_STD_ALL;
906         in->status      = 0;
907         logs(front);
908         return 0;
909 }
910
911 static int vidioc_g_input(struct file *file, void *fh, unsigned int *i)
912 {
913         struct front_face *front = fh;
914         struct poseidon *pd = front->pd;
915         struct running_context *context = &pd->video_data.context;
916
917         logs(front);
918         *i = context->sig_index;
919         return 0;
920 }
921
922 /* We can support several inputs */
923 static int vidioc_s_input(struct file *file, void *fh, unsigned int i)
924 {
925         struct front_face *front = fh;
926         struct poseidon *pd = front->pd;
927         s32 ret, cmd_status;
928
929         if (i < 0 || i >= POSEIDON_INPUTS)
930                 return -EINVAL;
931         ret = send_set_req(pd, SGNL_SRC_SEL,
932                         pd_inputs[i].tlg_src, &cmd_status);
933         if (ret)
934                 return ret;
935
936         pd->video_data.context.sig_index = i;
937         return 0;
938 }
939
940 static struct poseidon_control *check_control_id(__u32 id)
941 {
942         struct poseidon_control *control = &controls[0];
943         int array_size = ARRAY_SIZE(controls);
944
945         for (; control < &controls[array_size]; control++)
946                 if (control->v4l2_ctrl.id  == id)
947                         return control;
948         return NULL;
949 }
950
951 static int vidioc_queryctrl(struct file *file, void *fh,
952                         struct v4l2_queryctrl *a)
953 {
954         struct poseidon_control *control = NULL;
955
956         control = check_control_id(a->id);
957         if (!control)
958                 return -EINVAL;
959
960         *a = control->v4l2_ctrl;
961         return 0;
962 }
963
964 static int vidioc_g_ctrl(struct file *file, void *fh, struct v4l2_control *ctrl)
965 {
966         struct front_face *front = fh;
967         struct poseidon *pd = front->pd;
968         struct poseidon_control *control = NULL;
969         struct tuner_custom_parameter_s tuner_param;
970         s32 ret = 0, cmd_status;
971
972         control = check_control_id(ctrl->id);
973         if (!control)
974                 return -EINVAL;
975
976         mutex_lock(&pd->lock);
977         ret = send_get_req(pd, TUNER_CUSTOM_PARAMETER, control->vc_id,
978                         &tuner_param, &cmd_status, sizeof(tuner_param));
979         mutex_unlock(&pd->lock);
980
981         if (ret || cmd_status)
982                 return -1;
983
984         ctrl->value = tuner_param.param_value;
985         return 0;
986 }
987
988 static int vidioc_s_ctrl(struct file *file, void *fh, struct v4l2_control *a)
989 {
990         struct tuner_custom_parameter_s param = {0};
991         struct poseidon_control *control = NULL;
992         struct front_face *front        = fh;
993         struct poseidon *pd             = front->pd;
994         s32 ret = 0, cmd_status, params;
995
996         control = check_control_id(a->id);
997         if (!control)
998                 return -EINVAL;
999
1000         param.param_value = a->value;
1001         param.param_id  = control->vc_id;
1002         params = *(s32 *)&param; /* temp code */
1003
1004         mutex_lock(&pd->lock);
1005         ret = send_set_req(pd, TUNER_CUSTOM_PARAMETER, params, &cmd_status);
1006         ret = send_set_req(pd, TAKE_REQUEST, 0, &cmd_status);
1007         mutex_unlock(&pd->lock);
1008
1009         set_current_state(TASK_INTERRUPTIBLE);
1010         schedule_timeout(HZ/4);
1011         return ret;
1012 }
1013
1014 /* Audio ioctls */
1015 static int vidioc_enumaudio(struct file *file, void *fh, struct v4l2_audio *a)
1016 {
1017         if (0 != a->index)
1018                 return -EINVAL;
1019         a->capability = V4L2_AUDCAP_STEREO;
1020         strcpy(a->name, "USB audio in");
1021         /*Poseidon have no AVL function.*/
1022         a->mode = 0;
1023         return 0;
1024 }
1025
1026 static int vidioc_g_audio(struct file *file, void *fh, struct v4l2_audio *a)
1027 {
1028         a->index = 0;
1029         a->capability = V4L2_AUDCAP_STEREO;
1030         strcpy(a->name, "USB audio in");
1031         a->mode = 0;
1032         return 0;
1033 }
1034
1035 static int vidioc_s_audio(struct file *file, void *fh, struct v4l2_audio *a)
1036 {
1037         return (0 == a->index) ? 0 : -EINVAL;
1038 }
1039
1040 /* Tuner ioctls */
1041 static int vidioc_g_tuner(struct file *file, void *fh, struct v4l2_tuner *tuner)
1042 {
1043         struct front_face *front        = fh;
1044         struct poseidon *pd             = front->pd;
1045         struct tuner_atv_sig_stat_s atv_stat;
1046         s32 count = 5, ret, cmd_status;
1047         int index;
1048
1049         if (0 != tuner->index)
1050                 return -EINVAL;
1051
1052         mutex_lock(&pd->lock);
1053         ret = send_get_req(pd, TUNER_STATUS, TLG_MODE_ANALOG_TV,
1054                                 &atv_stat, &cmd_status, sizeof(atv_stat));
1055
1056         while (atv_stat.sig_lock_busy && count-- && !ret) {
1057                 set_current_state(TASK_INTERRUPTIBLE);
1058                 schedule_timeout(HZ);
1059
1060                 ret = send_get_req(pd, TUNER_STATUS, TLG_MODE_ANALOG_TV,
1061                                 &atv_stat, &cmd_status, sizeof(atv_stat));
1062         }
1063         mutex_unlock(&pd->lock);
1064
1065         if (debug_mode)
1066                 log("P:%d,S:%d", atv_stat.sig_present, atv_stat.sig_strength);
1067
1068         if (ret || cmd_status)
1069                 tuner->signal = 0;
1070         else if (atv_stat.sig_present && !atv_stat.sig_strength)
1071                 tuner->signal = 0xFFFF;
1072         else
1073                 tuner->signal = (atv_stat.sig_strength * 255 / 10) << 8;
1074
1075         strcpy(tuner->name, "Telegent Systems");
1076         tuner->type = V4L2_TUNER_ANALOG_TV;
1077         tuner->rangelow = TUNER_FREQ_MIN / 62500;
1078         tuner->rangehigh = TUNER_FREQ_MAX / 62500;
1079         tuner->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO |
1080                                 V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2;
1081         index = pd->video_data.context.audio_idx;
1082         tuner->rxsubchans = pd_audio_modes[index].v4l2_audio_sub;
1083         tuner->audmode = pd_audio_modes[index].v4l2_audio_mode;
1084         tuner->afc = 0;
1085         logs(front);
1086         return 0;
1087 }
1088
1089 static int pd_vidioc_s_tuner(struct poseidon *pd, int index)
1090 {
1091         s32 ret = 0, cmd_status, param, audiomode;
1092
1093         mutex_lock(&pd->lock);
1094         param = pd_audio_modes[index].tlg_audio_mode;
1095         ret = send_set_req(pd, TUNER_AUD_MODE, param, &cmd_status);
1096         audiomode = get_audio_std(pd->video_data.context.tvnormid);
1097         ret |= send_set_req(pd, TUNER_AUD_ANA_STD, audiomode,
1098                                 &cmd_status);
1099         if (!ret)
1100                 pd->video_data.context.audio_idx = index;
1101         mutex_unlock(&pd->lock);
1102         return ret;
1103 }
1104
1105 static int vidioc_s_tuner(struct file *file, void *fh, struct v4l2_tuner *a)
1106 {
1107         struct front_face *front        = fh;
1108         struct poseidon *pd             = front->pd;
1109         int index;
1110
1111         if (0 != a->index)
1112                 return -EINVAL;
1113         logs(front);
1114         for (index = 0; index < POSEIDON_AUDIOMODS; index++)
1115                 if (a->audmode == pd_audio_modes[index].v4l2_audio_mode)
1116                         return pd_vidioc_s_tuner(pd, index);
1117         return -EINVAL;
1118 }
1119
1120 static int vidioc_g_frequency(struct file *file, void *fh,
1121                         struct v4l2_frequency *freq)
1122 {
1123         struct front_face *front = fh;
1124         struct poseidon *pd = front->pd;
1125         struct running_context *context = &pd->video_data.context;
1126
1127         if (0 != freq->tuner)
1128                 return -EINVAL;
1129         freq->frequency = context->freq;
1130         freq->type = V4L2_TUNER_ANALOG_TV;
1131         return 0;
1132 }
1133
1134 static int set_frequency(struct poseidon *pd, __u32 frequency)
1135 {
1136         s32 ret = 0, param, cmd_status;
1137         struct running_context *context = &pd->video_data.context;
1138
1139         param = frequency * 62500 / 1000;
1140         if (param < TUNER_FREQ_MIN/1000 || param > TUNER_FREQ_MAX / 1000)
1141                 return -EINVAL;
1142
1143         mutex_lock(&pd->lock);
1144         ret = send_set_req(pd, TUNE_FREQ_SELECT, param, &cmd_status);
1145         ret = send_set_req(pd, TAKE_REQUEST, 0, &cmd_status);
1146
1147         msleep(250); /* wait for a while until the hardware is ready. */
1148         context->freq = frequency;
1149         mutex_unlock(&pd->lock);
1150         return ret;
1151 }
1152
1153 static int vidioc_s_frequency(struct file *file, void *fh,
1154                                 struct v4l2_frequency *freq)
1155 {
1156         struct front_face *front = fh;
1157         struct poseidon *pd = front->pd;
1158
1159         logs(front);
1160 #ifdef CONFIG_PM
1161         pd->pm_suspend = pm_video_suspend;
1162         pd->pm_resume = pm_video_resume;
1163 #endif
1164         return set_frequency(pd, freq->frequency);
1165 }
1166
1167 static int vidioc_reqbufs(struct file *file, void *fh,
1168                                 struct v4l2_requestbuffers *b)
1169 {
1170         struct front_face *front = file->private_data;
1171         logs(front);
1172         return videobuf_reqbufs(&front->q, b);
1173 }
1174
1175 static int vidioc_querybuf(struct file *file, void *fh, struct v4l2_buffer *b)
1176 {
1177         struct front_face *front = file->private_data;
1178         logs(front);
1179         return videobuf_querybuf(&front->q, b);
1180 }
1181
1182 static int vidioc_qbuf(struct file *file, void *fh, struct v4l2_buffer *b)
1183 {
1184         struct front_face *front = file->private_data;
1185         return videobuf_qbuf(&front->q, b);
1186 }
1187
1188 static int vidioc_dqbuf(struct file *file, void *fh, struct v4l2_buffer *b)
1189 {
1190         struct front_face *front = file->private_data;
1191         return videobuf_dqbuf(&front->q, b, file->f_flags & O_NONBLOCK);
1192 }
1193
1194 /* Just stop the URBs, do not free the URBs */
1195 static int usb_transfer_stop(struct video_data *video)
1196 {
1197         if (video->is_streaming) {
1198                 int i;
1199                 s32 cmd_status;
1200                 struct poseidon *pd = video->pd;
1201
1202                 video->is_streaming = 0;
1203                 for (i = 0; i < SBUF_NUM; ++i) {
1204                         if (video->urb_array[i])
1205                                 usb_kill_urb(video->urb_array[i]);
1206                 }
1207
1208                 send_set_req(pd, PLAY_SERVICE, TLG_TUNE_PLAY_SVC_STOP,
1209                                &cmd_status);
1210         }
1211         return 0;
1212 }
1213
1214 int stop_all_video_stream(struct poseidon *pd)
1215 {
1216         struct video_data *video = &pd->video_data;
1217         struct vbi_data *vbi    = &pd->vbi_data;
1218
1219         mutex_lock(&pd->lock);
1220         if (video->is_streaming) {
1221                 struct front_face *front = video->front;
1222
1223                 /* stop the URBs */
1224                 usb_transfer_stop(video);
1225                 free_all_urb(video);
1226
1227                 /* stop the host side of VIDEO */
1228                 videobuf_stop(&front->q);
1229                 videobuf_mmap_free(&front->q);
1230
1231                 /* stop the host side of VBI */
1232                 front = vbi->front;
1233                 if (front) {
1234                         videobuf_stop(&front->q);
1235                         videobuf_mmap_free(&front->q);
1236                 }
1237         }
1238         mutex_unlock(&pd->lock);
1239         return 0;
1240 }
1241
1242 /*
1243  * The bubbles can seriously damage the video's quality,
1244  * though it occurs in very rare situation.
1245  */
1246 static void iso_bubble_handler(struct work_struct *w)
1247 {
1248         struct video_data *video;
1249         struct poseidon *pd;
1250
1251         video = container_of(w, struct video_data, bubble_work);
1252         pd = video->pd;
1253
1254         mutex_lock(&pd->lock);
1255         usb_transfer_stop(video);
1256         msleep(500);
1257         start_video_stream(pd);
1258         mutex_unlock(&pd->lock);
1259 }
1260
1261
1262 static int vidioc_streamon(struct file *file, void *fh,
1263                                 enum v4l2_buf_type type)
1264 {
1265         struct front_face *front = fh;
1266
1267         logs(front);
1268         if (unlikely(type != front->type))
1269                 return -EINVAL;
1270         return videobuf_streamon(&front->q);
1271 }
1272
1273 static int vidioc_streamoff(struct file *file, void *fh,
1274                                 enum v4l2_buf_type type)
1275 {
1276         struct front_face *front = file->private_data;
1277
1278         logs(front);
1279         if (unlikely(type != front->type))
1280                 return -EINVAL;
1281         return videobuf_streamoff(&front->q);
1282 }
1283
1284 /* Set the firmware's default values : need altersetting */
1285 static int pd_video_checkmode(struct poseidon *pd)
1286 {
1287         s32 ret = 0, cmd_status, audiomode;
1288
1289         set_current_state(TASK_INTERRUPTIBLE);
1290         schedule_timeout(HZ/2);
1291
1292         /* choose the altersetting */
1293         ret = usb_set_interface(pd->udev, 0,
1294                                         (pd->cur_transfer_mode ?
1295                                          ISO_3K_BULK_ALTERNATE_IFACE :
1296                                          BULK_ALTERNATE_IFACE));
1297         if (ret < 0)
1298                 goto error;
1299
1300         /* set default parameters for PAL-D , with the VBI enabled*/
1301         ret = set_tuner_mode(pd, TLG_MODE_ANALOG_TV);
1302         ret |= send_set_req(pd, SGNL_SRC_SEL,
1303                                 TLG_SIG_SRC_ANTENNA, &cmd_status);
1304         ret |= send_set_req(pd, VIDEO_STD_SEL,
1305                                 TLG_TUNE_VSTD_PAL_D, &cmd_status);
1306         ret |= send_set_req(pd, VIDEO_STREAM_FMT_SEL,
1307                                 TLG_TUNER_VID_FORMAT_YUV, &cmd_status);
1308         ret |= send_set_req(pd, VIDEO_ROSOLU_SEL,
1309                                 TLG_TUNE_VID_RES_720, &cmd_status);
1310         ret |= send_set_req(pd, TUNE_FREQ_SELECT, TUNER_FREQ_MIN, &cmd_status);
1311         ret |= send_set_req(pd, VBI_DATA_SEL, 1, &cmd_status);/* enable vbi */
1312
1313         /* set the audio */
1314         audiomode = get_audio_std(pd->video_data.context.tvnormid);
1315         ret |= send_set_req(pd, TUNER_AUD_ANA_STD, audiomode, &cmd_status);
1316         ret |= send_set_req(pd, TUNER_AUD_MODE,
1317                                 TLG_TUNE_TVAUDIO_MODE_STEREO, &cmd_status);
1318         ret |= send_set_req(pd, AUDIO_SAMPLE_RATE_SEL,
1319                                 ATV_AUDIO_RATE_48K, &cmd_status);
1320 error:
1321         return ret;
1322 }
1323
1324 #ifdef CONFIG_PM
1325 static int pm_video_suspend(struct poseidon *pd)
1326 {
1327         /* stop audio */
1328         pm_alsa_suspend(pd);
1329
1330         /* stop and free all the URBs */
1331         usb_transfer_stop(&pd->video_data);
1332         free_all_urb(&pd->video_data);
1333
1334         /* reset the interface */
1335         usb_set_interface(pd->udev, 0, 0);
1336         msleep(300);
1337         return 0;
1338 }
1339
1340 static int restore_v4l2_context(struct poseidon *pd,
1341                                 struct running_context *context)
1342 {
1343         struct front_face *front = pd->video_data.front;
1344
1345         pd_video_checkmode(pd);
1346
1347         set_std(pd, &context->tvnormid);
1348         vidioc_s_input(NULL, front, context->sig_index);
1349         pd_vidioc_s_tuner(pd, context->audio_idx);
1350         pd_vidioc_s_fmt(pd, &context->pix);
1351         set_frequency(pd, context->freq);
1352         return 0;
1353 }
1354
1355 static int pm_video_resume(struct poseidon *pd)
1356 {
1357         struct video_data *video = &pd->video_data;
1358
1359         /* resume the video */
1360         /* [1] restore the origin V4L2 parameters */
1361         restore_v4l2_context(pd, &video->context);
1362
1363         /* [2] initiate video copy variables */
1364         if (video->front->curr_frame)
1365                 init_copy(video, 0);
1366
1367         /* [3] fire urbs        */
1368         start_video_stream(pd);
1369
1370         /* resume the audio */
1371         pm_alsa_resume(pd);
1372         return 0;
1373 }
1374 #endif
1375
1376 void set_debug_mode(struct video_device *vfd, int debug_mode)
1377 {
1378         vfd->debug = 0;
1379         if (debug_mode & 0x1)
1380                 vfd->debug = V4L2_DEBUG_IOCTL;
1381         if (debug_mode & 0x2)
1382                 vfd->debug = V4L2_DEBUG_IOCTL | V4L2_DEBUG_IOCTL_ARG;
1383 }
1384
1385 static void init_video_context(struct running_context *context)
1386 {
1387         context->sig_index      = 0;
1388         context->audio_idx      = 1; /* stereo */
1389         context->tvnormid       = V4L2_STD_PAL_D;
1390         context->pix = (struct v4l2_pix_format) {
1391                                 .width          = 720,
1392                                 .height         = 576,
1393                                 .pixelformat    = V4L2_PIX_FMT_YUYV,
1394                                 .field          = V4L2_FIELD_INTERLACED,
1395                                 .bytesperline   = 720 * 2,
1396                                 .sizeimage      = 720 * 576 * 2,
1397                                 .colorspace     = V4L2_COLORSPACE_SMPTE170M,
1398                                 .priv           = 0
1399                         };
1400 }
1401
1402 static int pd_video_open(struct file *file)
1403 {
1404         struct video_device *vfd = video_devdata(file);
1405         struct poseidon *pd = video_get_drvdata(vfd);
1406         struct front_face *front = NULL;
1407         int ret = -ENOMEM;
1408
1409         mutex_lock(&pd->lock);
1410         usb_autopm_get_interface(pd->interface);
1411
1412         if (vfd->vfl_type == VFL_TYPE_GRABBER
1413                 && !(pd->state & POSEIDON_STATE_ANALOG)) {
1414                 front = kzalloc(sizeof(struct front_face), GFP_KERNEL);
1415                 if (!front)
1416                         goto out;
1417
1418                 pd->cur_transfer_mode   = usb_transfer_mode;/* bulk or iso */
1419                 init_video_context(&pd->video_data.context);
1420
1421                 ret = pd_video_checkmode(pd);
1422                 if (ret < 0) {
1423                         kfree(front);
1424                         ret = -1;
1425                         goto out;
1426                 }
1427
1428                 pd->state               |= POSEIDON_STATE_ANALOG;
1429                 front->type             = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1430                 pd->video_data.users++;
1431                 set_debug_mode(vfd, debug_mode);
1432
1433                 videobuf_queue_vmalloc_init(&front->q, &pd_video_qops,
1434                                 NULL, &front->queue_lock,
1435                                 V4L2_BUF_TYPE_VIDEO_CAPTURE,
1436                                 V4L2_FIELD_INTERLACED,/* video is interlacd */
1437                                 sizeof(struct videobuf_buffer),/*it's enough*/
1438                                 front, NULL);
1439         } else if (vfd->vfl_type == VFL_TYPE_VBI
1440                 && !(pd->state & POSEIDON_STATE_VBI)) {
1441                 front = kzalloc(sizeof(struct front_face), GFP_KERNEL);
1442                 if (!front)
1443                         goto out;
1444
1445                 pd->state       |= POSEIDON_STATE_VBI;
1446                 front->type     = V4L2_BUF_TYPE_VBI_CAPTURE;
1447                 pd->vbi_data.front = front;
1448                 pd->vbi_data.users++;
1449
1450                 videobuf_queue_vmalloc_init(&front->q, &pd_video_qops,
1451                                 NULL, &front->queue_lock,
1452                                 V4L2_BUF_TYPE_VBI_CAPTURE,
1453                                 V4L2_FIELD_NONE, /* vbi is NONE mode */
1454                                 sizeof(struct videobuf_buffer),
1455                                 front, NULL);
1456         } else {
1457                 /* maybe add FM support here */
1458                 log("other ");
1459                 ret = -EINVAL;
1460                 goto out;
1461         }
1462
1463         front->pd               = pd;
1464         front->curr_frame       = NULL;
1465         INIT_LIST_HEAD(&front->active);
1466         spin_lock_init(&front->queue_lock);
1467
1468         file->private_data      = front;
1469         kref_get(&pd->kref);
1470
1471         mutex_unlock(&pd->lock);
1472         return 0;
1473 out:
1474         usb_autopm_put_interface(pd->interface);
1475         mutex_unlock(&pd->lock);
1476         return ret;
1477 }
1478
1479 static int pd_video_release(struct file *file)
1480 {
1481         struct front_face *front = file->private_data;
1482         struct poseidon *pd = front->pd;
1483         s32 cmd_status = 0;
1484
1485         logs(front);
1486         mutex_lock(&pd->lock);
1487
1488         if (front->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1489                 pd->state &= ~POSEIDON_STATE_ANALOG;
1490
1491                 /* stop the device, and free the URBs */
1492                 usb_transfer_stop(&pd->video_data);
1493                 free_all_urb(&pd->video_data);
1494
1495                 /* stop the firmware */
1496                 send_set_req(pd, PLAY_SERVICE, TLG_TUNE_PLAY_SVC_STOP,
1497                                &cmd_status);
1498
1499                 pd->file_for_stream = NULL;
1500                 pd->video_data.users--;
1501         } else if (front->type  == V4L2_BUF_TYPE_VBI_CAPTURE) {
1502                 pd->state &= ~POSEIDON_STATE_VBI;
1503                 pd->vbi_data.front = NULL;
1504                 pd->vbi_data.users--;
1505         }
1506         videobuf_stop(&front->q);
1507         videobuf_mmap_free(&front->q);
1508
1509         usb_autopm_put_interface(pd->interface);
1510         mutex_unlock(&pd->lock);
1511
1512         kfree(front);
1513         file->private_data = NULL;
1514         kref_put(&pd->kref, poseidon_delete);
1515         return 0;
1516 }
1517
1518 static int pd_video_mmap(struct file *file, struct vm_area_struct *vma)
1519 {
1520         struct front_face *front = file->private_data;
1521         return  videobuf_mmap_mapper(&front->q, vma);
1522 }
1523
1524 static unsigned int pd_video_poll(struct file *file, poll_table *table)
1525 {
1526         struct front_face *front = file->private_data;
1527         return videobuf_poll_stream(file, &front->q, table);
1528 }
1529
1530 static ssize_t pd_video_read(struct file *file, char __user *buffer,
1531                         size_t count, loff_t *ppos)
1532 {
1533         struct front_face *front = file->private_data;
1534         return videobuf_read_stream(&front->q, buffer, count, ppos,
1535                                 0, file->f_flags & O_NONBLOCK);
1536 }
1537
1538 /* This struct works for both VIDEO and VBI */
1539 static const struct v4l2_file_operations pd_video_fops = {
1540         .owner          = THIS_MODULE,
1541         .open           = pd_video_open,
1542         .release        = pd_video_release,
1543         .read           = pd_video_read,
1544         .poll           = pd_video_poll,
1545         .mmap           = pd_video_mmap,
1546         .ioctl          = video_ioctl2, /* maybe changed in future */
1547 };
1548
1549 static const struct v4l2_ioctl_ops pd_video_ioctl_ops = {
1550         .vidioc_querycap        = vidioc_querycap,
1551
1552         /* Video format */
1553         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt,
1554         .vidioc_enum_fmt_vid_cap        = vidioc_enum_fmt,
1555         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt,
1556         .vidioc_g_fmt_vbi_cap   = vidioc_g_fmt_vbi, /* VBI */
1557         .vidioc_try_fmt_vid_cap = vidioc_try_fmt,
1558
1559         /* Input */
1560         .vidioc_g_input         = vidioc_g_input,
1561         .vidioc_s_input         = vidioc_s_input,
1562         .vidioc_enum_input      = vidioc_enum_input,
1563
1564         /* Audio ioctls */
1565         .vidioc_enumaudio       = vidioc_enumaudio,
1566         .vidioc_g_audio         = vidioc_g_audio,
1567         .vidioc_s_audio         = vidioc_s_audio,
1568
1569         /* Tuner ioctls */
1570         .vidioc_g_tuner         = vidioc_g_tuner,
1571         .vidioc_s_tuner         = vidioc_s_tuner,
1572         .vidioc_s_std           = vidioc_s_std,
1573         .vidioc_g_frequency     = vidioc_g_frequency,
1574         .vidioc_s_frequency     = vidioc_s_frequency,
1575
1576         /* Buffer handlers */
1577         .vidioc_reqbufs         = vidioc_reqbufs,
1578         .vidioc_querybuf        = vidioc_querybuf,
1579         .vidioc_qbuf            = vidioc_qbuf,
1580         .vidioc_dqbuf           = vidioc_dqbuf,
1581
1582         /* Stream on/off */
1583         .vidioc_streamon        = vidioc_streamon,
1584         .vidioc_streamoff       = vidioc_streamoff,
1585
1586         /* Control handling */
1587         .vidioc_queryctrl       = vidioc_queryctrl,
1588         .vidioc_g_ctrl          = vidioc_g_ctrl,
1589         .vidioc_s_ctrl          = vidioc_s_ctrl,
1590 };
1591
1592 static struct video_device pd_video_template = {
1593         .name = "Telegent-Video",
1594         .fops = &pd_video_fops,
1595         .minor = -1,
1596         .release = video_device_release,
1597         .tvnorms = V4L2_STD_ALL,
1598         .ioctl_ops = &pd_video_ioctl_ops,
1599 };
1600
1601 struct video_device *vdev_init(struct poseidon *pd, struct video_device *tmp)
1602 {
1603         struct video_device *vfd;
1604
1605         vfd = video_device_alloc();
1606         if (vfd == NULL)
1607                 return NULL;
1608         *vfd            = *tmp;
1609         vfd->minor      = -1;
1610         vfd->v4l2_dev   = &pd->v4l2_dev;
1611         /*vfd->parent   = &(pd->udev->dev); */
1612         vfd->release    = video_device_release;
1613         video_set_drvdata(vfd, pd);
1614         return vfd;
1615 }
1616
1617 void destroy_video_device(struct video_device **v_dev)
1618 {
1619         struct video_device *dev = *v_dev;
1620
1621         if (dev == NULL)
1622                 return;
1623
1624         if (video_is_registered(dev))
1625                 video_unregister_device(dev);
1626         else
1627                 video_device_release(dev);
1628         *v_dev = NULL;
1629 }
1630
1631 void pd_video_exit(struct poseidon *pd)
1632 {
1633         struct video_data *video = &pd->video_data;
1634         struct vbi_data *vbi = &pd->vbi_data;
1635
1636         destroy_video_device(&video->v_dev);
1637         destroy_video_device(&vbi->v_dev);
1638         log();
1639 }
1640
1641 int pd_video_init(struct poseidon *pd)
1642 {
1643         struct video_data *video = &pd->video_data;
1644         struct vbi_data *vbi    = &pd->vbi_data;
1645         int ret = -ENOMEM;
1646
1647         video->v_dev = vdev_init(pd, &pd_video_template);
1648         if (video->v_dev == NULL)
1649                 goto out;
1650
1651         ret = video_register_device(video->v_dev, VFL_TYPE_GRABBER, -1);
1652         if (ret != 0)
1653                 goto out;
1654
1655         /* VBI uses the same template as video */
1656         vbi->v_dev = vdev_init(pd, &pd_video_template);
1657         if (vbi->v_dev == NULL) {
1658                 ret = -ENOMEM;
1659                 goto out;
1660         }
1661         ret = video_register_device(vbi->v_dev, VFL_TYPE_VBI, -1);
1662         if (ret != 0)
1663                 goto out;
1664         log("register VIDEO/VBI devices");
1665         return 0;
1666 out:
1667         log("VIDEO/VBI devices register failed, : %d", ret);
1668         pd_video_exit(pd);
1669         return ret;
1670 }
1671