GNU Linux-libre 4.4.289-gnu1
[releases.git] / drivers / media / usb / au0828 / au0828-video.c
1 /*
2  * Auvitek AU0828 USB Bridge (Analog video support)
3  *
4  * Copyright (C) 2009 Devin Heitmueller <dheitmueller@linuxtv.org>
5  * Copyright (C) 2005-2008 Auvitek International, Ltd.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * As published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20  * 02110-1301, USA.
21  */
22
23 /* Developer Notes:
24  *
25  * The hardware scaler supported is unimplemented
26  * AC97 audio support is unimplemented (only i2s audio mode)
27  *
28  */
29
30 #include "au0828.h"
31
32 #include <linux/module.h>
33 #include <linux/slab.h>
34 #include <linux/init.h>
35 #include <linux/device.h>
36 #include <media/v4l2-common.h>
37 #include <media/v4l2-ioctl.h>
38 #include <media/v4l2-event.h>
39 #include <media/tuner.h>
40 #include "au0828-reg.h"
41
42 static DEFINE_MUTEX(au0828_sysfs_lock);
43
44 /* ------------------------------------------------------------------
45         Videobuf operations
46    ------------------------------------------------------------------*/
47
48 static unsigned int isoc_debug;
49 module_param(isoc_debug, int, 0644);
50 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
51
52 #define au0828_isocdbg(fmt, arg...) \
53 do {\
54         if (isoc_debug) { \
55                 pr_info("au0828 %s :"fmt, \
56                        __func__ , ##arg);          \
57         } \
58   } while (0)
59
60 static inline void i2c_gate_ctrl(struct au0828_dev *dev, int val)
61 {
62         if (dev->dvb.frontend && dev->dvb.frontend->ops.analog_ops.i2c_gate_ctrl)
63                 dev->dvb.frontend->ops.analog_ops.i2c_gate_ctrl(dev->dvb.frontend, val);
64 }
65
66 static inline void print_err_status(struct au0828_dev *dev,
67                                     int packet, int status)
68 {
69         char *errmsg = "Unknown";
70
71         switch (status) {
72         case -ENOENT:
73                 errmsg = "unlinked synchronuously";
74                 break;
75         case -ECONNRESET:
76                 errmsg = "unlinked asynchronuously";
77                 break;
78         case -ENOSR:
79                 errmsg = "Buffer error (overrun)";
80                 break;
81         case -EPIPE:
82                 errmsg = "Stalled (device not responding)";
83                 break;
84         case -EOVERFLOW:
85                 errmsg = "Babble (bad cable?)";
86                 break;
87         case -EPROTO:
88                 errmsg = "Bit-stuff error (bad cable?)";
89                 break;
90         case -EILSEQ:
91                 errmsg = "CRC/Timeout (could be anything)";
92                 break;
93         case -ETIME:
94                 errmsg = "Device does not respond";
95                 break;
96         }
97         if (packet < 0) {
98                 au0828_isocdbg("URB status %d [%s].\n", status, errmsg);
99         } else {
100                 au0828_isocdbg("URB packet %d, status %d [%s].\n",
101                                packet, status, errmsg);
102         }
103 }
104
105 static int check_dev(struct au0828_dev *dev)
106 {
107         if (test_bit(DEV_DISCONNECTED, &dev->dev_state)) {
108                 pr_info("v4l2 ioctl: device not present\n");
109                 return -ENODEV;
110         }
111
112         if (test_bit(DEV_MISCONFIGURED, &dev->dev_state)) {
113                 pr_info("v4l2 ioctl: device is misconfigured; close and open it again\n");
114                 return -EIO;
115         }
116         return 0;
117 }
118
119 /*
120  * IRQ callback, called by URB callback
121  */
122 static void au0828_irq_callback(struct urb *urb)
123 {
124         struct au0828_dmaqueue  *dma_q = urb->context;
125         struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
126         unsigned long flags = 0;
127         int i;
128
129         switch (urb->status) {
130         case 0:             /* success */
131         case -ETIMEDOUT:    /* NAK */
132                 break;
133         case -ECONNRESET:   /* kill */
134         case -ENOENT:
135         case -ESHUTDOWN:
136                 au0828_isocdbg("au0828_irq_callback called: status kill\n");
137                 return;
138         default:            /* unknown error */
139                 au0828_isocdbg("urb completition error %d.\n", urb->status);
140                 break;
141         }
142
143         /* Copy data from URB */
144         spin_lock_irqsave(&dev->slock, flags);
145         dev->isoc_ctl.isoc_copy(dev, urb);
146         spin_unlock_irqrestore(&dev->slock, flags);
147
148         /* Reset urb buffers */
149         for (i = 0; i < urb->number_of_packets; i++) {
150                 urb->iso_frame_desc[i].status = 0;
151                 urb->iso_frame_desc[i].actual_length = 0;
152         }
153         urb->status = 0;
154
155         urb->status = usb_submit_urb(urb, GFP_ATOMIC);
156         if (urb->status) {
157                 au0828_isocdbg("urb resubmit failed (error=%i)\n",
158                                urb->status);
159         }
160         dev->stream_state = STREAM_ON;
161 }
162
163 /*
164  * Stop and Deallocate URBs
165  */
166 static void au0828_uninit_isoc(struct au0828_dev *dev)
167 {
168         struct urb *urb;
169         int i;
170
171         au0828_isocdbg("au0828: called au0828_uninit_isoc\n");
172
173         dev->isoc_ctl.nfields = -1;
174         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
175                 urb = dev->isoc_ctl.urb[i];
176                 if (urb) {
177                         if (!irqs_disabled())
178                                 usb_kill_urb(urb);
179                         else
180                                 usb_unlink_urb(urb);
181
182                         if (dev->isoc_ctl.transfer_buffer[i]) {
183                                 usb_free_coherent(dev->usbdev,
184                                         urb->transfer_buffer_length,
185                                         dev->isoc_ctl.transfer_buffer[i],
186                                         urb->transfer_dma);
187                         }
188                         usb_free_urb(urb);
189                         dev->isoc_ctl.urb[i] = NULL;
190                 }
191                 dev->isoc_ctl.transfer_buffer[i] = NULL;
192         }
193
194         kfree(dev->isoc_ctl.urb);
195         kfree(dev->isoc_ctl.transfer_buffer);
196
197         dev->isoc_ctl.urb = NULL;
198         dev->isoc_ctl.transfer_buffer = NULL;
199         dev->isoc_ctl.num_bufs = 0;
200
201         dev->stream_state = STREAM_OFF;
202 }
203
204 /*
205  * Allocate URBs and start IRQ
206  */
207 static int au0828_init_isoc(struct au0828_dev *dev, int max_packets,
208                             int num_bufs, int max_pkt_size,
209                             int (*isoc_copy) (struct au0828_dev *dev, struct urb *urb))
210 {
211         struct au0828_dmaqueue *dma_q = &dev->vidq;
212         int i;
213         int sb_size, pipe;
214         struct urb *urb;
215         int j, k;
216         int rc;
217
218         au0828_isocdbg("au0828: called au0828_prepare_isoc\n");
219
220         dev->isoc_ctl.isoc_copy = isoc_copy;
221         dev->isoc_ctl.num_bufs = num_bufs;
222
223         dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs,  GFP_KERNEL);
224         if (!dev->isoc_ctl.urb) {
225                 au0828_isocdbg("cannot alloc memory for usb buffers\n");
226                 return -ENOMEM;
227         }
228
229         dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
230                                               GFP_KERNEL);
231         if (!dev->isoc_ctl.transfer_buffer) {
232                 au0828_isocdbg("cannot allocate memory for usb transfer\n");
233                 kfree(dev->isoc_ctl.urb);
234                 return -ENOMEM;
235         }
236
237         dev->isoc_ctl.max_pkt_size = max_pkt_size;
238         dev->isoc_ctl.buf = NULL;
239
240         sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
241
242         /* allocate urbs and transfer buffers */
243         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
244                 urb = usb_alloc_urb(max_packets, GFP_KERNEL);
245                 if (!urb) {
246                         au0828_isocdbg("cannot alloc isoc_ctl.urb %i\n", i);
247                         au0828_uninit_isoc(dev);
248                         return -ENOMEM;
249                 }
250                 dev->isoc_ctl.urb[i] = urb;
251
252                 dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->usbdev,
253                         sb_size, GFP_KERNEL, &urb->transfer_dma);
254                 if (!dev->isoc_ctl.transfer_buffer[i]) {
255                         printk("unable to allocate %i bytes for transfer"
256                                         " buffer %i%s\n",
257                                         sb_size, i,
258                                         in_interrupt() ? " while in int" : "");
259                         au0828_uninit_isoc(dev);
260                         return -ENOMEM;
261                 }
262                 memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
263
264                 pipe = usb_rcvisocpipe(dev->usbdev,
265                                        dev->isoc_in_endpointaddr),
266
267                 usb_fill_int_urb(urb, dev->usbdev, pipe,
268                                  dev->isoc_ctl.transfer_buffer[i], sb_size,
269                                  au0828_irq_callback, dma_q, 1);
270
271                 urb->number_of_packets = max_packets;
272                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
273
274                 k = 0;
275                 for (j = 0; j < max_packets; j++) {
276                         urb->iso_frame_desc[j].offset = k;
277                         urb->iso_frame_desc[j].length =
278                                                 dev->isoc_ctl.max_pkt_size;
279                         k += dev->isoc_ctl.max_pkt_size;
280                 }
281         }
282
283         /* submit urbs and enables IRQ */
284         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
285                 rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
286                 if (rc) {
287                         au0828_isocdbg("submit of urb %i failed (error=%i)\n",
288                                        i, rc);
289                         au0828_uninit_isoc(dev);
290                         return rc;
291                 }
292         }
293
294         return 0;
295 }
296
297 /*
298  * Announces that a buffer were filled and request the next
299  */
300 static inline void buffer_filled(struct au0828_dev *dev,
301                                  struct au0828_dmaqueue *dma_q,
302                                  struct au0828_buffer *buf)
303 {
304         struct vb2_v4l2_buffer *vb = &buf->vb;
305         struct vb2_queue *q = vb->vb2_buf.vb2_queue;
306
307         /* Advice that buffer was filled */
308         au0828_isocdbg("[%p/%d] wakeup\n", buf, buf->top_field);
309
310         if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
311                 vb->sequence = dev->frame_count++;
312         else
313                 vb->sequence = dev->vbi_frame_count++;
314
315         vb->field = V4L2_FIELD_INTERLACED;
316         v4l2_get_timestamp(&vb->timestamp);
317         vb2_buffer_done(&vb->vb2_buf, VB2_BUF_STATE_DONE);
318 }
319
320 /*
321  * Identify the buffer header type and properly handles
322  */
323 static void au0828_copy_video(struct au0828_dev *dev,
324                               struct au0828_dmaqueue  *dma_q,
325                               struct au0828_buffer *buf,
326                               unsigned char *p,
327                               unsigned char *outp, unsigned long len)
328 {
329         void *fieldstart, *startwrite, *startread;
330         int  linesdone, currlinedone, offset, lencopy, remain;
331         int bytesperline = dev->width << 1; /* Assumes 16-bit depth @@@@ */
332
333         if (len == 0)
334                 return;
335
336         if (dma_q->pos + len > buf->length)
337                 len = buf->length - dma_q->pos;
338
339         startread = p;
340         remain = len;
341
342         /* Interlaces frame */
343         if (buf->top_field)
344                 fieldstart = outp;
345         else
346                 fieldstart = outp + bytesperline;
347
348         linesdone = dma_q->pos / bytesperline;
349         currlinedone = dma_q->pos % bytesperline;
350         offset = linesdone * bytesperline * 2 + currlinedone;
351         startwrite = fieldstart + offset;
352         lencopy = bytesperline - currlinedone;
353         lencopy = lencopy > remain ? remain : lencopy;
354
355         if ((char *)startwrite + lencopy > (char *)outp + buf->length) {
356                 au0828_isocdbg("Overflow of %zi bytes past buffer end (1)\n",
357                                ((char *)startwrite + lencopy) -
358                                ((char *)outp + buf->length));
359                 remain = (char *)outp + buf->length - (char *)startwrite;
360                 lencopy = remain;
361         }
362         if (lencopy <= 0)
363                 return;
364         memcpy(startwrite, startread, lencopy);
365
366         remain -= lencopy;
367
368         while (remain > 0) {
369                 startwrite += lencopy + bytesperline;
370                 startread += lencopy;
371                 if (bytesperline > remain)
372                         lencopy = remain;
373                 else
374                         lencopy = bytesperline;
375
376                 if ((char *)startwrite + lencopy > (char *)outp +
377                     buf->length) {
378                         au0828_isocdbg("Overflow %zi bytes past buf end (2)\n",
379                                        ((char *)startwrite + lencopy) -
380                                        ((char *)outp + buf->length));
381                         lencopy = remain = (char *)outp + buf->length -
382                                            (char *)startwrite;
383                 }
384                 if (lencopy <= 0)
385                         break;
386
387                 memcpy(startwrite, startread, lencopy);
388
389                 remain -= lencopy;
390         }
391
392         if (offset > 1440) {
393                 /* We have enough data to check for greenscreen */
394                 if (outp[0] < 0x60 && outp[1440] < 0x60)
395                         dev->greenscreen_detected = 1;
396         }
397
398         dma_q->pos += len;
399 }
400
401 /*
402  * video-buf generic routine to get the next available buffer
403  */
404 static inline void get_next_buf(struct au0828_dmaqueue *dma_q,
405                                 struct au0828_buffer **buf)
406 {
407         struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
408
409         if (list_empty(&dma_q->active)) {
410                 au0828_isocdbg("No active queue to serve\n");
411                 dev->isoc_ctl.buf = NULL;
412                 *buf = NULL;
413                 return;
414         }
415
416         /* Get the next buffer */
417         *buf = list_entry(dma_q->active.next, struct au0828_buffer, list);
418         /* Cleans up buffer - Useful for testing for frame/URB loss */
419         list_del(&(*buf)->list);
420         dma_q->pos = 0;
421         (*buf)->vb_buf = (*buf)->mem;
422         dev->isoc_ctl.buf = *buf;
423
424         return;
425 }
426
427 static void au0828_copy_vbi(struct au0828_dev *dev,
428                               struct au0828_dmaqueue  *dma_q,
429                               struct au0828_buffer *buf,
430                               unsigned char *p,
431                               unsigned char *outp, unsigned long len)
432 {
433         unsigned char *startwrite, *startread;
434         int bytesperline;
435         int i, j = 0;
436
437         if (dev == NULL) {
438                 au0828_isocdbg("dev is null\n");
439                 return;
440         }
441
442         if (dma_q == NULL) {
443                 au0828_isocdbg("dma_q is null\n");
444                 return;
445         }
446         if (buf == NULL)
447                 return;
448         if (p == NULL) {
449                 au0828_isocdbg("p is null\n");
450                 return;
451         }
452         if (outp == NULL) {
453                 au0828_isocdbg("outp is null\n");
454                 return;
455         }
456
457         bytesperline = dev->vbi_width;
458
459         if (dma_q->pos + len > buf->length)
460                 len = buf->length - dma_q->pos;
461
462         startread = p;
463         startwrite = outp + (dma_q->pos / 2);
464
465         /* Make sure the bottom field populates the second half of the frame */
466         if (buf->top_field == 0)
467                 startwrite += bytesperline * dev->vbi_height;
468
469         for (i = 0; i < len; i += 2)
470                 startwrite[j++] = startread[i+1];
471
472         dma_q->pos += len;
473 }
474
475
476 /*
477  * video-buf generic routine to get the next available VBI buffer
478  */
479 static inline void vbi_get_next_buf(struct au0828_dmaqueue *dma_q,
480                                     struct au0828_buffer **buf)
481 {
482         struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vbiq);
483
484         if (list_empty(&dma_q->active)) {
485                 au0828_isocdbg("No active queue to serve\n");
486                 dev->isoc_ctl.vbi_buf = NULL;
487                 *buf = NULL;
488                 return;
489         }
490
491         /* Get the next buffer */
492         *buf = list_entry(dma_q->active.next, struct au0828_buffer, list);
493         /* Cleans up buffer - Useful for testing for frame/URB loss */
494         list_del(&(*buf)->list);
495         dma_q->pos = 0;
496         (*buf)->vb_buf = (*buf)->mem;
497         dev->isoc_ctl.vbi_buf = *buf;
498         return;
499 }
500
501 /*
502  * Controls the isoc copy of each urb packet
503  */
504 static inline int au0828_isoc_copy(struct au0828_dev *dev, struct urb *urb)
505 {
506         struct au0828_buffer    *buf;
507         struct au0828_buffer    *vbi_buf;
508         struct au0828_dmaqueue  *dma_q = urb->context;
509         struct au0828_dmaqueue  *vbi_dma_q = &dev->vbiq;
510         unsigned char *outp = NULL;
511         unsigned char *vbioutp = NULL;
512         int i, len = 0, rc = 1;
513         unsigned char *p;
514         unsigned char fbyte;
515         unsigned int vbi_field_size;
516         unsigned int remain, lencopy;
517
518         if (!dev)
519                 return 0;
520
521         if (test_bit(DEV_DISCONNECTED, &dev->dev_state) ||
522             test_bit(DEV_MISCONFIGURED, &dev->dev_state))
523                 return 0;
524
525         if (urb->status < 0) {
526                 print_err_status(dev, -1, urb->status);
527                 if (urb->status == -ENOENT)
528                         return 0;
529         }
530
531         buf = dev->isoc_ctl.buf;
532         if (buf != NULL)
533                 outp = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
534
535         vbi_buf = dev->isoc_ctl.vbi_buf;
536         if (vbi_buf != NULL)
537                 vbioutp = vb2_plane_vaddr(&vbi_buf->vb.vb2_buf, 0);
538
539         for (i = 0; i < urb->number_of_packets; i++) {
540                 int status = urb->iso_frame_desc[i].status;
541
542                 if (status < 0) {
543                         print_err_status(dev, i, status);
544                         if (urb->iso_frame_desc[i].status != -EPROTO)
545                                 continue;
546                 }
547
548                 if (urb->iso_frame_desc[i].actual_length <= 0)
549                         continue;
550
551                 if (urb->iso_frame_desc[i].actual_length >
552                                                 dev->max_pkt_size) {
553                         au0828_isocdbg("packet bigger than packet size");
554                         continue;
555                 }
556
557                 p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
558                 fbyte = p[0];
559                 len = urb->iso_frame_desc[i].actual_length - 4;
560                 p += 4;
561
562                 if (fbyte & 0x80) {
563                         len -= 4;
564                         p += 4;
565                         au0828_isocdbg("Video frame %s\n",
566                                        (fbyte & 0x40) ? "odd" : "even");
567                         if (fbyte & 0x40) {
568                                 /* VBI */
569                                 if (vbi_buf != NULL)
570                                         buffer_filled(dev, vbi_dma_q, vbi_buf);
571                                 vbi_get_next_buf(vbi_dma_q, &vbi_buf);
572                                 if (vbi_buf == NULL)
573                                         vbioutp = NULL;
574                                 else
575                                         vbioutp = vb2_plane_vaddr(
576                                                 &vbi_buf->vb.vb2_buf, 0);
577
578                                 /* Video */
579                                 if (buf != NULL)
580                                         buffer_filled(dev, dma_q, buf);
581                                 get_next_buf(dma_q, &buf);
582                                 if (buf == NULL)
583                                         outp = NULL;
584                                 else
585                                         outp = vb2_plane_vaddr(
586                                                 &buf->vb.vb2_buf, 0);
587
588                                 /* As long as isoc traffic is arriving, keep
589                                    resetting the timer */
590                                 if (dev->vid_timeout_running)
591                                         mod_timer(&dev->vid_timeout,
592                                                   jiffies + (HZ / 10));
593                                 if (dev->vbi_timeout_running)
594                                         mod_timer(&dev->vbi_timeout,
595                                                   jiffies + (HZ / 10));
596                         }
597
598                         if (buf != NULL) {
599                                 if (fbyte & 0x40)
600                                         buf->top_field = 1;
601                                 else
602                                         buf->top_field = 0;
603                         }
604
605                         if (vbi_buf != NULL) {
606                                 if (fbyte & 0x40)
607                                         vbi_buf->top_field = 1;
608                                 else
609                                         vbi_buf->top_field = 0;
610                         }
611
612                         dev->vbi_read = 0;
613                         vbi_dma_q->pos = 0;
614                         dma_q->pos = 0;
615                 }
616
617                 vbi_field_size = dev->vbi_width * dev->vbi_height * 2;
618                 if (dev->vbi_read < vbi_field_size) {
619                         remain  = vbi_field_size - dev->vbi_read;
620                         if (len < remain)
621                                 lencopy = len;
622                         else
623                                 lencopy = remain;
624
625                         if (vbi_buf != NULL)
626                                 au0828_copy_vbi(dev, vbi_dma_q, vbi_buf, p,
627                                                 vbioutp, len);
628
629                         len -= lencopy;
630                         p += lencopy;
631                         dev->vbi_read += lencopy;
632                 }
633
634                 if (dev->vbi_read >= vbi_field_size && buf != NULL)
635                         au0828_copy_video(dev, dma_q, buf, p, outp, len);
636         }
637         return rc;
638 }
639
640 static int queue_setup(struct vb2_queue *vq, const void *parg,
641                        unsigned int *nbuffers, unsigned int *nplanes,
642                        unsigned int sizes[], void *alloc_ctxs[])
643 {
644         const struct v4l2_format *fmt = parg;
645         struct au0828_dev *dev = vb2_get_drv_priv(vq);
646         unsigned long img_size = dev->height * dev->bytesperline;
647         unsigned long size;
648
649         size = fmt ? fmt->fmt.pix.sizeimage : img_size;
650         if (size < img_size)
651                 return -EINVAL;
652
653         *nplanes = 1;
654         sizes[0] = size;
655
656         return 0;
657 }
658
659 static int
660 buffer_prepare(struct vb2_buffer *vb)
661 {
662         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
663         struct au0828_buffer *buf = container_of(vbuf,
664                                 struct au0828_buffer, vb);
665         struct au0828_dev    *dev = vb2_get_drv_priv(vb->vb2_queue);
666
667         buf->length = dev->height * dev->bytesperline;
668
669         if (vb2_plane_size(vb, 0) < buf->length) {
670                 pr_err("%s data will not fit into plane (%lu < %lu)\n",
671                         __func__, vb2_plane_size(vb, 0), buf->length);
672                 return -EINVAL;
673         }
674         vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->length);
675         return 0;
676 }
677
678 static void
679 buffer_queue(struct vb2_buffer *vb)
680 {
681         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
682         struct au0828_buffer    *buf     = container_of(vbuf,
683                                                         struct au0828_buffer,
684                                                         vb);
685         struct au0828_dev       *dev     = vb2_get_drv_priv(vb->vb2_queue);
686         struct au0828_dmaqueue  *vidq    = &dev->vidq;
687         unsigned long flags = 0;
688
689         buf->mem = vb2_plane_vaddr(vb, 0);
690         buf->length = vb2_plane_size(vb, 0);
691
692         spin_lock_irqsave(&dev->slock, flags);
693         list_add_tail(&buf->list, &vidq->active);
694         spin_unlock_irqrestore(&dev->slock, flags);
695 }
696
697 static int au0828_i2s_init(struct au0828_dev *dev)
698 {
699         /* Enable i2s mode */
700         au0828_writereg(dev, AU0828_AUDIOCTRL_50C, 0x01);
701         return 0;
702 }
703
704 /*
705  * Auvitek au0828 analog stream enable
706  */
707 static int au0828_analog_stream_enable(struct au0828_dev *d)
708 {
709         struct usb_interface *iface;
710         int ret, h, w;
711
712         dprintk(1, "au0828_analog_stream_enable called\n");
713
714         if (test_bit(DEV_DISCONNECTED, &d->dev_state))
715                 return -ENODEV;
716
717         iface = usb_ifnum_to_if(d->usbdev, 0);
718         if (iface && iface->cur_altsetting->desc.bAlternateSetting != 5) {
719                 dprintk(1, "Changing intf#0 to alt 5\n");
720                 /* set au0828 interface0 to AS5 here again */
721                 ret = usb_set_interface(d->usbdev, 0, 5);
722                 if (ret < 0) {
723                         pr_info("Au0828 can't set alt setting to 5!\n");
724                         return -EBUSY;
725                 }
726         }
727
728         h = d->height / 2 + 2;
729         w = d->width * 2;
730
731         au0828_writereg(d, AU0828_SENSORCTRL_VBI_103, 0x00);
732         au0828_writereg(d, 0x106, 0x00);
733         /* set x position */
734         au0828_writereg(d, 0x110, 0x00);
735         au0828_writereg(d, 0x111, 0x00);
736         au0828_writereg(d, 0x114, w & 0xff);
737         au0828_writereg(d, 0x115, w >> 8);
738         /* set y position */
739         au0828_writereg(d, 0x112, 0x00);
740         au0828_writereg(d, 0x113, 0x00);
741         au0828_writereg(d, 0x116, h & 0xff);
742         au0828_writereg(d, 0x117, h >> 8);
743         au0828_writereg(d, AU0828_SENSORCTRL_100, 0xb3);
744
745         return 0;
746 }
747
748 static int au0828_analog_stream_disable(struct au0828_dev *d)
749 {
750         dprintk(1, "au0828_analog_stream_disable called\n");
751         au0828_writereg(d, AU0828_SENSORCTRL_100, 0x0);
752         return 0;
753 }
754
755 static void au0828_analog_stream_reset(struct au0828_dev *dev)
756 {
757         dprintk(1, "au0828_analog_stream_reset called\n");
758         au0828_writereg(dev, AU0828_SENSORCTRL_100, 0x0);
759         mdelay(30);
760         au0828_writereg(dev, AU0828_SENSORCTRL_100, 0xb3);
761 }
762
763 /*
764  * Some operations needs to stop current streaming
765  */
766 static int au0828_stream_interrupt(struct au0828_dev *dev)
767 {
768         int ret = 0;
769
770         dev->stream_state = STREAM_INTERRUPT;
771         if (test_bit(DEV_DISCONNECTED, &dev->dev_state))
772                 return -ENODEV;
773         else if (ret) {
774                 set_bit(DEV_MISCONFIGURED, &dev->dev_state);
775                 dprintk(1, "%s device is misconfigured!\n", __func__);
776                 return ret;
777         }
778         return 0;
779 }
780
781 int au0828_start_analog_streaming(struct vb2_queue *vq, unsigned int count)
782 {
783         struct au0828_dev *dev = vb2_get_drv_priv(vq);
784         int rc = 0;
785
786         dprintk(1, "au0828_start_analog_streaming called %d\n",
787                 dev->streaming_users);
788
789         if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
790                 dev->frame_count = 0;
791         else
792                 dev->vbi_frame_count = 0;
793
794         if (dev->streaming_users == 0) {
795                 /* If we were doing ac97 instead of i2s, it would go here...*/
796                 au0828_i2s_init(dev);
797                 rc = au0828_init_isoc(dev, AU0828_ISO_PACKETS_PER_URB,
798                                    AU0828_MAX_ISO_BUFS, dev->max_pkt_size,
799                                    au0828_isoc_copy);
800                 if (rc < 0) {
801                         pr_info("au0828_init_isoc failed\n");
802                         return rc;
803                 }
804
805                 v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 1);
806
807                 if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
808                         dev->vid_timeout_running = 1;
809                         mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
810                 } else if (vq->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
811                         dev->vbi_timeout_running = 1;
812                         mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
813                 }
814         }
815         dev->streaming_users++;
816         return rc;
817 }
818
819 static void au0828_stop_streaming(struct vb2_queue *vq)
820 {
821         struct au0828_dev *dev = vb2_get_drv_priv(vq);
822         struct au0828_dmaqueue *vidq = &dev->vidq;
823         unsigned long flags = 0;
824
825         dprintk(1, "au0828_stop_streaming called %d\n", dev->streaming_users);
826
827         if (dev->streaming_users-- == 1) {
828                 au0828_uninit_isoc(dev);
829                 v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
830         }
831
832         dev->vid_timeout_running = 0;
833         del_timer_sync(&dev->vid_timeout);
834
835         spin_lock_irqsave(&dev->slock, flags);
836         if (dev->isoc_ctl.buf != NULL) {
837                 vb2_buffer_done(&dev->isoc_ctl.buf->vb.vb2_buf,
838                                 VB2_BUF_STATE_ERROR);
839                 dev->isoc_ctl.buf = NULL;
840         }
841         while (!list_empty(&vidq->active)) {
842                 struct au0828_buffer *buf;
843
844                 buf = list_entry(vidq->active.next, struct au0828_buffer, list);
845                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
846                 list_del(&buf->list);
847         }
848         spin_unlock_irqrestore(&dev->slock, flags);
849 }
850
851 void au0828_stop_vbi_streaming(struct vb2_queue *vq)
852 {
853         struct au0828_dev *dev = vb2_get_drv_priv(vq);
854         struct au0828_dmaqueue *vbiq = &dev->vbiq;
855         unsigned long flags = 0;
856
857         dprintk(1, "au0828_stop_vbi_streaming called %d\n",
858                 dev->streaming_users);
859
860         if (dev->streaming_users-- == 1) {
861                 au0828_uninit_isoc(dev);
862                 v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
863         }
864
865         spin_lock_irqsave(&dev->slock, flags);
866         if (dev->isoc_ctl.vbi_buf != NULL) {
867                 vb2_buffer_done(&dev->isoc_ctl.vbi_buf->vb.vb2_buf,
868                                 VB2_BUF_STATE_ERROR);
869                 dev->isoc_ctl.vbi_buf = NULL;
870         }
871         while (!list_empty(&vbiq->active)) {
872                 struct au0828_buffer *buf;
873
874                 buf = list_entry(vbiq->active.next, struct au0828_buffer, list);
875                 list_del(&buf->list);
876                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
877         }
878         spin_unlock_irqrestore(&dev->slock, flags);
879
880         dev->vbi_timeout_running = 0;
881         del_timer_sync(&dev->vbi_timeout);
882 }
883
884 static struct vb2_ops au0828_video_qops = {
885         .queue_setup     = queue_setup,
886         .buf_prepare     = buffer_prepare,
887         .buf_queue       = buffer_queue,
888         .start_streaming = au0828_start_analog_streaming,
889         .stop_streaming  = au0828_stop_streaming,
890         .wait_prepare    = vb2_ops_wait_prepare,
891         .wait_finish     = vb2_ops_wait_finish,
892 };
893
894 /* ------------------------------------------------------------------
895    V4L2 interface
896    ------------------------------------------------------------------*/
897 /*
898  * au0828_analog_unregister
899  * unregister v4l2 devices
900  */
901 void au0828_analog_unregister(struct au0828_dev *dev)
902 {
903         dprintk(1, "au0828_analog_unregister called\n");
904         mutex_lock(&au0828_sysfs_lock);
905         video_unregister_device(&dev->vdev);
906         video_unregister_device(&dev->vbi_dev);
907         mutex_unlock(&au0828_sysfs_lock);
908 }
909
910 /* This function ensures that video frames continue to be delivered even if
911    the ITU-656 input isn't receiving any data (thereby preventing applications
912    such as tvtime from hanging) */
913 static void au0828_vid_buffer_timeout(unsigned long data)
914 {
915         struct au0828_dev *dev = (struct au0828_dev *) data;
916         struct au0828_dmaqueue *dma_q = &dev->vidq;
917         struct au0828_buffer *buf;
918         unsigned char *vid_data;
919         unsigned long flags = 0;
920
921         spin_lock_irqsave(&dev->slock, flags);
922
923         buf = dev->isoc_ctl.buf;
924         if (buf != NULL) {
925                 vid_data = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
926                 memset(vid_data, 0x00, buf->length); /* Blank green frame */
927                 buffer_filled(dev, dma_q, buf);
928         }
929         get_next_buf(dma_q, &buf);
930
931         if (dev->vid_timeout_running == 1)
932                 mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
933
934         spin_unlock_irqrestore(&dev->slock, flags);
935 }
936
937 static void au0828_vbi_buffer_timeout(unsigned long data)
938 {
939         struct au0828_dev *dev = (struct au0828_dev *) data;
940         struct au0828_dmaqueue *dma_q = &dev->vbiq;
941         struct au0828_buffer *buf;
942         unsigned char *vbi_data;
943         unsigned long flags = 0;
944
945         spin_lock_irqsave(&dev->slock, flags);
946
947         buf = dev->isoc_ctl.vbi_buf;
948         if (buf != NULL) {
949                 vbi_data = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
950                 memset(vbi_data, 0x00, buf->length);
951                 buffer_filled(dev, dma_q, buf);
952         }
953         vbi_get_next_buf(dma_q, &buf);
954
955         if (dev->vbi_timeout_running == 1)
956                 mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
957         spin_unlock_irqrestore(&dev->slock, flags);
958 }
959
960 static int au0828_v4l2_open(struct file *filp)
961 {
962         struct au0828_dev *dev = video_drvdata(filp);
963         int ret;
964
965         dprintk(1,
966                 "%s called std_set %d dev_state %ld stream users %d users %d\n",
967                 __func__, dev->std_set_in_tuner_core, dev->dev_state,
968                 dev->streaming_users, dev->users);
969
970         if (mutex_lock_interruptible(&dev->lock))
971                 return -ERESTARTSYS;
972
973         ret = v4l2_fh_open(filp);
974         if (ret) {
975                 au0828_isocdbg("%s: v4l2_fh_open() returned error %d\n",
976                                 __func__, ret);
977                 mutex_unlock(&dev->lock);
978                 return ret;
979         }
980
981         if (dev->users == 0) {
982                 au0828_analog_stream_enable(dev);
983                 au0828_analog_stream_reset(dev);
984                 dev->stream_state = STREAM_OFF;
985                 set_bit(DEV_INITIALIZED, &dev->dev_state);
986         }
987         dev->users++;
988         mutex_unlock(&dev->lock);
989         return ret;
990 }
991
992 static int au0828_v4l2_close(struct file *filp)
993 {
994         int ret;
995         struct au0828_dev *dev = video_drvdata(filp);
996         struct video_device *vdev = video_devdata(filp);
997
998         dprintk(1,
999                 "%s called std_set %d dev_state %ld stream users %d users %d\n",
1000                 __func__, dev->std_set_in_tuner_core, dev->dev_state,
1001                 dev->streaming_users, dev->users);
1002
1003         mutex_lock(&dev->lock);
1004         if (vdev->vfl_type == VFL_TYPE_GRABBER && dev->vid_timeout_running) {
1005                 /* Cancel timeout thread in case they didn't call streamoff */
1006                 dev->vid_timeout_running = 0;
1007                 del_timer_sync(&dev->vid_timeout);
1008         } else if (vdev->vfl_type == VFL_TYPE_VBI &&
1009                         dev->vbi_timeout_running) {
1010                 /* Cancel timeout thread in case they didn't call streamoff */
1011                 dev->vbi_timeout_running = 0;
1012                 del_timer_sync(&dev->vbi_timeout);
1013         }
1014
1015         if (test_bit(DEV_DISCONNECTED, &dev->dev_state))
1016                 goto end;
1017
1018         if (dev->users == 1) {
1019                 /* Save some power by putting tuner to sleep */
1020                 v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_power, 0);
1021                 dev->std_set_in_tuner_core = 0;
1022
1023                 /* When close the device, set the usb intf0 into alt0 to free
1024                    USB bandwidth */
1025                 ret = usb_set_interface(dev->usbdev, 0, 0);
1026                 if (ret < 0)
1027                         pr_info("Au0828 can't set alternate to 0!\n");
1028         }
1029 end:
1030         _vb2_fop_release(filp, NULL);
1031         dev->users--;
1032         mutex_unlock(&dev->lock);
1033         return 0;
1034 }
1035
1036 /* Must be called with dev->lock held */
1037 static void au0828_init_tuner(struct au0828_dev *dev)
1038 {
1039         struct v4l2_frequency f = {
1040                 .frequency = dev->ctrl_freq,
1041                 .type = V4L2_TUNER_ANALOG_TV,
1042         };
1043
1044         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1045                 dev->std_set_in_tuner_core, dev->dev_state);
1046
1047         if (dev->std_set_in_tuner_core)
1048                 return;
1049         dev->std_set_in_tuner_core = 1;
1050         i2c_gate_ctrl(dev, 1);
1051         /* If we've never sent the standard in tuner core, do so now.
1052            We don't do this at device probe because we don't want to
1053            incur the cost of a firmware load */
1054         v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std, dev->std);
1055         v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, &f);
1056         i2c_gate_ctrl(dev, 0);
1057 }
1058
1059 static int au0828_set_format(struct au0828_dev *dev, unsigned int cmd,
1060                              struct v4l2_format *format)
1061 {
1062         int ret;
1063         int width = format->fmt.pix.width;
1064         int height = format->fmt.pix.height;
1065
1066         /* If they are demanding a format other than the one we support,
1067            bail out (tvtime asks for UYVY and then retries with YUYV) */
1068         if (format->fmt.pix.pixelformat != V4L2_PIX_FMT_UYVY)
1069                 return -EINVAL;
1070
1071         /* format->fmt.pix.width only support 720 and height 480 */
1072         if (width != 720)
1073                 width = 720;
1074         if (height != 480)
1075                 height = 480;
1076
1077         format->fmt.pix.width = width;
1078         format->fmt.pix.height = height;
1079         format->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1080         format->fmt.pix.bytesperline = width * 2;
1081         format->fmt.pix.sizeimage = width * height * 2;
1082         format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1083         format->fmt.pix.field = V4L2_FIELD_INTERLACED;
1084         format->fmt.pix.priv = 0;
1085
1086         if (cmd == VIDIOC_TRY_FMT)
1087                 return 0;
1088
1089         /* maybe set new image format, driver current only support 720*480 */
1090         dev->width = width;
1091         dev->height = height;
1092         dev->frame_size = width * height * 2;
1093         dev->field_size = width * height;
1094         dev->bytesperline = width * 2;
1095
1096         if (dev->stream_state == STREAM_ON) {
1097                 dprintk(1, "VIDIOC_SET_FMT: interrupting stream!\n");
1098                 ret = au0828_stream_interrupt(dev);
1099                 if (ret != 0) {
1100                         dprintk(1, "error interrupting video stream!\n");
1101                         return ret;
1102                 }
1103         }
1104
1105         au0828_analog_stream_enable(dev);
1106
1107         return 0;
1108 }
1109
1110 static int vidioc_querycap(struct file *file, void  *priv,
1111                            struct v4l2_capability *cap)
1112 {
1113         struct video_device *vdev = video_devdata(file);
1114         struct au0828_dev *dev = video_drvdata(file);
1115
1116         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1117                 dev->std_set_in_tuner_core, dev->dev_state);
1118
1119         strlcpy(cap->driver, "au0828", sizeof(cap->driver));
1120         strlcpy(cap->card, dev->board.name, sizeof(cap->card));
1121         usb_make_path(dev->usbdev, cap->bus_info, sizeof(cap->bus_info));
1122
1123         /* set the device capabilities */
1124         cap->device_caps = V4L2_CAP_AUDIO |
1125                 V4L2_CAP_READWRITE |
1126                 V4L2_CAP_STREAMING |
1127                 V4L2_CAP_TUNER;
1128         if (vdev->vfl_type == VFL_TYPE_GRABBER)
1129                 cap->device_caps |= V4L2_CAP_VIDEO_CAPTURE;
1130         else
1131                 cap->device_caps |= V4L2_CAP_VBI_CAPTURE;
1132         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS |
1133                 V4L2_CAP_VBI_CAPTURE | V4L2_CAP_VIDEO_CAPTURE;
1134         return 0;
1135 }
1136
1137 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1138                                         struct v4l2_fmtdesc *f)
1139 {
1140         if (f->index)
1141                 return -EINVAL;
1142
1143         dprintk(1, "%s called\n", __func__);
1144
1145         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1146         strcpy(f->description, "Packed YUV2");
1147
1148         f->flags = 0;
1149         f->pixelformat = V4L2_PIX_FMT_UYVY;
1150
1151         return 0;
1152 }
1153
1154 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1155                                         struct v4l2_format *f)
1156 {
1157         struct au0828_dev *dev = video_drvdata(file);
1158
1159         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1160                 dev->std_set_in_tuner_core, dev->dev_state);
1161
1162         f->fmt.pix.width = dev->width;
1163         f->fmt.pix.height = dev->height;
1164         f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1165         f->fmt.pix.bytesperline = dev->bytesperline;
1166         f->fmt.pix.sizeimage = dev->frame_size;
1167         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; /* NTSC/PAL */
1168         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1169         f->fmt.pix.priv = 0;
1170         return 0;
1171 }
1172
1173 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1174                                   struct v4l2_format *f)
1175 {
1176         struct au0828_dev *dev = video_drvdata(file);
1177
1178         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1179                 dev->std_set_in_tuner_core, dev->dev_state);
1180
1181         return au0828_set_format(dev, VIDIOC_TRY_FMT, f);
1182 }
1183
1184 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1185                                 struct v4l2_format *f)
1186 {
1187         struct au0828_dev *dev = video_drvdata(file);
1188         int rc;
1189
1190         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1191                 dev->std_set_in_tuner_core, dev->dev_state);
1192
1193         rc = check_dev(dev);
1194         if (rc < 0)
1195                 return rc;
1196
1197         if (vb2_is_busy(&dev->vb_vidq)) {
1198                 pr_info("%s queue busy\n", __func__);
1199                 rc = -EBUSY;
1200                 goto out;
1201         }
1202
1203         rc = au0828_set_format(dev, VIDIOC_S_FMT, f);
1204 out:
1205         return rc;
1206 }
1207
1208 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1209 {
1210         struct au0828_dev *dev = video_drvdata(file);
1211
1212         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1213                 dev->std_set_in_tuner_core, dev->dev_state);
1214
1215         if (norm == dev->std)
1216                 return 0;
1217
1218         if (dev->streaming_users > 0)
1219                 return -EBUSY;
1220
1221         dev->std = norm;
1222
1223         au0828_init_tuner(dev);
1224
1225         i2c_gate_ctrl(dev, 1);
1226
1227         /*
1228          * FIXME: when we support something other than 60Hz standards,
1229          * we are going to have to make the au0828 bridge adjust the size
1230          * of its capture buffer, which is currently hardcoded at 720x480
1231          */
1232
1233         v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std, norm);
1234
1235         i2c_gate_ctrl(dev, 0);
1236
1237         return 0;
1238 }
1239
1240 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
1241 {
1242         struct au0828_dev *dev = video_drvdata(file);
1243
1244         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1245                 dev->std_set_in_tuner_core, dev->dev_state);
1246
1247         *norm = dev->std;
1248         return 0;
1249 }
1250
1251 static int vidioc_enum_input(struct file *file, void *priv,
1252                                 struct v4l2_input *input)
1253 {
1254         struct au0828_dev *dev = video_drvdata(file);
1255         unsigned int tmp;
1256
1257         static const char *inames[] = {
1258                 [AU0828_VMUX_UNDEFINED] = "Undefined",
1259                 [AU0828_VMUX_COMPOSITE] = "Composite",
1260                 [AU0828_VMUX_SVIDEO] = "S-Video",
1261                 [AU0828_VMUX_CABLE] = "Cable TV",
1262                 [AU0828_VMUX_TELEVISION] = "Television",
1263                 [AU0828_VMUX_DVB] = "DVB",
1264                 [AU0828_VMUX_DEBUG] = "tv debug"
1265         };
1266
1267         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1268                 dev->std_set_in_tuner_core, dev->dev_state);
1269
1270         tmp = input->index;
1271
1272         if (tmp >= AU0828_MAX_INPUT)
1273                 return -EINVAL;
1274         if (AUVI_INPUT(tmp).type == 0)
1275                 return -EINVAL;
1276
1277         input->index = tmp;
1278         strcpy(input->name, inames[AUVI_INPUT(tmp).type]);
1279         if ((AUVI_INPUT(tmp).type == AU0828_VMUX_TELEVISION) ||
1280             (AUVI_INPUT(tmp).type == AU0828_VMUX_CABLE)) {
1281                 input->type |= V4L2_INPUT_TYPE_TUNER;
1282                 input->audioset = 1;
1283         } else {
1284                 input->type |= V4L2_INPUT_TYPE_CAMERA;
1285                 input->audioset = 2;
1286         }
1287
1288         input->std = dev->vdev.tvnorms;
1289
1290         return 0;
1291 }
1292
1293 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1294 {
1295         struct au0828_dev *dev = video_drvdata(file);
1296
1297         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1298                 dev->std_set_in_tuner_core, dev->dev_state);
1299
1300         *i = dev->ctrl_input;
1301         return 0;
1302 }
1303
1304 static void au0828_s_input(struct au0828_dev *dev, int index)
1305 {
1306         int i;
1307
1308         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1309                 dev->std_set_in_tuner_core, dev->dev_state);
1310
1311         switch (AUVI_INPUT(index).type) {
1312         case AU0828_VMUX_SVIDEO:
1313                 dev->input_type = AU0828_VMUX_SVIDEO;
1314                 dev->ctrl_ainput = 1;
1315                 break;
1316         case AU0828_VMUX_COMPOSITE:
1317                 dev->input_type = AU0828_VMUX_COMPOSITE;
1318                 dev->ctrl_ainput = 1;
1319                 break;
1320         case AU0828_VMUX_TELEVISION:
1321                 dev->input_type = AU0828_VMUX_TELEVISION;
1322                 dev->ctrl_ainput = 0;
1323                 break;
1324         default:
1325                 dprintk(1, "unknown input type set [%d]\n",
1326                         AUVI_INPUT(index).type);
1327                 break;
1328         }
1329
1330         v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_routing,
1331                         AUVI_INPUT(index).vmux, 0, 0);
1332
1333         for (i = 0; i < AU0828_MAX_INPUT; i++) {
1334                 int enable = 0;
1335                 if (AUVI_INPUT(i).audio_setup == NULL)
1336                         continue;
1337
1338                 if (i == index)
1339                         enable = 1;
1340                 else
1341                         enable = 0;
1342                 if (enable) {
1343                         (AUVI_INPUT(i).audio_setup)(dev, enable);
1344                 } else {
1345                         /* Make sure we leave it turned on if some
1346                            other input is routed to this callback */
1347                         if ((AUVI_INPUT(i).audio_setup) !=
1348                             ((AUVI_INPUT(index).audio_setup))) {
1349                                 (AUVI_INPUT(i).audio_setup)(dev, enable);
1350                         }
1351                 }
1352         }
1353
1354         v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
1355                         AUVI_INPUT(index).amux, 0, 0);
1356 }
1357
1358 static int vidioc_s_input(struct file *file, void *priv, unsigned int index)
1359 {
1360         struct au0828_dev *dev = video_drvdata(file);
1361
1362         dprintk(1, "VIDIOC_S_INPUT in function %s, input=%d\n", __func__,
1363                 index);
1364         if (index >= AU0828_MAX_INPUT)
1365                 return -EINVAL;
1366         if (AUVI_INPUT(index).type == 0)
1367                 return -EINVAL;
1368         dev->ctrl_input = index;
1369         au0828_s_input(dev, index);
1370         return 0;
1371 }
1372
1373 static int vidioc_enumaudio(struct file *file, void *priv, struct v4l2_audio *a)
1374 {
1375         if (a->index > 1)
1376                 return -EINVAL;
1377
1378         dprintk(1, "%s called\n", __func__);
1379
1380         if (a->index == 0)
1381                 strcpy(a->name, "Television");
1382         else
1383                 strcpy(a->name, "Line in");
1384
1385         a->capability = V4L2_AUDCAP_STEREO;
1386         return 0;
1387 }
1388
1389 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1390 {
1391         struct au0828_dev *dev = video_drvdata(file);
1392
1393         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1394                 dev->std_set_in_tuner_core, dev->dev_state);
1395
1396         a->index = dev->ctrl_ainput;
1397         if (a->index == 0)
1398                 strcpy(a->name, "Television");
1399         else
1400                 strcpy(a->name, "Line in");
1401
1402         a->capability = V4L2_AUDCAP_STEREO;
1403         return 0;
1404 }
1405
1406 static int vidioc_s_audio(struct file *file, void *priv, const struct v4l2_audio *a)
1407 {
1408         struct au0828_dev *dev = video_drvdata(file);
1409
1410         if (a->index != dev->ctrl_ainput)
1411                 return -EINVAL;
1412
1413         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1414                 dev->std_set_in_tuner_core, dev->dev_state);
1415         return 0;
1416 }
1417
1418 static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1419 {
1420         struct au0828_dev *dev = video_drvdata(file);
1421
1422         if (t->index != 0)
1423                 return -EINVAL;
1424
1425         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1426                 dev->std_set_in_tuner_core, dev->dev_state);
1427
1428         strcpy(t->name, "Auvitek tuner");
1429
1430         au0828_init_tuner(dev);
1431         i2c_gate_ctrl(dev, 1);
1432         v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
1433         i2c_gate_ctrl(dev, 0);
1434         return 0;
1435 }
1436
1437 static int vidioc_s_tuner(struct file *file, void *priv,
1438                                 const struct v4l2_tuner *t)
1439 {
1440         struct au0828_dev *dev = video_drvdata(file);
1441
1442         if (t->index != 0)
1443                 return -EINVAL;
1444
1445         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1446                 dev->std_set_in_tuner_core, dev->dev_state);
1447
1448         au0828_init_tuner(dev);
1449         i2c_gate_ctrl(dev, 1);
1450         v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
1451         i2c_gate_ctrl(dev, 0);
1452
1453         dprintk(1, "VIDIOC_S_TUNER: signal = %x, afc = %x\n", t->signal,
1454                 t->afc);
1455
1456         return 0;
1457
1458 }
1459
1460 static int vidioc_g_frequency(struct file *file, void *priv,
1461                                 struct v4l2_frequency *freq)
1462 {
1463         struct au0828_dev *dev = video_drvdata(file);
1464
1465         if (freq->tuner != 0)
1466                 return -EINVAL;
1467         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1468                 dev->std_set_in_tuner_core, dev->dev_state);
1469         freq->frequency = dev->ctrl_freq;
1470         return 0;
1471 }
1472
1473 static int vidioc_s_frequency(struct file *file, void *priv,
1474                                 const struct v4l2_frequency *freq)
1475 {
1476         struct au0828_dev *dev = video_drvdata(file);
1477         struct v4l2_frequency new_freq = *freq;
1478
1479         if (freq->tuner != 0)
1480                 return -EINVAL;
1481
1482         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1483                 dev->std_set_in_tuner_core, dev->dev_state);
1484
1485         au0828_init_tuner(dev);
1486         i2c_gate_ctrl(dev, 1);
1487
1488         v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, freq);
1489         /* Get the actual set (and possibly clamped) frequency */
1490         v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_frequency, &new_freq);
1491         dev->ctrl_freq = new_freq.frequency;
1492
1493         i2c_gate_ctrl(dev, 0);
1494
1495         au0828_analog_stream_reset(dev);
1496
1497         return 0;
1498 }
1499
1500
1501 /* RAW VBI ioctls */
1502
1503 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1504                                 struct v4l2_format *format)
1505 {
1506         struct au0828_dev *dev = video_drvdata(file);
1507
1508         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1509                 dev->std_set_in_tuner_core, dev->dev_state);
1510
1511         format->fmt.vbi.samples_per_line = dev->vbi_width;
1512         format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1513         format->fmt.vbi.offset = 0;
1514         format->fmt.vbi.flags = 0;
1515         format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1516
1517         format->fmt.vbi.count[0] = dev->vbi_height;
1518         format->fmt.vbi.count[1] = dev->vbi_height;
1519         format->fmt.vbi.start[0] = 21;
1520         format->fmt.vbi.start[1] = 284;
1521         memset(format->fmt.vbi.reserved, 0, sizeof(format->fmt.vbi.reserved));
1522
1523         return 0;
1524 }
1525
1526 static int vidioc_cropcap(struct file *file, void *priv,
1527                           struct v4l2_cropcap *cc)
1528 {
1529         struct au0828_dev *dev = video_drvdata(file);
1530
1531         if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1532                 return -EINVAL;
1533
1534         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1535                 dev->std_set_in_tuner_core, dev->dev_state);
1536
1537         cc->bounds.left = 0;
1538         cc->bounds.top = 0;
1539         cc->bounds.width = dev->width;
1540         cc->bounds.height = dev->height;
1541
1542         cc->defrect = cc->bounds;
1543
1544         cc->pixelaspect.numerator = 54;
1545         cc->pixelaspect.denominator = 59;
1546
1547         return 0;
1548 }
1549
1550 #ifdef CONFIG_VIDEO_ADV_DEBUG
1551 static int vidioc_g_register(struct file *file, void *priv,
1552                              struct v4l2_dbg_register *reg)
1553 {
1554         struct au0828_dev *dev = video_drvdata(file);
1555
1556         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1557                 dev->std_set_in_tuner_core, dev->dev_state);
1558
1559         reg->val = au0828_read(dev, reg->reg);
1560         reg->size = 1;
1561         return 0;
1562 }
1563
1564 static int vidioc_s_register(struct file *file, void *priv,
1565                              const struct v4l2_dbg_register *reg)
1566 {
1567         struct au0828_dev *dev = video_drvdata(file);
1568
1569         dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1570                 dev->std_set_in_tuner_core, dev->dev_state);
1571
1572         return au0828_writereg(dev, reg->reg, reg->val);
1573 }
1574 #endif
1575
1576 static int vidioc_log_status(struct file *file, void *fh)
1577 {
1578         struct video_device *vdev = video_devdata(file);
1579
1580         dprintk(1, "%s called\n", __func__);
1581
1582         v4l2_ctrl_log_status(file, fh);
1583         v4l2_device_call_all(vdev->v4l2_dev, 0, core, log_status);
1584         return 0;
1585 }
1586
1587 void au0828_v4l2_suspend(struct au0828_dev *dev)
1588 {
1589         struct urb *urb;
1590         int i;
1591
1592         pr_info("stopping V4L2\n");
1593
1594         if (dev->stream_state == STREAM_ON) {
1595                 pr_info("stopping V4L2 active URBs\n");
1596                 au0828_analog_stream_disable(dev);
1597                 /* stop urbs */
1598                 for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
1599                         urb = dev->isoc_ctl.urb[i];
1600                         if (urb) {
1601                                 if (!irqs_disabled())
1602                                         usb_kill_urb(urb);
1603                                 else
1604                                         usb_unlink_urb(urb);
1605                         }
1606                 }
1607         }
1608
1609         if (dev->vid_timeout_running)
1610                 del_timer_sync(&dev->vid_timeout);
1611         if (dev->vbi_timeout_running)
1612                 del_timer_sync(&dev->vbi_timeout);
1613 }
1614
1615 void au0828_v4l2_resume(struct au0828_dev *dev)
1616 {
1617         int i, rc;
1618
1619         pr_info("restarting V4L2\n");
1620
1621         if (dev->stream_state == STREAM_ON) {
1622                 au0828_stream_interrupt(dev);
1623                 au0828_init_tuner(dev);
1624         }
1625
1626         if (dev->vid_timeout_running)
1627                 mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
1628         if (dev->vbi_timeout_running)
1629                 mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
1630
1631         /* If we were doing ac97 instead of i2s, it would go here...*/
1632         au0828_i2s_init(dev);
1633
1634         au0828_analog_stream_enable(dev);
1635
1636         if (!(dev->stream_state == STREAM_ON)) {
1637                 au0828_analog_stream_reset(dev);
1638                 /* submit urbs */
1639                 for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
1640                         rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
1641                         if (rc) {
1642                                 au0828_isocdbg("submit of urb %i failed (error=%i)\n",
1643                                                i, rc);
1644                                 au0828_uninit_isoc(dev);
1645                         }
1646                 }
1647         }
1648 }
1649
1650 static struct v4l2_file_operations au0828_v4l_fops = {
1651         .owner      = THIS_MODULE,
1652         .open       = au0828_v4l2_open,
1653         .release    = au0828_v4l2_close,
1654         .read       = vb2_fop_read,
1655         .poll       = vb2_fop_poll,
1656         .mmap       = vb2_fop_mmap,
1657         .unlocked_ioctl = video_ioctl2,
1658 };
1659
1660 static const struct v4l2_ioctl_ops video_ioctl_ops = {
1661         .vidioc_querycap            = vidioc_querycap,
1662         .vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
1663         .vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
1664         .vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
1665         .vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
1666         .vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
1667         .vidioc_try_fmt_vbi_cap     = vidioc_g_fmt_vbi_cap,
1668         .vidioc_s_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
1669         .vidioc_enumaudio           = vidioc_enumaudio,
1670         .vidioc_g_audio             = vidioc_g_audio,
1671         .vidioc_s_audio             = vidioc_s_audio,
1672         .vidioc_cropcap             = vidioc_cropcap,
1673
1674         .vidioc_reqbufs             = vb2_ioctl_reqbufs,
1675         .vidioc_create_bufs         = vb2_ioctl_create_bufs,
1676         .vidioc_prepare_buf         = vb2_ioctl_prepare_buf,
1677         .vidioc_querybuf            = vb2_ioctl_querybuf,
1678         .vidioc_qbuf                = vb2_ioctl_qbuf,
1679         .vidioc_dqbuf               = vb2_ioctl_dqbuf,
1680         .vidioc_expbuf               = vb2_ioctl_expbuf,
1681
1682         .vidioc_s_std               = vidioc_s_std,
1683         .vidioc_g_std               = vidioc_g_std,
1684         .vidioc_enum_input          = vidioc_enum_input,
1685         .vidioc_g_input             = vidioc_g_input,
1686         .vidioc_s_input             = vidioc_s_input,
1687
1688         .vidioc_streamon            = vb2_ioctl_streamon,
1689         .vidioc_streamoff           = vb2_ioctl_streamoff,
1690
1691         .vidioc_g_tuner             = vidioc_g_tuner,
1692         .vidioc_s_tuner             = vidioc_s_tuner,
1693         .vidioc_g_frequency         = vidioc_g_frequency,
1694         .vidioc_s_frequency         = vidioc_s_frequency,
1695 #ifdef CONFIG_VIDEO_ADV_DEBUG
1696         .vidioc_g_register          = vidioc_g_register,
1697         .vidioc_s_register          = vidioc_s_register,
1698 #endif
1699         .vidioc_log_status          = vidioc_log_status,
1700         .vidioc_subscribe_event     = v4l2_ctrl_subscribe_event,
1701         .vidioc_unsubscribe_event   = v4l2_event_unsubscribe,
1702 };
1703
1704 static const struct video_device au0828_video_template = {
1705         .fops                       = &au0828_v4l_fops,
1706         .release                    = video_device_release_empty,
1707         .ioctl_ops                  = &video_ioctl_ops,
1708         .tvnorms                    = V4L2_STD_NTSC_M | V4L2_STD_PAL_M,
1709 };
1710
1711 static int au0828_vb2_setup(struct au0828_dev *dev)
1712 {
1713         int rc;
1714         struct vb2_queue *q;
1715
1716         /* Setup Videobuf2 for Video capture */
1717         q = &dev->vb_vidq;
1718         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1719         q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1720         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1721         q->drv_priv = dev;
1722         q->buf_struct_size = sizeof(struct au0828_buffer);
1723         q->ops = &au0828_video_qops;
1724         q->mem_ops = &vb2_vmalloc_memops;
1725
1726         rc = vb2_queue_init(q);
1727         if (rc < 0)
1728                 return rc;
1729
1730         /* Setup Videobuf2 for VBI capture */
1731         q = &dev->vb_vbiq;
1732         q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1733         q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1734         q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1735         q->drv_priv = dev;
1736         q->buf_struct_size = sizeof(struct au0828_buffer);
1737         q->ops = &au0828_vbi_qops;
1738         q->mem_ops = &vb2_vmalloc_memops;
1739
1740         rc = vb2_queue_init(q);
1741         if (rc < 0)
1742                 return rc;
1743
1744         return 0;
1745 }
1746
1747 /**************************************************************************/
1748
1749 int au0828_analog_register(struct au0828_dev *dev,
1750                            struct usb_interface *interface)
1751 {
1752         int retval = -ENOMEM;
1753         struct usb_host_interface *iface_desc;
1754         struct usb_endpoint_descriptor *endpoint;
1755         int i, ret;
1756
1757         dprintk(1, "au0828_analog_register called for intf#%d!\n",
1758                 interface->cur_altsetting->desc.bInterfaceNumber);
1759
1760         /* set au0828 usb interface0 to as5 */
1761         retval = usb_set_interface(dev->usbdev,
1762                         interface->cur_altsetting->desc.bInterfaceNumber, 5);
1763         if (retval != 0) {
1764                 pr_info("Failure setting usb interface0 to as5\n");
1765                 return retval;
1766         }
1767
1768         /* Figure out which endpoint has the isoc interface */
1769         iface_desc = interface->cur_altsetting;
1770         for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
1771                 endpoint = &iface_desc->endpoint[i].desc;
1772                 if (((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
1773                      == USB_DIR_IN) &&
1774                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1775                      == USB_ENDPOINT_XFER_ISOC)) {
1776
1777                         /* we find our isoc in endpoint */
1778                         u16 tmp = le16_to_cpu(endpoint->wMaxPacketSize);
1779                         dev->max_pkt_size = (tmp & 0x07ff) *
1780                                 (((tmp & 0x1800) >> 11) + 1);
1781                         dev->isoc_in_endpointaddr = endpoint->bEndpointAddress;
1782                         dprintk(1,
1783                                 "Found isoc endpoint 0x%02x, max size = %d\n",
1784                                 dev->isoc_in_endpointaddr, dev->max_pkt_size);
1785                 }
1786         }
1787         if (!(dev->isoc_in_endpointaddr)) {
1788                 pr_info("Could not locate isoc endpoint\n");
1789                 return -ENODEV;
1790         }
1791
1792         init_waitqueue_head(&dev->open);
1793         spin_lock_init(&dev->slock);
1794
1795         /* init video dma queues */
1796         INIT_LIST_HEAD(&dev->vidq.active);
1797         INIT_LIST_HEAD(&dev->vbiq.active);
1798
1799         setup_timer(&dev->vid_timeout, au0828_vid_buffer_timeout,
1800                     (unsigned long)dev);
1801         setup_timer(&dev->vbi_timeout, au0828_vbi_buffer_timeout,
1802                     (unsigned long)dev);
1803
1804         dev->width = NTSC_STD_W;
1805         dev->height = NTSC_STD_H;
1806         dev->field_size = dev->width * dev->height;
1807         dev->frame_size = dev->field_size << 1;
1808         dev->bytesperline = dev->width << 1;
1809         dev->vbi_width = 720;
1810         dev->vbi_height = 1;
1811         dev->ctrl_ainput = 0;
1812         dev->ctrl_freq = 960;
1813         dev->std = V4L2_STD_NTSC_M;
1814         au0828_s_input(dev, 0);
1815
1816         mutex_init(&dev->vb_queue_lock);
1817         mutex_init(&dev->vb_vbi_queue_lock);
1818
1819         /* Fill the video capture device struct */
1820         dev->vdev = au0828_video_template;
1821         dev->vdev.v4l2_dev = &dev->v4l2_dev;
1822         dev->vdev.lock = &dev->lock;
1823         dev->vdev.queue = &dev->vb_vidq;
1824         dev->vdev.queue->lock = &dev->vb_queue_lock;
1825         strcpy(dev->vdev.name, "au0828a video");
1826
1827         /* Setup the VBI device */
1828         dev->vbi_dev = au0828_video_template;
1829         dev->vbi_dev.v4l2_dev = &dev->v4l2_dev;
1830         dev->vbi_dev.lock = &dev->lock;
1831         dev->vbi_dev.queue = &dev->vb_vbiq;
1832         dev->vbi_dev.queue->lock = &dev->vb_vbi_queue_lock;
1833         strcpy(dev->vbi_dev.name, "au0828a vbi");
1834
1835         /* initialize videobuf2 stuff */
1836         retval = au0828_vb2_setup(dev);
1837         if (retval != 0) {
1838                 dprintk(1, "unable to setup videobuf2 queues (error = %d).\n",
1839                         retval);
1840                 return -ENODEV;
1841         }
1842
1843         /* Register the v4l2 device */
1844         video_set_drvdata(&dev->vdev, dev);
1845         retval = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
1846         if (retval != 0) {
1847                 dprintk(1, "unable to register video device (error = %d).\n",
1848                         retval);
1849                 ret = -ENODEV;
1850                 goto err_reg_vdev;
1851         }
1852
1853         /* Register the vbi device */
1854         video_set_drvdata(&dev->vbi_dev, dev);
1855         retval = video_register_device(&dev->vbi_dev, VFL_TYPE_VBI, -1);
1856         if (retval != 0) {
1857                 dprintk(1, "unable to register vbi device (error = %d).\n",
1858                         retval);
1859                 ret = -ENODEV;
1860                 goto err_reg_vbi_dev;
1861         }
1862
1863         dprintk(1, "%s completed!\n", __func__);
1864
1865         return 0;
1866
1867 err_reg_vbi_dev:
1868         video_unregister_device(&dev->vdev);
1869 err_reg_vdev:
1870         vb2_queue_release(&dev->vb_vidq);
1871         vb2_queue_release(&dev->vb_vbiq);
1872         return ret;
1873 }
1874