xref: /linux/drivers/media/usb/au0828/au0828-video.c (revision 32786fdc9506aeba98278c1844d4bfb766863832)
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 #include "au8522.h"
32 
33 #include <linux/module.h>
34 #include <linux/slab.h>
35 #include <linux/init.h>
36 #include <linux/device.h>
37 #include <media/v4l2-common.h>
38 #include <media/v4l2-mc.h>
39 #include <media/v4l2-ioctl.h>
40 #include <media/v4l2-event.h>
41 #include <media/tuner.h>
42 #include "au0828-reg.h"
43 
44 static DEFINE_MUTEX(au0828_sysfs_lock);
45 
46 /* ------------------------------------------------------------------
47 	Videobuf operations
48    ------------------------------------------------------------------*/
49 
50 static unsigned int isoc_debug;
51 module_param(isoc_debug, int, 0644);
52 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
53 
54 #define au0828_isocdbg(fmt, arg...) \
55 do {\
56 	if (isoc_debug) { \
57 		pr_info("au0828 %s :"fmt, \
58 		       __func__ , ##arg);	   \
59 	} \
60   } while (0)
61 
62 static inline void i2c_gate_ctrl(struct au0828_dev *dev, int val)
63 {
64 	if (dev->dvb.frontend && dev->dvb.frontend->ops.analog_ops.i2c_gate_ctrl)
65 		dev->dvb.frontend->ops.analog_ops.i2c_gate_ctrl(dev->dvb.frontend, val);
66 }
67 
68 static inline void print_err_status(struct au0828_dev *dev,
69 				    int packet, int status)
70 {
71 	char *errmsg = "Unknown";
72 
73 	switch (status) {
74 	case -ENOENT:
75 		errmsg = "unlinked synchronuously";
76 		break;
77 	case -ECONNRESET:
78 		errmsg = "unlinked asynchronuously";
79 		break;
80 	case -ENOSR:
81 		errmsg = "Buffer error (overrun)";
82 		break;
83 	case -EPIPE:
84 		errmsg = "Stalled (device not responding)";
85 		break;
86 	case -EOVERFLOW:
87 		errmsg = "Babble (bad cable?)";
88 		break;
89 	case -EPROTO:
90 		errmsg = "Bit-stuff error (bad cable?)";
91 		break;
92 	case -EILSEQ:
93 		errmsg = "CRC/Timeout (could be anything)";
94 		break;
95 	case -ETIME:
96 		errmsg = "Device does not respond";
97 		break;
98 	}
99 	if (packet < 0) {
100 		au0828_isocdbg("URB status %d [%s].\n",	status, errmsg);
101 	} else {
102 		au0828_isocdbg("URB packet %d, status %d [%s].\n",
103 			       packet, status, errmsg);
104 	}
105 }
106 
107 static int check_dev(struct au0828_dev *dev)
108 {
109 	if (test_bit(DEV_DISCONNECTED, &dev->dev_state)) {
110 		pr_info("v4l2 ioctl: device not present\n");
111 		return -ENODEV;
112 	}
113 
114 	if (test_bit(DEV_MISCONFIGURED, &dev->dev_state)) {
115 		pr_info("v4l2 ioctl: device is misconfigured; close and open it again\n");
116 		return -EIO;
117 	}
118 	return 0;
119 }
120 
121 /*
122  * IRQ callback, called by URB callback
123  */
124 static void au0828_irq_callback(struct urb *urb)
125 {
126 	struct au0828_dmaqueue  *dma_q = urb->context;
127 	struct au0828_dev *dev = container_of(dma_q, struct au0828_dev, vidq);
128 	unsigned long flags = 0;
129 	int i;
130 
131 	switch (urb->status) {
132 	case 0:             /* success */
133 	case -ETIMEDOUT:    /* NAK */
134 		break;
135 	case -ECONNRESET:   /* kill */
136 	case -ENOENT:
137 	case -ESHUTDOWN:
138 		au0828_isocdbg("au0828_irq_callback called: status kill\n");
139 		return;
140 	default:            /* unknown error */
141 		au0828_isocdbg("urb completition error %d.\n", urb->status);
142 		break;
143 	}
144 
145 	/* Copy data from URB */
146 	spin_lock_irqsave(&dev->slock, flags);
147 	dev->isoc_ctl.isoc_copy(dev, urb);
148 	spin_unlock_irqrestore(&dev->slock, flags);
149 
150 	/* Reset urb buffers */
151 	for (i = 0; i < urb->number_of_packets; i++) {
152 		urb->iso_frame_desc[i].status = 0;
153 		urb->iso_frame_desc[i].actual_length = 0;
154 	}
155 	urb->status = 0;
156 
157 	urb->status = usb_submit_urb(urb, GFP_ATOMIC);
158 	if (urb->status) {
159 		au0828_isocdbg("urb resubmit failed (error=%i)\n",
160 			       urb->status);
161 	}
162 	dev->stream_state = STREAM_ON;
163 }
164 
165 /*
166  * Stop and Deallocate URBs
167  */
168 static void au0828_uninit_isoc(struct au0828_dev *dev)
169 {
170 	struct urb *urb;
171 	int i;
172 
173 	au0828_isocdbg("au0828: called au0828_uninit_isoc\n");
174 
175 	dev->isoc_ctl.nfields = -1;
176 	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
177 		urb = dev->isoc_ctl.urb[i];
178 		if (urb) {
179 			if (!irqs_disabled())
180 				usb_kill_urb(urb);
181 			else
182 				usb_unlink_urb(urb);
183 
184 			if (dev->isoc_ctl.transfer_buffer[i]) {
185 				usb_free_coherent(dev->usbdev,
186 					urb->transfer_buffer_length,
187 					dev->isoc_ctl.transfer_buffer[i],
188 					urb->transfer_dma);
189 			}
190 			usb_free_urb(urb);
191 			dev->isoc_ctl.urb[i] = NULL;
192 		}
193 		dev->isoc_ctl.transfer_buffer[i] = NULL;
194 	}
195 
196 	kfree(dev->isoc_ctl.urb);
197 	kfree(dev->isoc_ctl.transfer_buffer);
198 
199 	dev->isoc_ctl.urb = NULL;
200 	dev->isoc_ctl.transfer_buffer = NULL;
201 	dev->isoc_ctl.num_bufs = 0;
202 
203 	dev->stream_state = STREAM_OFF;
204 }
205 
206 /*
207  * Allocate URBs and start IRQ
208  */
209 static int au0828_init_isoc(struct au0828_dev *dev, int max_packets,
210 			    int num_bufs, int max_pkt_size,
211 			    int (*isoc_copy) (struct au0828_dev *dev, struct urb *urb))
212 {
213 	struct au0828_dmaqueue *dma_q = &dev->vidq;
214 	int i;
215 	int sb_size, pipe;
216 	struct urb *urb;
217 	int j, k;
218 	int rc;
219 
220 	au0828_isocdbg("au0828: called au0828_prepare_isoc\n");
221 
222 	dev->isoc_ctl.isoc_copy = isoc_copy;
223 	dev->isoc_ctl.num_bufs = num_bufs;
224 
225 	dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs,  GFP_KERNEL);
226 	if (!dev->isoc_ctl.urb) {
227 		au0828_isocdbg("cannot alloc memory for usb buffers\n");
228 		return -ENOMEM;
229 	}
230 
231 	dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
232 					      GFP_KERNEL);
233 	if (!dev->isoc_ctl.transfer_buffer) {
234 		au0828_isocdbg("cannot allocate memory for usb transfer\n");
235 		kfree(dev->isoc_ctl.urb);
236 		return -ENOMEM;
237 	}
238 
239 	dev->isoc_ctl.max_pkt_size = max_pkt_size;
240 	dev->isoc_ctl.buf = NULL;
241 
242 	sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
243 
244 	/* allocate urbs and transfer buffers */
245 	for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
246 		urb = usb_alloc_urb(max_packets, GFP_KERNEL);
247 		if (!urb) {
248 			au0828_uninit_isoc(dev);
249 			return -ENOMEM;
250 		}
251 		dev->isoc_ctl.urb[i] = urb;
252 
253 		dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->usbdev,
254 			sb_size, GFP_KERNEL, &urb->transfer_dma);
255 		if (!dev->isoc_ctl.transfer_buffer[i]) {
256 			printk("unable to allocate %i bytes for transfer 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 	vb->vb2_buf.timestamp = ktime_get_ns();
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 void au0828_usb_v4l2_media_release(struct au0828_dev *dev)
641 {
642 #ifdef CONFIG_MEDIA_CONTROLLER
643 	int i;
644 
645 	for (i = 0; i < AU0828_MAX_INPUT; i++) {
646 		if (AUVI_INPUT(i).type == AU0828_VMUX_UNDEFINED)
647 			return;
648 		media_device_unregister_entity(&dev->input_ent[i]);
649 	}
650 #endif
651 }
652 
653 static void au0828_usb_v4l2_release(struct v4l2_device *v4l2_dev)
654 {
655 	struct au0828_dev *dev =
656 		container_of(v4l2_dev, struct au0828_dev, v4l2_dev);
657 
658 	v4l2_ctrl_handler_free(&dev->v4l2_ctrl_hdl);
659 	v4l2_device_unregister(&dev->v4l2_dev);
660 	au0828_usb_v4l2_media_release(dev);
661 	au0828_usb_release(dev);
662 }
663 
664 int au0828_v4l2_device_register(struct usb_interface *interface,
665 				struct au0828_dev *dev)
666 {
667 	int retval;
668 
669 	if (AUVI_INPUT(0).type == AU0828_VMUX_UNDEFINED)
670 		return 0;
671 
672 	/* Create the v4l2_device */
673 #ifdef CONFIG_MEDIA_CONTROLLER
674 	dev->v4l2_dev.mdev = dev->media_dev;
675 #endif
676 	retval = v4l2_device_register(&interface->dev, &dev->v4l2_dev);
677 	if (retval) {
678 		pr_err("%s() v4l2_device_register failed\n",
679 		       __func__);
680 		return retval;
681 	}
682 
683 	dev->v4l2_dev.release = au0828_usb_v4l2_release;
684 
685 	/* This control handler will inherit the controls from au8522 */
686 	retval = v4l2_ctrl_handler_init(&dev->v4l2_ctrl_hdl, 4);
687 	if (retval) {
688 		pr_err("%s() v4l2_ctrl_handler_init failed\n",
689 		       __func__);
690 		return retval;
691 	}
692 	dev->v4l2_dev.ctrl_handler = &dev->v4l2_ctrl_hdl;
693 
694 	return 0;
695 }
696 
697 static int queue_setup(struct vb2_queue *vq,
698 		       unsigned int *nbuffers, unsigned int *nplanes,
699 		       unsigned int sizes[], struct device *alloc_devs[])
700 {
701 	struct au0828_dev *dev = vb2_get_drv_priv(vq);
702 	unsigned long size = dev->height * dev->bytesperline;
703 
704 	if (*nplanes)
705 		return sizes[0] < size ? -EINVAL : 0;
706 	*nplanes = 1;
707 	sizes[0] = size;
708 	return 0;
709 }
710 
711 static int
712 buffer_prepare(struct vb2_buffer *vb)
713 {
714 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
715 	struct au0828_buffer *buf = container_of(vbuf,
716 				struct au0828_buffer, vb);
717 	struct au0828_dev    *dev = vb2_get_drv_priv(vb->vb2_queue);
718 
719 	buf->length = dev->height * dev->bytesperline;
720 
721 	if (vb2_plane_size(vb, 0) < buf->length) {
722 		pr_err("%s data will not fit into plane (%lu < %lu)\n",
723 			__func__, vb2_plane_size(vb, 0), buf->length);
724 		return -EINVAL;
725 	}
726 	vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->length);
727 	return 0;
728 }
729 
730 static void
731 buffer_queue(struct vb2_buffer *vb)
732 {
733 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
734 	struct au0828_buffer    *buf     = container_of(vbuf,
735 							struct au0828_buffer,
736 							vb);
737 	struct au0828_dev       *dev     = vb2_get_drv_priv(vb->vb2_queue);
738 	struct au0828_dmaqueue  *vidq    = &dev->vidq;
739 	unsigned long flags = 0;
740 
741 	buf->mem = vb2_plane_vaddr(vb, 0);
742 	buf->length = vb2_plane_size(vb, 0);
743 
744 	spin_lock_irqsave(&dev->slock, flags);
745 	list_add_tail(&buf->list, &vidq->active);
746 	spin_unlock_irqrestore(&dev->slock, flags);
747 }
748 
749 static int au0828_i2s_init(struct au0828_dev *dev)
750 {
751 	/* Enable i2s mode */
752 	au0828_writereg(dev, AU0828_AUDIOCTRL_50C, 0x01);
753 	return 0;
754 }
755 
756 /*
757  * Auvitek au0828 analog stream enable
758  */
759 static int au0828_analog_stream_enable(struct au0828_dev *d)
760 {
761 	struct usb_interface *iface;
762 	int ret, h, w;
763 
764 	dprintk(1, "au0828_analog_stream_enable called\n");
765 
766 	iface = usb_ifnum_to_if(d->usbdev, 0);
767 	if (iface && iface->cur_altsetting->desc.bAlternateSetting != 5) {
768 		dprintk(1, "Changing intf#0 to alt 5\n");
769 		/* set au0828 interface0 to AS5 here again */
770 		ret = usb_set_interface(d->usbdev, 0, 5);
771 		if (ret < 0) {
772 			pr_info("Au0828 can't set alt setting to 5!\n");
773 			return -EBUSY;
774 		}
775 	}
776 
777 	h = d->height / 2 + 2;
778 	w = d->width * 2;
779 
780 	au0828_writereg(d, AU0828_SENSORCTRL_VBI_103, 0x00);
781 	au0828_writereg(d, 0x106, 0x00);
782 	/* set x position */
783 	au0828_writereg(d, 0x110, 0x00);
784 	au0828_writereg(d, 0x111, 0x00);
785 	au0828_writereg(d, 0x114, w & 0xff);
786 	au0828_writereg(d, 0x115, w >> 8);
787 	/* set y position */
788 	au0828_writereg(d, 0x112, 0x00);
789 	au0828_writereg(d, 0x113, 0x00);
790 	au0828_writereg(d, 0x116, h & 0xff);
791 	au0828_writereg(d, 0x117, h >> 8);
792 	au0828_writereg(d, AU0828_SENSORCTRL_100, 0xb3);
793 
794 	return 0;
795 }
796 
797 static int au0828_analog_stream_disable(struct au0828_dev *d)
798 {
799 	dprintk(1, "au0828_analog_stream_disable called\n");
800 	au0828_writereg(d, AU0828_SENSORCTRL_100, 0x0);
801 	return 0;
802 }
803 
804 static void au0828_analog_stream_reset(struct au0828_dev *dev)
805 {
806 	dprintk(1, "au0828_analog_stream_reset called\n");
807 	au0828_writereg(dev, AU0828_SENSORCTRL_100, 0x0);
808 	mdelay(30);
809 	au0828_writereg(dev, AU0828_SENSORCTRL_100, 0xb3);
810 }
811 
812 /*
813  * Some operations needs to stop current streaming
814  */
815 static int au0828_stream_interrupt(struct au0828_dev *dev)
816 {
817 	int ret = 0;
818 
819 	dev->stream_state = STREAM_INTERRUPT;
820 	if (test_bit(DEV_DISCONNECTED, &dev->dev_state))
821 		return -ENODEV;
822 	else if (ret) {
823 		set_bit(DEV_MISCONFIGURED, &dev->dev_state);
824 		dprintk(1, "%s device is misconfigured!\n", __func__);
825 		return ret;
826 	}
827 	return 0;
828 }
829 
830 int au0828_start_analog_streaming(struct vb2_queue *vq, unsigned int count)
831 {
832 	struct au0828_dev *dev = vb2_get_drv_priv(vq);
833 	int rc = 0;
834 
835 	dprintk(1, "au0828_start_analog_streaming called %d\n",
836 		dev->streaming_users);
837 
838 	if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
839 		dev->frame_count = 0;
840 	else
841 		dev->vbi_frame_count = 0;
842 
843 	if (dev->streaming_users == 0) {
844 		/* If we were doing ac97 instead of i2s, it would go here...*/
845 		au0828_i2s_init(dev);
846 		rc = au0828_init_isoc(dev, AU0828_ISO_PACKETS_PER_URB,
847 				   AU0828_MAX_ISO_BUFS, dev->max_pkt_size,
848 				   au0828_isoc_copy);
849 		if (rc < 0) {
850 			pr_info("au0828_init_isoc failed\n");
851 			return rc;
852 		}
853 
854 		if (vq->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
855 			v4l2_device_call_all(&dev->v4l2_dev, 0, video,
856 						s_stream, 1);
857 			dev->vid_timeout_running = 1;
858 			mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
859 		} else if (vq->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
860 			dev->vbi_timeout_running = 1;
861 			mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
862 		}
863 	}
864 	dev->streaming_users++;
865 	return rc;
866 }
867 
868 static void au0828_stop_streaming(struct vb2_queue *vq)
869 {
870 	struct au0828_dev *dev = vb2_get_drv_priv(vq);
871 	struct au0828_dmaqueue *vidq = &dev->vidq;
872 	unsigned long flags = 0;
873 
874 	dprintk(1, "au0828_stop_streaming called %d\n", dev->streaming_users);
875 
876 	if (dev->streaming_users-- == 1)
877 		au0828_uninit_isoc(dev);
878 
879 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_stream, 0);
880 	dev->vid_timeout_running = 0;
881 	del_timer_sync(&dev->vid_timeout);
882 
883 	spin_lock_irqsave(&dev->slock, flags);
884 	if (dev->isoc_ctl.buf != NULL) {
885 		vb2_buffer_done(&dev->isoc_ctl.buf->vb.vb2_buf,
886 				VB2_BUF_STATE_ERROR);
887 		dev->isoc_ctl.buf = NULL;
888 	}
889 	while (!list_empty(&vidq->active)) {
890 		struct au0828_buffer *buf;
891 
892 		buf = list_entry(vidq->active.next, struct au0828_buffer, list);
893 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
894 		list_del(&buf->list);
895 	}
896 	spin_unlock_irqrestore(&dev->slock, flags);
897 }
898 
899 void au0828_stop_vbi_streaming(struct vb2_queue *vq)
900 {
901 	struct au0828_dev *dev = vb2_get_drv_priv(vq);
902 	struct au0828_dmaqueue *vbiq = &dev->vbiq;
903 	unsigned long flags = 0;
904 
905 	dprintk(1, "au0828_stop_vbi_streaming called %d\n",
906 		dev->streaming_users);
907 
908 	if (dev->streaming_users-- == 1)
909 		au0828_uninit_isoc(dev);
910 
911 	spin_lock_irqsave(&dev->slock, flags);
912 	if (dev->isoc_ctl.vbi_buf != NULL) {
913 		vb2_buffer_done(&dev->isoc_ctl.vbi_buf->vb.vb2_buf,
914 				VB2_BUF_STATE_ERROR);
915 		dev->isoc_ctl.vbi_buf = NULL;
916 	}
917 	while (!list_empty(&vbiq->active)) {
918 		struct au0828_buffer *buf;
919 
920 		buf = list_entry(vbiq->active.next, struct au0828_buffer, list);
921 		list_del(&buf->list);
922 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
923 	}
924 	spin_unlock_irqrestore(&dev->slock, flags);
925 
926 	dev->vbi_timeout_running = 0;
927 	del_timer_sync(&dev->vbi_timeout);
928 }
929 
930 static const struct vb2_ops au0828_video_qops = {
931 	.queue_setup     = queue_setup,
932 	.buf_prepare     = buffer_prepare,
933 	.buf_queue       = buffer_queue,
934 	.start_streaming = au0828_start_analog_streaming,
935 	.stop_streaming  = au0828_stop_streaming,
936 	.wait_prepare    = vb2_ops_wait_prepare,
937 	.wait_finish     = vb2_ops_wait_finish,
938 };
939 
940 /* ------------------------------------------------------------------
941    V4L2 interface
942    ------------------------------------------------------------------*/
943 /*
944  * au0828_analog_unregister
945  * unregister v4l2 devices
946  */
947 int au0828_analog_unregister(struct au0828_dev *dev)
948 {
949 	dprintk(1, "au0828_analog_unregister called\n");
950 
951 	/* No analog TV */
952 	if (AUVI_INPUT(0).type == AU0828_VMUX_UNDEFINED)
953 		return 0;
954 
955 	mutex_lock(&au0828_sysfs_lock);
956 	video_unregister_device(&dev->vdev);
957 	video_unregister_device(&dev->vbi_dev);
958 	mutex_unlock(&au0828_sysfs_lock);
959 
960 	v4l2_device_disconnect(&dev->v4l2_dev);
961 	v4l2_device_put(&dev->v4l2_dev);
962 
963 	return 1;
964 }
965 
966 /* This function ensures that video frames continue to be delivered even if
967    the ITU-656 input isn't receiving any data (thereby preventing applications
968    such as tvtime from hanging) */
969 static void au0828_vid_buffer_timeout(unsigned long data)
970 {
971 	struct au0828_dev *dev = (struct au0828_dev *) data;
972 	struct au0828_dmaqueue *dma_q = &dev->vidq;
973 	struct au0828_buffer *buf;
974 	unsigned char *vid_data;
975 	unsigned long flags = 0;
976 
977 	spin_lock_irqsave(&dev->slock, flags);
978 
979 	buf = dev->isoc_ctl.buf;
980 	if (buf != NULL) {
981 		vid_data = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
982 		memset(vid_data, 0x00, buf->length); /* Blank green frame */
983 		buffer_filled(dev, dma_q, buf);
984 	}
985 	get_next_buf(dma_q, &buf);
986 
987 	if (dev->vid_timeout_running == 1)
988 		mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
989 
990 	spin_unlock_irqrestore(&dev->slock, flags);
991 }
992 
993 static void au0828_vbi_buffer_timeout(unsigned long data)
994 {
995 	struct au0828_dev *dev = (struct au0828_dev *) data;
996 	struct au0828_dmaqueue *dma_q = &dev->vbiq;
997 	struct au0828_buffer *buf;
998 	unsigned char *vbi_data;
999 	unsigned long flags = 0;
1000 
1001 	spin_lock_irqsave(&dev->slock, flags);
1002 
1003 	buf = dev->isoc_ctl.vbi_buf;
1004 	if (buf != NULL) {
1005 		vbi_data = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
1006 		memset(vbi_data, 0x00, buf->length);
1007 		buffer_filled(dev, dma_q, buf);
1008 	}
1009 	vbi_get_next_buf(dma_q, &buf);
1010 
1011 	if (dev->vbi_timeout_running == 1)
1012 		mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
1013 	spin_unlock_irqrestore(&dev->slock, flags);
1014 }
1015 
1016 static int au0828_v4l2_open(struct file *filp)
1017 {
1018 	struct au0828_dev *dev = video_drvdata(filp);
1019 	int ret;
1020 
1021 	dprintk(1,
1022 		"%s called std_set %d dev_state %ld stream users %d users %d\n",
1023 		__func__, dev->std_set_in_tuner_core, dev->dev_state,
1024 		dev->streaming_users, dev->users);
1025 
1026 	if (mutex_lock_interruptible(&dev->lock))
1027 		return -ERESTARTSYS;
1028 
1029 	ret = v4l2_fh_open(filp);
1030 	if (ret) {
1031 		au0828_isocdbg("%s: v4l2_fh_open() returned error %d\n",
1032 				__func__, ret);
1033 		mutex_unlock(&dev->lock);
1034 		return ret;
1035 	}
1036 
1037 	if (dev->users == 0) {
1038 		au0828_analog_stream_enable(dev);
1039 		au0828_analog_stream_reset(dev);
1040 		dev->stream_state = STREAM_OFF;
1041 		set_bit(DEV_INITIALIZED, &dev->dev_state);
1042 	}
1043 	dev->users++;
1044 	mutex_unlock(&dev->lock);
1045 	return ret;
1046 }
1047 
1048 static int au0828_v4l2_close(struct file *filp)
1049 {
1050 	int ret;
1051 	struct au0828_dev *dev = video_drvdata(filp);
1052 	struct video_device *vdev = video_devdata(filp);
1053 
1054 	dprintk(1,
1055 		"%s called std_set %d dev_state %ld stream users %d users %d\n",
1056 		__func__, dev->std_set_in_tuner_core, dev->dev_state,
1057 		dev->streaming_users, dev->users);
1058 
1059 	mutex_lock(&dev->lock);
1060 	if (vdev->vfl_type == VFL_TYPE_GRABBER && dev->vid_timeout_running) {
1061 		/* Cancel timeout thread in case they didn't call streamoff */
1062 		dev->vid_timeout_running = 0;
1063 		del_timer_sync(&dev->vid_timeout);
1064 	} else if (vdev->vfl_type == VFL_TYPE_VBI &&
1065 			dev->vbi_timeout_running) {
1066 		/* Cancel timeout thread in case they didn't call streamoff */
1067 		dev->vbi_timeout_running = 0;
1068 		del_timer_sync(&dev->vbi_timeout);
1069 	}
1070 
1071 	if (test_bit(DEV_DISCONNECTED, &dev->dev_state))
1072 		goto end;
1073 
1074 	if (dev->users == 1) {
1075 		/*
1076 		 * Avoid putting tuner in sleep if DVB or ALSA are
1077 		 * streaming.
1078 		 *
1079 		 * On most USB devices  like au0828 the tuner can
1080 		 * be safely put in sleep stare here if ALSA isn't
1081 		 * streaming. Exceptions are some very old USB tuner
1082 		 * models such as em28xx-based WinTV USB2 which have
1083 		 * a separate audio output jack. The devices that have
1084 		 * a separate audio output jack have analog tuners,
1085 		 * like Philips FM1236. Those devices are always on,
1086 		 * so the s_power callback are silently ignored.
1087 		 * So, the current logic here does the following:
1088 		 * Disable (put tuner to sleep) when
1089 		 * - ALSA and DVB aren't not streaming;
1090 		 * - the last V4L2 file handler is closed.
1091 		 *
1092 		 * FIXME:
1093 		 *
1094 		 * Additionally, this logic could be improved to
1095 		 * disable the media source if the above conditions
1096 		 * are met and if the device:
1097 		 * - doesn't have a separate audio out plug (or
1098 		 * - doesn't use a silicon tuner like xc2028/3028/4000/5000).
1099 		 *
1100 		 * Once this additional logic is in place, a callback
1101 		 * is needed to enable the media source and power on
1102 		 * the tuner, for radio to work.
1103 		*/
1104 		ret = v4l_enable_media_source(vdev);
1105 		if (ret == 0)
1106 			v4l2_device_call_all(&dev->v4l2_dev, 0, core,
1107 					     s_power, 0);
1108 		dev->std_set_in_tuner_core = 0;
1109 
1110 		/* When close the device, set the usb intf0 into alt0 to free
1111 		   USB bandwidth */
1112 		ret = usb_set_interface(dev->usbdev, 0, 0);
1113 		if (ret < 0)
1114 			pr_info("Au0828 can't set alternate to 0!\n");
1115 	}
1116 end:
1117 	_vb2_fop_release(filp, NULL);
1118 	dev->users--;
1119 	mutex_unlock(&dev->lock);
1120 	return 0;
1121 }
1122 
1123 /* Must be called with dev->lock held */
1124 static void au0828_init_tuner(struct au0828_dev *dev)
1125 {
1126 	struct v4l2_frequency f = {
1127 		.frequency = dev->ctrl_freq,
1128 		.type = V4L2_TUNER_ANALOG_TV,
1129 	};
1130 
1131 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1132 		dev->std_set_in_tuner_core, dev->dev_state);
1133 
1134 	if (dev->std_set_in_tuner_core)
1135 		return;
1136 	dev->std_set_in_tuner_core = 1;
1137 	i2c_gate_ctrl(dev, 1);
1138 	/* If we've never sent the standard in tuner core, do so now.
1139 	   We don't do this at device probe because we don't want to
1140 	   incur the cost of a firmware load */
1141 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std, dev->std);
1142 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, &f);
1143 	i2c_gate_ctrl(dev, 0);
1144 }
1145 
1146 static int au0828_set_format(struct au0828_dev *dev, unsigned int cmd,
1147 			     struct v4l2_format *format)
1148 {
1149 	int ret;
1150 	int width = format->fmt.pix.width;
1151 	int height = format->fmt.pix.height;
1152 
1153 	/* If they are demanding a format other than the one we support,
1154 	   bail out (tvtime asks for UYVY and then retries with YUYV) */
1155 	if (format->fmt.pix.pixelformat != V4L2_PIX_FMT_UYVY)
1156 		return -EINVAL;
1157 
1158 	/* format->fmt.pix.width only support 720 and height 480 */
1159 	if (width != 720)
1160 		width = 720;
1161 	if (height != 480)
1162 		height = 480;
1163 
1164 	format->fmt.pix.width = width;
1165 	format->fmt.pix.height = height;
1166 	format->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1167 	format->fmt.pix.bytesperline = width * 2;
1168 	format->fmt.pix.sizeimage = width * height * 2;
1169 	format->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1170 	format->fmt.pix.field = V4L2_FIELD_INTERLACED;
1171 	format->fmt.pix.priv = 0;
1172 
1173 	if (cmd == VIDIOC_TRY_FMT)
1174 		return 0;
1175 
1176 	/* maybe set new image format, driver current only support 720*480 */
1177 	dev->width = width;
1178 	dev->height = height;
1179 	dev->frame_size = width * height * 2;
1180 	dev->field_size = width * height;
1181 	dev->bytesperline = width * 2;
1182 
1183 	if (dev->stream_state == STREAM_ON) {
1184 		dprintk(1, "VIDIOC_SET_FMT: interrupting stream!\n");
1185 		ret = au0828_stream_interrupt(dev);
1186 		if (ret != 0) {
1187 			dprintk(1, "error interrupting video stream!\n");
1188 			return ret;
1189 		}
1190 	}
1191 
1192 	au0828_analog_stream_enable(dev);
1193 
1194 	return 0;
1195 }
1196 
1197 static int vidioc_querycap(struct file *file, void  *priv,
1198 			   struct v4l2_capability *cap)
1199 {
1200 	struct video_device *vdev = video_devdata(file);
1201 	struct au0828_dev *dev = video_drvdata(file);
1202 
1203 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1204 		dev->std_set_in_tuner_core, dev->dev_state);
1205 
1206 	strlcpy(cap->driver, "au0828", sizeof(cap->driver));
1207 	strlcpy(cap->card, dev->board.name, sizeof(cap->card));
1208 	usb_make_path(dev->usbdev, cap->bus_info, sizeof(cap->bus_info));
1209 
1210 	/* set the device capabilities */
1211 	cap->device_caps = V4L2_CAP_AUDIO |
1212 		V4L2_CAP_READWRITE |
1213 		V4L2_CAP_STREAMING |
1214 		V4L2_CAP_TUNER;
1215 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1216 		cap->device_caps |= V4L2_CAP_VIDEO_CAPTURE;
1217 	else
1218 		cap->device_caps |= V4L2_CAP_VBI_CAPTURE;
1219 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS |
1220 		V4L2_CAP_VBI_CAPTURE | V4L2_CAP_VIDEO_CAPTURE;
1221 	return 0;
1222 }
1223 
1224 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1225 					struct v4l2_fmtdesc *f)
1226 {
1227 	if (f->index)
1228 		return -EINVAL;
1229 
1230 	dprintk(1, "%s called\n", __func__);
1231 
1232 	f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1233 	strcpy(f->description, "Packed YUV2");
1234 
1235 	f->flags = 0;
1236 	f->pixelformat = V4L2_PIX_FMT_UYVY;
1237 
1238 	return 0;
1239 }
1240 
1241 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1242 					struct v4l2_format *f)
1243 {
1244 	struct au0828_dev *dev = video_drvdata(file);
1245 
1246 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1247 		dev->std_set_in_tuner_core, dev->dev_state);
1248 
1249 	f->fmt.pix.width = dev->width;
1250 	f->fmt.pix.height = dev->height;
1251 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1252 	f->fmt.pix.bytesperline = dev->bytesperline;
1253 	f->fmt.pix.sizeimage = dev->frame_size;
1254 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; /* NTSC/PAL */
1255 	f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1256 	f->fmt.pix.priv = 0;
1257 	return 0;
1258 }
1259 
1260 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1261 				  struct v4l2_format *f)
1262 {
1263 	struct au0828_dev *dev = video_drvdata(file);
1264 
1265 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1266 		dev->std_set_in_tuner_core, dev->dev_state);
1267 
1268 	return au0828_set_format(dev, VIDIOC_TRY_FMT, f);
1269 }
1270 
1271 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1272 				struct v4l2_format *f)
1273 {
1274 	struct au0828_dev *dev = video_drvdata(file);
1275 	int rc;
1276 
1277 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1278 		dev->std_set_in_tuner_core, dev->dev_state);
1279 
1280 	rc = check_dev(dev);
1281 	if (rc < 0)
1282 		return rc;
1283 
1284 	if (vb2_is_busy(&dev->vb_vidq)) {
1285 		pr_info("%s queue busy\n", __func__);
1286 		rc = -EBUSY;
1287 		goto out;
1288 	}
1289 
1290 	rc = au0828_set_format(dev, VIDIOC_S_FMT, f);
1291 out:
1292 	return rc;
1293 }
1294 
1295 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1296 {
1297 	struct au0828_dev *dev = video_drvdata(file);
1298 
1299 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1300 		dev->std_set_in_tuner_core, dev->dev_state);
1301 
1302 	if (norm == dev->std)
1303 		return 0;
1304 
1305 	if (dev->streaming_users > 0)
1306 		return -EBUSY;
1307 
1308 	dev->std = norm;
1309 
1310 	au0828_init_tuner(dev);
1311 
1312 	i2c_gate_ctrl(dev, 1);
1313 
1314 	/*
1315 	 * FIXME: when we support something other than 60Hz standards,
1316 	 * we are going to have to make the au0828 bridge adjust the size
1317 	 * of its capture buffer, which is currently hardcoded at 720x480
1318 	 */
1319 
1320 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_std, norm);
1321 
1322 	i2c_gate_ctrl(dev, 0);
1323 
1324 	return 0;
1325 }
1326 
1327 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *norm)
1328 {
1329 	struct au0828_dev *dev = video_drvdata(file);
1330 
1331 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1332 		dev->std_set_in_tuner_core, dev->dev_state);
1333 
1334 	*norm = dev->std;
1335 	return 0;
1336 }
1337 
1338 static int vidioc_enum_input(struct file *file, void *priv,
1339 				struct v4l2_input *input)
1340 {
1341 	struct au0828_dev *dev = video_drvdata(file);
1342 	unsigned int tmp;
1343 
1344 	static const char *inames[] = {
1345 		[AU0828_VMUX_UNDEFINED] = "Undefined",
1346 		[AU0828_VMUX_COMPOSITE] = "Composite",
1347 		[AU0828_VMUX_SVIDEO] = "S-Video",
1348 		[AU0828_VMUX_CABLE] = "Cable TV",
1349 		[AU0828_VMUX_TELEVISION] = "Television",
1350 		[AU0828_VMUX_DVB] = "DVB",
1351 	};
1352 
1353 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1354 		dev->std_set_in_tuner_core, dev->dev_state);
1355 
1356 	tmp = input->index;
1357 
1358 	if (tmp >= AU0828_MAX_INPUT)
1359 		return -EINVAL;
1360 	if (AUVI_INPUT(tmp).type == 0)
1361 		return -EINVAL;
1362 
1363 	input->index = tmp;
1364 	strcpy(input->name, inames[AUVI_INPUT(tmp).type]);
1365 	if ((AUVI_INPUT(tmp).type == AU0828_VMUX_TELEVISION) ||
1366 	    (AUVI_INPUT(tmp).type == AU0828_VMUX_CABLE)) {
1367 		input->type |= V4L2_INPUT_TYPE_TUNER;
1368 		input->audioset = 1;
1369 	} else {
1370 		input->type |= V4L2_INPUT_TYPE_CAMERA;
1371 		input->audioset = 2;
1372 	}
1373 
1374 	input->std = dev->vdev.tvnorms;
1375 
1376 	return 0;
1377 }
1378 
1379 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1380 {
1381 	struct au0828_dev *dev = video_drvdata(file);
1382 
1383 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1384 		dev->std_set_in_tuner_core, dev->dev_state);
1385 
1386 	*i = dev->ctrl_input;
1387 	return 0;
1388 }
1389 
1390 static void au0828_s_input(struct au0828_dev *dev, int index)
1391 {
1392 	int i;
1393 
1394 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1395 		dev->std_set_in_tuner_core, dev->dev_state);
1396 
1397 	switch (AUVI_INPUT(index).type) {
1398 	case AU0828_VMUX_SVIDEO:
1399 		dev->input_type = AU0828_VMUX_SVIDEO;
1400 		dev->ctrl_ainput = 1;
1401 		break;
1402 	case AU0828_VMUX_COMPOSITE:
1403 		dev->input_type = AU0828_VMUX_COMPOSITE;
1404 		dev->ctrl_ainput = 1;
1405 		break;
1406 	case AU0828_VMUX_TELEVISION:
1407 		dev->input_type = AU0828_VMUX_TELEVISION;
1408 		dev->ctrl_ainput = 0;
1409 		break;
1410 	default:
1411 		dprintk(1, "unknown input type set [%d]\n",
1412 			AUVI_INPUT(index).type);
1413 		return;
1414 	}
1415 
1416 	dev->ctrl_input = index;
1417 
1418 	v4l2_device_call_all(&dev->v4l2_dev, 0, video, s_routing,
1419 			AUVI_INPUT(index).vmux, 0, 0);
1420 
1421 	for (i = 0; i < AU0828_MAX_INPUT; i++) {
1422 		int enable = 0;
1423 		if (AUVI_INPUT(i).audio_setup == NULL)
1424 			continue;
1425 
1426 		if (i == index)
1427 			enable = 1;
1428 		else
1429 			enable = 0;
1430 		if (enable) {
1431 			(AUVI_INPUT(i).audio_setup)(dev, enable);
1432 		} else {
1433 			/* Make sure we leave it turned on if some
1434 			   other input is routed to this callback */
1435 			if ((AUVI_INPUT(i).audio_setup) !=
1436 			    ((AUVI_INPUT(index).audio_setup))) {
1437 				(AUVI_INPUT(i).audio_setup)(dev, enable);
1438 			}
1439 		}
1440 	}
1441 
1442 	v4l2_device_call_all(&dev->v4l2_dev, 0, audio, s_routing,
1443 			AUVI_INPUT(index).amux, 0, 0);
1444 }
1445 
1446 static int vidioc_s_input(struct file *file, void *priv, unsigned int index)
1447 {
1448 	struct au0828_dev *dev = video_drvdata(file);
1449 	struct video_device *vfd = video_devdata(file);
1450 
1451 	dprintk(1, "VIDIOC_S_INPUT in function %s, input=%d\n", __func__,
1452 		index);
1453 	if (index >= AU0828_MAX_INPUT)
1454 		return -EINVAL;
1455 	if (AUVI_INPUT(index).type == 0)
1456 		return -EINVAL;
1457 
1458 	if (dev->ctrl_input == index)
1459 		return 0;
1460 
1461 	au0828_s_input(dev, index);
1462 
1463 	/*
1464 	 * Input has been changed. Disable the media source
1465 	 * associated with the old input and enable source
1466 	 * for the newly set input
1467 	 */
1468 	v4l_disable_media_source(vfd);
1469 	return v4l_enable_media_source(vfd);
1470 }
1471 
1472 static int vidioc_enumaudio(struct file *file, void *priv, struct v4l2_audio *a)
1473 {
1474 	if (a->index > 1)
1475 		return -EINVAL;
1476 
1477 	dprintk(1, "%s called\n", __func__);
1478 
1479 	if (a->index == 0)
1480 		strcpy(a->name, "Television");
1481 	else
1482 		strcpy(a->name, "Line in");
1483 
1484 	a->capability = V4L2_AUDCAP_STEREO;
1485 	return 0;
1486 }
1487 
1488 static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a)
1489 {
1490 	struct au0828_dev *dev = video_drvdata(file);
1491 
1492 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1493 		dev->std_set_in_tuner_core, dev->dev_state);
1494 
1495 	a->index = dev->ctrl_ainput;
1496 	if (a->index == 0)
1497 		strcpy(a->name, "Television");
1498 	else
1499 		strcpy(a->name, "Line in");
1500 
1501 	a->capability = V4L2_AUDCAP_STEREO;
1502 	return 0;
1503 }
1504 
1505 static int vidioc_s_audio(struct file *file, void *priv, const struct v4l2_audio *a)
1506 {
1507 	struct au0828_dev *dev = video_drvdata(file);
1508 
1509 	if (a->index != dev->ctrl_ainput)
1510 		return -EINVAL;
1511 
1512 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1513 		dev->std_set_in_tuner_core, dev->dev_state);
1514 	return 0;
1515 }
1516 
1517 static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1518 {
1519 	struct au0828_dev *dev = video_drvdata(file);
1520 	struct video_device *vfd = video_devdata(file);
1521 	int ret;
1522 
1523 	if (t->index != 0)
1524 		return -EINVAL;
1525 
1526 	ret = v4l_enable_media_source(vfd);
1527 	if (ret)
1528 		return ret;
1529 
1530 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1531 		dev->std_set_in_tuner_core, dev->dev_state);
1532 
1533 	strcpy(t->name, "Auvitek tuner");
1534 
1535 	au0828_init_tuner(dev);
1536 	i2c_gate_ctrl(dev, 1);
1537 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_tuner, t);
1538 	i2c_gate_ctrl(dev, 0);
1539 	return 0;
1540 }
1541 
1542 static int vidioc_s_tuner(struct file *file, void *priv,
1543 				const struct v4l2_tuner *t)
1544 {
1545 	struct au0828_dev *dev = video_drvdata(file);
1546 
1547 	if (t->index != 0)
1548 		return -EINVAL;
1549 
1550 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1551 		dev->std_set_in_tuner_core, dev->dev_state);
1552 
1553 	au0828_init_tuner(dev);
1554 	i2c_gate_ctrl(dev, 1);
1555 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_tuner, t);
1556 	i2c_gate_ctrl(dev, 0);
1557 
1558 	dprintk(1, "VIDIOC_S_TUNER: signal = %x, afc = %x\n", t->signal,
1559 		t->afc);
1560 
1561 	return 0;
1562 
1563 }
1564 
1565 static int vidioc_g_frequency(struct file *file, void *priv,
1566 				struct v4l2_frequency *freq)
1567 {
1568 	struct au0828_dev *dev = video_drvdata(file);
1569 
1570 	if (freq->tuner != 0)
1571 		return -EINVAL;
1572 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1573 		dev->std_set_in_tuner_core, dev->dev_state);
1574 	freq->frequency = dev->ctrl_freq;
1575 	return 0;
1576 }
1577 
1578 static int vidioc_s_frequency(struct file *file, void *priv,
1579 				const struct v4l2_frequency *freq)
1580 {
1581 	struct au0828_dev *dev = video_drvdata(file);
1582 	struct v4l2_frequency new_freq = *freq;
1583 
1584 	if (freq->tuner != 0)
1585 		return -EINVAL;
1586 
1587 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1588 		dev->std_set_in_tuner_core, dev->dev_state);
1589 
1590 	au0828_init_tuner(dev);
1591 	i2c_gate_ctrl(dev, 1);
1592 
1593 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, freq);
1594 	/* Get the actual set (and possibly clamped) frequency */
1595 	v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, g_frequency, &new_freq);
1596 	dev->ctrl_freq = new_freq.frequency;
1597 
1598 	i2c_gate_ctrl(dev, 0);
1599 
1600 	au0828_analog_stream_reset(dev);
1601 
1602 	return 0;
1603 }
1604 
1605 
1606 /* RAW VBI ioctls */
1607 
1608 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1609 				struct v4l2_format *format)
1610 {
1611 	struct au0828_dev *dev = video_drvdata(file);
1612 
1613 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1614 		dev->std_set_in_tuner_core, dev->dev_state);
1615 
1616 	format->fmt.vbi.samples_per_line = dev->vbi_width;
1617 	format->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1618 	format->fmt.vbi.offset = 0;
1619 	format->fmt.vbi.flags = 0;
1620 	format->fmt.vbi.sampling_rate = 6750000 * 4 / 2;
1621 
1622 	format->fmt.vbi.count[0] = dev->vbi_height;
1623 	format->fmt.vbi.count[1] = dev->vbi_height;
1624 	format->fmt.vbi.start[0] = 21;
1625 	format->fmt.vbi.start[1] = 284;
1626 	memset(format->fmt.vbi.reserved, 0, sizeof(format->fmt.vbi.reserved));
1627 
1628 	return 0;
1629 }
1630 
1631 static int vidioc_cropcap(struct file *file, void *priv,
1632 			  struct v4l2_cropcap *cc)
1633 {
1634 	struct au0828_dev *dev = video_drvdata(file);
1635 
1636 	if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1637 		return -EINVAL;
1638 
1639 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1640 		dev->std_set_in_tuner_core, dev->dev_state);
1641 
1642 	cc->bounds.left = 0;
1643 	cc->bounds.top = 0;
1644 	cc->bounds.width = dev->width;
1645 	cc->bounds.height = dev->height;
1646 
1647 	cc->defrect = cc->bounds;
1648 
1649 	cc->pixelaspect.numerator = 54;
1650 	cc->pixelaspect.denominator = 59;
1651 
1652 	return 0;
1653 }
1654 
1655 #ifdef CONFIG_VIDEO_ADV_DEBUG
1656 static int vidioc_g_register(struct file *file, void *priv,
1657 			     struct v4l2_dbg_register *reg)
1658 {
1659 	struct au0828_dev *dev = video_drvdata(file);
1660 
1661 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1662 		dev->std_set_in_tuner_core, dev->dev_state);
1663 
1664 	reg->val = au0828_read(dev, reg->reg);
1665 	reg->size = 1;
1666 	return 0;
1667 }
1668 
1669 static int vidioc_s_register(struct file *file, void *priv,
1670 			     const struct v4l2_dbg_register *reg)
1671 {
1672 	struct au0828_dev *dev = video_drvdata(file);
1673 
1674 	dprintk(1, "%s called std_set %d dev_state %ld\n", __func__,
1675 		dev->std_set_in_tuner_core, dev->dev_state);
1676 
1677 	return au0828_writereg(dev, reg->reg, reg->val);
1678 }
1679 #endif
1680 
1681 static int vidioc_log_status(struct file *file, void *fh)
1682 {
1683 	struct video_device *vdev = video_devdata(file);
1684 
1685 	dprintk(1, "%s called\n", __func__);
1686 
1687 	v4l2_ctrl_log_status(file, fh);
1688 	v4l2_device_call_all(vdev->v4l2_dev, 0, core, log_status);
1689 	return 0;
1690 }
1691 
1692 void au0828_v4l2_suspend(struct au0828_dev *dev)
1693 {
1694 	struct urb *urb;
1695 	int i;
1696 
1697 	pr_info("stopping V4L2\n");
1698 
1699 	if (dev->stream_state == STREAM_ON) {
1700 		pr_info("stopping V4L2 active URBs\n");
1701 		au0828_analog_stream_disable(dev);
1702 		/* stop urbs */
1703 		for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
1704 			urb = dev->isoc_ctl.urb[i];
1705 			if (urb) {
1706 				if (!irqs_disabled())
1707 					usb_kill_urb(urb);
1708 				else
1709 					usb_unlink_urb(urb);
1710 			}
1711 		}
1712 	}
1713 
1714 	if (dev->vid_timeout_running)
1715 		del_timer_sync(&dev->vid_timeout);
1716 	if (dev->vbi_timeout_running)
1717 		del_timer_sync(&dev->vbi_timeout);
1718 }
1719 
1720 void au0828_v4l2_resume(struct au0828_dev *dev)
1721 {
1722 	int i, rc;
1723 
1724 	pr_info("restarting V4L2\n");
1725 
1726 	if (dev->stream_state == STREAM_ON) {
1727 		au0828_stream_interrupt(dev);
1728 		au0828_init_tuner(dev);
1729 	}
1730 
1731 	if (dev->vid_timeout_running)
1732 		mod_timer(&dev->vid_timeout, jiffies + (HZ / 10));
1733 	if (dev->vbi_timeout_running)
1734 		mod_timer(&dev->vbi_timeout, jiffies + (HZ / 10));
1735 
1736 	/* If we were doing ac97 instead of i2s, it would go here...*/
1737 	au0828_i2s_init(dev);
1738 
1739 	au0828_analog_stream_enable(dev);
1740 
1741 	if (!(dev->stream_state == STREAM_ON)) {
1742 		au0828_analog_stream_reset(dev);
1743 		/* submit urbs */
1744 		for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
1745 			rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
1746 			if (rc) {
1747 				au0828_isocdbg("submit of urb %i failed (error=%i)\n",
1748 					       i, rc);
1749 				au0828_uninit_isoc(dev);
1750 			}
1751 		}
1752 	}
1753 }
1754 
1755 static struct v4l2_file_operations au0828_v4l_fops = {
1756 	.owner      = THIS_MODULE,
1757 	.open       = au0828_v4l2_open,
1758 	.release    = au0828_v4l2_close,
1759 	.read       = vb2_fop_read,
1760 	.poll       = vb2_fop_poll,
1761 	.mmap       = vb2_fop_mmap,
1762 	.unlocked_ioctl = video_ioctl2,
1763 };
1764 
1765 static const struct v4l2_ioctl_ops video_ioctl_ops = {
1766 	.vidioc_querycap            = vidioc_querycap,
1767 	.vidioc_enum_fmt_vid_cap    = vidioc_enum_fmt_vid_cap,
1768 	.vidioc_g_fmt_vid_cap       = vidioc_g_fmt_vid_cap,
1769 	.vidioc_try_fmt_vid_cap     = vidioc_try_fmt_vid_cap,
1770 	.vidioc_s_fmt_vid_cap       = vidioc_s_fmt_vid_cap,
1771 	.vidioc_g_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
1772 	.vidioc_try_fmt_vbi_cap     = vidioc_g_fmt_vbi_cap,
1773 	.vidioc_s_fmt_vbi_cap       = vidioc_g_fmt_vbi_cap,
1774 	.vidioc_enumaudio           = vidioc_enumaudio,
1775 	.vidioc_g_audio             = vidioc_g_audio,
1776 	.vidioc_s_audio             = vidioc_s_audio,
1777 	.vidioc_cropcap             = vidioc_cropcap,
1778 
1779 	.vidioc_reqbufs             = vb2_ioctl_reqbufs,
1780 	.vidioc_create_bufs         = vb2_ioctl_create_bufs,
1781 	.vidioc_prepare_buf         = vb2_ioctl_prepare_buf,
1782 	.vidioc_querybuf            = vb2_ioctl_querybuf,
1783 	.vidioc_qbuf                = vb2_ioctl_qbuf,
1784 	.vidioc_dqbuf               = vb2_ioctl_dqbuf,
1785 	.vidioc_expbuf               = vb2_ioctl_expbuf,
1786 
1787 	.vidioc_s_std               = vidioc_s_std,
1788 	.vidioc_g_std               = vidioc_g_std,
1789 	.vidioc_enum_input          = vidioc_enum_input,
1790 	.vidioc_g_input             = vidioc_g_input,
1791 	.vidioc_s_input             = vidioc_s_input,
1792 
1793 	.vidioc_streamon            = vb2_ioctl_streamon,
1794 	.vidioc_streamoff           = vb2_ioctl_streamoff,
1795 
1796 	.vidioc_g_tuner             = vidioc_g_tuner,
1797 	.vidioc_s_tuner             = vidioc_s_tuner,
1798 	.vidioc_g_frequency         = vidioc_g_frequency,
1799 	.vidioc_s_frequency         = vidioc_s_frequency,
1800 #ifdef CONFIG_VIDEO_ADV_DEBUG
1801 	.vidioc_g_register          = vidioc_g_register,
1802 	.vidioc_s_register          = vidioc_s_register,
1803 #endif
1804 	.vidioc_log_status	    = vidioc_log_status,
1805 	.vidioc_subscribe_event     = v4l2_ctrl_subscribe_event,
1806 	.vidioc_unsubscribe_event   = v4l2_event_unsubscribe,
1807 };
1808 
1809 static const struct video_device au0828_video_template = {
1810 	.fops                       = &au0828_v4l_fops,
1811 	.release                    = video_device_release_empty,
1812 	.ioctl_ops 		    = &video_ioctl_ops,
1813 	.tvnorms                    = V4L2_STD_NTSC_M | V4L2_STD_PAL_M,
1814 };
1815 
1816 static int au0828_vb2_setup(struct au0828_dev *dev)
1817 {
1818 	int rc;
1819 	struct vb2_queue *q;
1820 
1821 	/* Setup Videobuf2 for Video capture */
1822 	q = &dev->vb_vidq;
1823 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1824 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1825 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1826 	q->drv_priv = dev;
1827 	q->buf_struct_size = sizeof(struct au0828_buffer);
1828 	q->ops = &au0828_video_qops;
1829 	q->mem_ops = &vb2_vmalloc_memops;
1830 
1831 	rc = vb2_queue_init(q);
1832 	if (rc < 0)
1833 		return rc;
1834 
1835 	/* Setup Videobuf2 for VBI capture */
1836 	q = &dev->vb_vbiq;
1837 	q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
1838 	q->io_modes = VB2_READ | VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1839 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1840 	q->drv_priv = dev;
1841 	q->buf_struct_size = sizeof(struct au0828_buffer);
1842 	q->ops = &au0828_vbi_qops;
1843 	q->mem_ops = &vb2_vmalloc_memops;
1844 
1845 	rc = vb2_queue_init(q);
1846 	if (rc < 0)
1847 		return rc;
1848 
1849 	return 0;
1850 }
1851 
1852 static void au0828_analog_create_entities(struct au0828_dev *dev)
1853 {
1854 #if defined(CONFIG_MEDIA_CONTROLLER)
1855 	static const char * const inames[] = {
1856 		[AU0828_VMUX_COMPOSITE] = "Composite",
1857 		[AU0828_VMUX_SVIDEO] = "S-Video",
1858 		[AU0828_VMUX_CABLE] = "Cable TV",
1859 		[AU0828_VMUX_TELEVISION] = "Television",
1860 		[AU0828_VMUX_DVB] = "DVB",
1861 	};
1862 	int ret, i;
1863 
1864 	/* Initialize Video and VBI pads */
1865 	dev->video_pad.flags = MEDIA_PAD_FL_SINK;
1866 	ret = media_entity_pads_init(&dev->vdev.entity, 1, &dev->video_pad);
1867 	if (ret < 0)
1868 		pr_err("failed to initialize video media entity!\n");
1869 
1870 	dev->vbi_pad.flags = MEDIA_PAD_FL_SINK;
1871 	ret = media_entity_pads_init(&dev->vbi_dev.entity, 1, &dev->vbi_pad);
1872 	if (ret < 0)
1873 		pr_err("failed to initialize vbi media entity!\n");
1874 
1875 	/* Create entities for each input connector */
1876 	for (i = 0; i < AU0828_MAX_INPUT; i++) {
1877 		struct media_entity *ent = &dev->input_ent[i];
1878 
1879 		if (AUVI_INPUT(i).type == AU0828_VMUX_UNDEFINED)
1880 			break;
1881 
1882 		ent->name = inames[AUVI_INPUT(i).type];
1883 		ent->flags = MEDIA_ENT_FL_CONNECTOR;
1884 		dev->input_pad[i].flags = MEDIA_PAD_FL_SOURCE;
1885 
1886 		switch (AUVI_INPUT(i).type) {
1887 		case AU0828_VMUX_COMPOSITE:
1888 			ent->function = MEDIA_ENT_F_CONN_COMPOSITE;
1889 			break;
1890 		case AU0828_VMUX_SVIDEO:
1891 			ent->function = MEDIA_ENT_F_CONN_SVIDEO;
1892 			break;
1893 		case AU0828_VMUX_CABLE:
1894 		case AU0828_VMUX_TELEVISION:
1895 		case AU0828_VMUX_DVB:
1896 		default: /* Just to shut up a warning */
1897 			ent->function = MEDIA_ENT_F_CONN_RF;
1898 			break;
1899 		}
1900 
1901 		ret = media_entity_pads_init(ent, 1, &dev->input_pad[i]);
1902 		if (ret < 0)
1903 			pr_err("failed to initialize input pad[%d]!\n", i);
1904 
1905 		ret = media_device_register_entity(dev->media_dev, ent);
1906 		if (ret < 0)
1907 			pr_err("failed to register input entity %d!\n", i);
1908 	}
1909 #endif
1910 }
1911 
1912 /**************************************************************************/
1913 
1914 int au0828_analog_register(struct au0828_dev *dev,
1915 			   struct usb_interface *interface)
1916 {
1917 	int retval = -ENOMEM;
1918 	struct usb_host_interface *iface_desc;
1919 	struct usb_endpoint_descriptor *endpoint;
1920 	int i, ret;
1921 
1922 	dprintk(1, "au0828_analog_register called for intf#%d!\n",
1923 		interface->cur_altsetting->desc.bInterfaceNumber);
1924 
1925 	/* No analog TV */
1926 	if (AUVI_INPUT(0).type == AU0828_VMUX_UNDEFINED)
1927 		return 0;
1928 
1929 	/* set au0828 usb interface0 to as5 */
1930 	retval = usb_set_interface(dev->usbdev,
1931 			interface->cur_altsetting->desc.bInterfaceNumber, 5);
1932 	if (retval != 0) {
1933 		pr_info("Failure setting usb interface0 to as5\n");
1934 		return retval;
1935 	}
1936 
1937 	/* Figure out which endpoint has the isoc interface */
1938 	iface_desc = interface->cur_altsetting;
1939 	for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
1940 		endpoint = &iface_desc->endpoint[i].desc;
1941 		if (((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
1942 		     == USB_DIR_IN) &&
1943 		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1944 		     == USB_ENDPOINT_XFER_ISOC)) {
1945 
1946 			/* we find our isoc in endpoint */
1947 			u16 tmp = le16_to_cpu(endpoint->wMaxPacketSize);
1948 			dev->max_pkt_size = (tmp & 0x07ff) *
1949 				(((tmp & 0x1800) >> 11) + 1);
1950 			dev->isoc_in_endpointaddr = endpoint->bEndpointAddress;
1951 			dprintk(1,
1952 				"Found isoc endpoint 0x%02x, max size = %d\n",
1953 				dev->isoc_in_endpointaddr, dev->max_pkt_size);
1954 		}
1955 	}
1956 	if (!(dev->isoc_in_endpointaddr)) {
1957 		pr_info("Could not locate isoc endpoint\n");
1958 		return -ENODEV;
1959 	}
1960 
1961 	init_waitqueue_head(&dev->open);
1962 	spin_lock_init(&dev->slock);
1963 
1964 	/* init video dma queues */
1965 	INIT_LIST_HEAD(&dev->vidq.active);
1966 	INIT_LIST_HEAD(&dev->vbiq.active);
1967 
1968 	setup_timer(&dev->vid_timeout, au0828_vid_buffer_timeout,
1969 		    (unsigned long)dev);
1970 	setup_timer(&dev->vbi_timeout, au0828_vbi_buffer_timeout,
1971 		    (unsigned long)dev);
1972 
1973 	dev->width = NTSC_STD_W;
1974 	dev->height = NTSC_STD_H;
1975 	dev->field_size = dev->width * dev->height;
1976 	dev->frame_size = dev->field_size << 1;
1977 	dev->bytesperline = dev->width << 1;
1978 	dev->vbi_width = 720;
1979 	dev->vbi_height = 1;
1980 	dev->ctrl_ainput = 0;
1981 	dev->ctrl_freq = 960;
1982 	dev->std = V4L2_STD_NTSC_M;
1983 	/* Default input is TV Tuner */
1984 	au0828_s_input(dev, 0);
1985 
1986 	mutex_init(&dev->vb_queue_lock);
1987 	mutex_init(&dev->vb_vbi_queue_lock);
1988 
1989 	/* Fill the video capture device struct */
1990 	dev->vdev = au0828_video_template;
1991 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
1992 	dev->vdev.lock = &dev->lock;
1993 	dev->vdev.queue = &dev->vb_vidq;
1994 	dev->vdev.queue->lock = &dev->vb_queue_lock;
1995 	strcpy(dev->vdev.name, "au0828a video");
1996 
1997 	/* Setup the VBI device */
1998 	dev->vbi_dev = au0828_video_template;
1999 	dev->vbi_dev.v4l2_dev = &dev->v4l2_dev;
2000 	dev->vbi_dev.lock = &dev->lock;
2001 	dev->vbi_dev.queue = &dev->vb_vbiq;
2002 	dev->vbi_dev.queue->lock = &dev->vb_vbi_queue_lock;
2003 	strcpy(dev->vbi_dev.name, "au0828a vbi");
2004 
2005 	/* Init entities at the Media Controller */
2006 	au0828_analog_create_entities(dev);
2007 
2008 	/* initialize videobuf2 stuff */
2009 	retval = au0828_vb2_setup(dev);
2010 	if (retval != 0) {
2011 		dprintk(1, "unable to setup videobuf2 queues (error = %d).\n",
2012 			retval);
2013 		return -ENODEV;
2014 	}
2015 
2016 	/* Register the v4l2 device */
2017 	video_set_drvdata(&dev->vdev, dev);
2018 	retval = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
2019 	if (retval != 0) {
2020 		dprintk(1, "unable to register video device (error = %d).\n",
2021 			retval);
2022 		ret = -ENODEV;
2023 		goto err_reg_vdev;
2024 	}
2025 
2026 	/* Register the vbi device */
2027 	video_set_drvdata(&dev->vbi_dev, dev);
2028 	retval = video_register_device(&dev->vbi_dev, VFL_TYPE_VBI, -1);
2029 	if (retval != 0) {
2030 		dprintk(1, "unable to register vbi device (error = %d).\n",
2031 			retval);
2032 		ret = -ENODEV;
2033 		goto err_reg_vbi_dev;
2034 	}
2035 
2036 #ifdef CONFIG_MEDIA_CONTROLLER
2037 	retval = v4l2_mc_create_media_graph(dev->media_dev);
2038 	if (retval) {
2039 		pr_err("%s() au0282_dev_register failed to create graph\n",
2040 			__func__);
2041 		ret = -ENODEV;
2042 		goto err_reg_vbi_dev;
2043 	}
2044 #endif
2045 
2046 	dprintk(1, "%s completed!\n", __func__);
2047 
2048 	return 0;
2049 
2050 err_reg_vbi_dev:
2051 	video_unregister_device(&dev->vdev);
2052 err_reg_vdev:
2053 	vb2_queue_release(&dev->vb_vidq);
2054 	vb2_queue_release(&dev->vb_vbiq);
2055 	return ret;
2056 }
2057 
2058