xref: /linux/drivers/media/usb/dvb-usb/cxusb-analog.c (revision 10a34367ce097d5cd62ea526f5bcc809f99b5eb3)
1 // SPDX-License-Identifier: GPL-2.0+
2 //
3 // DVB USB compliant linux driver for Conexant USB reference design -
4 // (analog part).
5 //
6 // Copyright (C) 2011, 2017, 2018
7 //	Maciej S. Szmigiero (mail@maciej.szmigiero.name)
8 //
9 // In case there are new analog / DVB-T hybrid devices released in the market
10 // using the same general design as Medion MD95700: a CX25840 video decoder
11 // outputting a BT.656 stream to a USB bridge chip which then forwards it to
12 // the host in isochronous USB packets this code should be made generic, with
13 // board specific bits implemented via separate card structures.
14 //
15 // This is, however, unlikely as the Medion model was released
16 // years ago (in 2005).
17 //
18 // TODO:
19 //  * audio support,
20 //  * finish radio support (requires audio of course),
21 //  * VBI support,
22 //  * controls support
23 
24 #include <linux/bitops.h>
25 #include <linux/device.h>
26 #include <linux/slab.h>
27 #include <linux/string.h>
28 #include <linux/timekeeping.h>
29 #include <linux/vmalloc.h>
30 #include <media/drv-intf/cx25840.h>
31 #include <media/tuner.h>
32 #include <media/v4l2-fh.h>
33 #include <media/v4l2-ioctl.h>
34 #include <media/v4l2-subdev.h>
35 #include <media/videobuf2-vmalloc.h>
36 
37 #include "cxusb.h"
38 
39 static int cxusb_medion_v_queue_setup(struct vb2_queue *q,
40 				      unsigned int *num_buffers,
41 				      unsigned int *num_planes,
42 				      unsigned int sizes[],
43 				      struct device *alloc_devs[])
44 {
45 	struct dvb_usb_device *dvbdev = vb2_get_drv_priv(q);
46 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
47 	unsigned int size = cxdev->raw_mode ?
48 		CXUSB_VIDEO_MAX_FRAME_SIZE :
49 		cxdev->width * cxdev->height * 2;
50 
51 	if (*num_planes > 0) {
52 		if (*num_planes != 1)
53 			return -EINVAL;
54 
55 		if (sizes[0] < size)
56 			return -EINVAL;
57 	} else {
58 		*num_planes = 1;
59 		sizes[0] = size;
60 	}
61 
62 	return 0;
63 }
64 
65 static int cxusb_medion_v_buf_init(struct vb2_buffer *vb)
66 {
67 	struct dvb_usb_device *dvbdev = vb2_get_drv_priv(vb->vb2_queue);
68 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
69 
70 	cxusb_vprintk(dvbdev, OPS, "buffer init\n");
71 
72 	if (cxdev->raw_mode) {
73 		if (vb2_plane_size(vb, 0) < CXUSB_VIDEO_MAX_FRAME_SIZE)
74 			return -ENOMEM;
75 	} else {
76 		if (vb2_plane_size(vb, 0) < cxdev->width * cxdev->height * 2)
77 			return -ENOMEM;
78 	}
79 
80 	cxusb_vprintk(dvbdev, OPS, "buffer OK\n");
81 
82 	return 0;
83 }
84 
85 static void cxusb_auxbuf_init(struct dvb_usb_device *dvbdev,
86 			      struct cxusb_medion_auxbuf *auxbuf,
87 			      u8 *buf, unsigned int len)
88 {
89 	cxusb_vprintk(dvbdev, AUXB, "initializing auxbuf of len %u\n", len);
90 
91 	auxbuf->buf = buf;
92 	auxbuf->len = len;
93 	auxbuf->paylen = 0;
94 }
95 
96 static void cxusb_auxbuf_head_trim(struct dvb_usb_device *dvbdev,
97 				   struct cxusb_medion_auxbuf *auxbuf,
98 				   unsigned int pos)
99 {
100 	if (pos == 0)
101 		return;
102 
103 	if (WARN_ON(pos > auxbuf->paylen))
104 		return;
105 
106 	cxusb_vprintk(dvbdev, AUXB,
107 		      "trimming auxbuf len by %u to %u\n",
108 		      pos, auxbuf->paylen - pos);
109 
110 	memmove(auxbuf->buf, auxbuf->buf + pos, auxbuf->paylen - pos);
111 	auxbuf->paylen -= pos;
112 }
113 
114 static unsigned int cxusb_auxbuf_paylen(struct cxusb_medion_auxbuf *auxbuf)
115 {
116 	return auxbuf->paylen;
117 }
118 
119 static bool cxusb_auxbuf_make_space(struct dvb_usb_device *dvbdev,
120 				    struct cxusb_medion_auxbuf *auxbuf,
121 				    unsigned int howmuch)
122 {
123 	unsigned int freespace;
124 
125 	if (WARN_ON(howmuch >= auxbuf->len))
126 		howmuch = auxbuf->len - 1;
127 
128 	freespace = auxbuf->len - cxusb_auxbuf_paylen(auxbuf);
129 
130 	cxusb_vprintk(dvbdev, AUXB, "freespace is %u\n", freespace);
131 
132 	if (freespace >= howmuch)
133 		return true;
134 
135 	howmuch -= freespace;
136 
137 	cxusb_vprintk(dvbdev, AUXB, "will overwrite %u bytes of buffer\n",
138 		      howmuch);
139 
140 	cxusb_auxbuf_head_trim(dvbdev, auxbuf, howmuch);
141 
142 	return false;
143 }
144 
145 /* returns false if some data was overwritten */
146 static bool cxusb_auxbuf_append_urb(struct dvb_usb_device *dvbdev,
147 				    struct cxusb_medion_auxbuf *auxbuf,
148 				    struct urb *urb)
149 {
150 	unsigned long len;
151 	int i;
152 	bool ret;
153 
154 	for (i = 0, len = 0; i < urb->number_of_packets; i++)
155 		len += urb->iso_frame_desc[i].actual_length;
156 
157 	ret = cxusb_auxbuf_make_space(dvbdev, auxbuf, len);
158 
159 	for (i = 0; i < urb->number_of_packets; i++) {
160 		unsigned int to_copy;
161 
162 		to_copy = urb->iso_frame_desc[i].actual_length;
163 
164 		memcpy(auxbuf->buf + auxbuf->paylen, urb->transfer_buffer +
165 		       urb->iso_frame_desc[i].offset, to_copy);
166 
167 		auxbuf->paylen += to_copy;
168 	}
169 
170 	return ret;
171 }
172 
173 static bool cxusb_auxbuf_copy(struct cxusb_medion_auxbuf *auxbuf,
174 			      unsigned int pos, unsigned char *dest,
175 			      unsigned int len)
176 {
177 	if (pos + len > auxbuf->paylen)
178 		return false;
179 
180 	memcpy(dest, auxbuf->buf + pos, len);
181 
182 	return true;
183 }
184 
185 static bool cxusb_medion_cf_refc_fld_chg(struct dvb_usb_device *dvbdev,
186 					 struct cxusb_bt656_params *bt656,
187 					 bool firstfield,
188 					 unsigned int maxlines,
189 					 unsigned int maxlinesamples,
190 					 unsigned char buf[4])
191 {
192 	bool firstfield_code = (buf[3] & CXUSB_BT656_FIELD_MASK) ==
193 		CXUSB_BT656_FIELD_1;
194 	unsigned int remlines;
195 
196 	if (bt656->line == 0 || firstfield == firstfield_code)
197 		return false;
198 
199 	if (bt656->fmode == LINE_SAMPLES) {
200 		unsigned int remsamples = maxlinesamples -
201 			bt656->linesamples;
202 
203 		cxusb_vprintk(dvbdev, BT656,
204 			      "field %c after line %u field change\n",
205 			      firstfield ? '1' : '2', bt656->line);
206 
207 		if (bt656->buf && remsamples > 0) {
208 			memset(bt656->buf, 0, remsamples);
209 			bt656->buf += remsamples;
210 
211 			cxusb_vprintk(dvbdev, BT656,
212 				      "field %c line %u %u samples still remaining (of %u)\n",
213 				      firstfield ? '1' : '2',
214 				      bt656->line, remsamples,
215 				      maxlinesamples);
216 		}
217 
218 		bt656->line++;
219 	}
220 
221 	remlines = maxlines - bt656->line;
222 	if (bt656->buf && remlines > 0) {
223 		memset(bt656->buf, 0, remlines * maxlinesamples);
224 		bt656->buf += remlines * maxlinesamples;
225 
226 		cxusb_vprintk(dvbdev, BT656,
227 			      "field %c %u lines still remaining (of %u)\n",
228 			      firstfield ? '1' : '2', remlines,
229 			      maxlines);
230 	}
231 
232 	return true;
233 }
234 
235 static void cxusb_medion_cf_refc_start_sch(struct dvb_usb_device *dvbdev,
236 					   struct cxusb_bt656_params *bt656,
237 					   bool firstfield,
238 					   unsigned char buf[4])
239 {
240 	bool firstfield_code = (buf[3] & CXUSB_BT656_FIELD_MASK) ==
241 		CXUSB_BT656_FIELD_1;
242 	bool sav_code = (buf[3] & CXUSB_BT656_SEAV_MASK) ==
243 		CXUSB_BT656_SEAV_SAV;
244 	bool vbi_code = (buf[3] & CXUSB_BT656_VBI_MASK) ==
245 		CXUSB_BT656_VBI_ON;
246 
247 	if (!sav_code || firstfield != firstfield_code)
248 		return;
249 
250 	if (!vbi_code) {
251 		cxusb_vprintk(dvbdev, BT656, "line start @ pos %u\n",
252 			      bt656->pos);
253 
254 		bt656->linesamples = 0;
255 		bt656->fmode = LINE_SAMPLES;
256 	} else {
257 		cxusb_vprintk(dvbdev, BT656, "VBI start @ pos %u\n",
258 			      bt656->pos);
259 
260 		bt656->fmode = VBI_SAMPLES;
261 	}
262 }
263 
264 static void cxusb_medion_cf_refc_line_smpl(struct dvb_usb_device *dvbdev,
265 					   struct cxusb_bt656_params *bt656,
266 					   bool firstfield,
267 					   unsigned int maxlinesamples,
268 					   unsigned char buf[4])
269 {
270 	bool sav_code = (buf[3] & CXUSB_BT656_SEAV_MASK) ==
271 		CXUSB_BT656_SEAV_SAV;
272 	unsigned int remsamples;
273 
274 	if (sav_code)
275 		cxusb_vprintk(dvbdev, BT656,
276 			      "SAV in line samples @ line %u, pos %u\n",
277 			      bt656->line, bt656->pos);
278 
279 	remsamples = maxlinesamples - bt656->linesamples;
280 	if (bt656->buf && remsamples > 0) {
281 		memset(bt656->buf, 0, remsamples);
282 		bt656->buf += remsamples;
283 
284 		cxusb_vprintk(dvbdev, BT656,
285 			      "field %c line %u %u samples still remaining (of %u)\n",
286 			      firstfield ? '1' : '2', bt656->line, remsamples,
287 			      maxlinesamples);
288 	}
289 
290 	bt656->fmode = START_SEARCH;
291 	bt656->line++;
292 }
293 
294 static void cxusb_medion_cf_refc_vbi_smpl(struct dvb_usb_device *dvbdev,
295 					  struct cxusb_bt656_params *bt656,
296 					  unsigned char buf[4])
297 {
298 	bool sav_code = (buf[3] & CXUSB_BT656_SEAV_MASK) ==
299 		CXUSB_BT656_SEAV_SAV;
300 
301 	if (sav_code)
302 		cxusb_vprintk(dvbdev, BT656, "SAV in VBI samples @ pos %u\n",
303 			      bt656->pos);
304 
305 	bt656->fmode = START_SEARCH;
306 }
307 
308 /* returns whether the whole 4-byte code should be skipped in the buffer */
309 static bool cxusb_medion_cf_ref_code(struct dvb_usb_device *dvbdev,
310 				     struct cxusb_bt656_params *bt656,
311 				     bool firstfield,
312 				     unsigned int maxlines,
313 				     unsigned int maxlinesamples,
314 				     unsigned char buf[4])
315 {
316 	if (bt656->fmode == START_SEARCH) {
317 		cxusb_medion_cf_refc_start_sch(dvbdev, bt656, firstfield, buf);
318 	} else if (bt656->fmode == LINE_SAMPLES) {
319 		cxusb_medion_cf_refc_line_smpl(dvbdev, bt656, firstfield,
320 					       maxlinesamples, buf);
321 		return false;
322 	} else if (bt656->fmode == VBI_SAMPLES) {
323 		cxusb_medion_cf_refc_vbi_smpl(dvbdev, bt656, buf);
324 		return false;
325 	}
326 
327 	return true;
328 }
329 
330 static bool cxusb_medion_cs_start_sch(struct dvb_usb_device *dvbdev,
331 				      struct cxusb_medion_auxbuf *auxbuf,
332 				      struct cxusb_bt656_params *bt656,
333 				      unsigned int maxlinesamples)
334 {
335 	unsigned char buf[64];
336 	unsigned int idx;
337 	unsigned int tocheck = clamp_t(size_t, maxlinesamples / 4, 3,
338 				       sizeof(buf));
339 
340 	if (!cxusb_auxbuf_copy(auxbuf, bt656->pos + 1, buf, tocheck))
341 		return false;
342 
343 	for (idx = 0; idx <= tocheck - 3; idx++)
344 		if (memcmp(buf + idx, CXUSB_BT656_PREAMBLE, 3) == 0) {
345 			bt656->pos += (1 + idx);
346 			return true;
347 		}
348 
349 	cxusb_vprintk(dvbdev, BT656, "line %u early start, pos %u\n",
350 		      bt656->line, bt656->pos);
351 
352 	bt656->linesamples = 0;
353 	bt656->fmode = LINE_SAMPLES;
354 
355 	return true;
356 }
357 
358 static void cxusb_medion_cs_line_smpl(struct cxusb_bt656_params *bt656,
359 				      unsigned int maxlinesamples,
360 				      unsigned char val)
361 {
362 	if (bt656->buf)
363 		*(bt656->buf++) = val;
364 
365 	bt656->linesamples++;
366 	bt656->pos++;
367 
368 	if (bt656->linesamples >= maxlinesamples) {
369 		bt656->fmode = START_SEARCH;
370 		bt656->line++;
371 	}
372 }
373 
374 static bool cxusb_medion_copy_samples(struct dvb_usb_device *dvbdev,
375 				      struct cxusb_medion_auxbuf *auxbuf,
376 				      struct cxusb_bt656_params *bt656,
377 				      unsigned int maxlinesamples,
378 				      unsigned char val)
379 {
380 	if (bt656->fmode == START_SEARCH && bt656->line > 0)
381 		return cxusb_medion_cs_start_sch(dvbdev, auxbuf, bt656,
382 						 maxlinesamples);
383 	else if (bt656->fmode == LINE_SAMPLES)
384 		cxusb_medion_cs_line_smpl(bt656, maxlinesamples, val);
385 	else /* TODO: copy VBI samples */
386 		bt656->pos++;
387 
388 	return true;
389 }
390 
391 static bool cxusb_medion_copy_field(struct dvb_usb_device *dvbdev,
392 				    struct cxusb_medion_auxbuf *auxbuf,
393 				    struct cxusb_bt656_params *bt656,
394 				    bool firstfield,
395 				    unsigned int maxlines,
396 				    unsigned int maxlinesmpls)
397 {
398 	while (bt656->line < maxlines) {
399 		unsigned char val;
400 
401 		if (!cxusb_auxbuf_copy(auxbuf, bt656->pos, &val, 1))
402 			break;
403 
404 		if (val == CXUSB_BT656_PREAMBLE[0]) {
405 			unsigned char buf[4];
406 
407 			buf[0] = val;
408 			if (!cxusb_auxbuf_copy(auxbuf, bt656->pos + 1,
409 					       buf + 1, 3))
410 				break;
411 
412 			if (buf[1] == CXUSB_BT656_PREAMBLE[1] &&
413 			    buf[2] == CXUSB_BT656_PREAMBLE[2]) {
414 				/*
415 				 * is this a field change?
416 				 * if so, terminate copying the current field
417 				 */
418 				if (cxusb_medion_cf_refc_fld_chg(dvbdev,
419 								 bt656,
420 								 firstfield,
421 								 maxlines,
422 								 maxlinesmpls,
423 								 buf))
424 					return true;
425 
426 				if (cxusb_medion_cf_ref_code(dvbdev, bt656,
427 							     firstfield,
428 							     maxlines,
429 							     maxlinesmpls,
430 							     buf))
431 					bt656->pos += 4;
432 
433 				continue;
434 			}
435 		}
436 
437 		if (!cxusb_medion_copy_samples(dvbdev, auxbuf, bt656,
438 					       maxlinesmpls, val))
439 			break;
440 	}
441 
442 	if (bt656->line < maxlines) {
443 		cxusb_vprintk(dvbdev, BT656,
444 			      "end of buffer pos = %u, line = %u\n",
445 			      bt656->pos, bt656->line);
446 		return false;
447 	}
448 
449 	return true;
450 }
451 
452 static void cxusb_medion_v_process_urb_raw(struct cxusb_medion_dev *cxdev,
453 					   struct urb *urb)
454 {
455 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
456 	u8 *buf;
457 	struct cxusb_medion_vbuffer *vbuf;
458 	int i;
459 	unsigned long len;
460 
461 	if (list_empty(&cxdev->buflist)) {
462 		dev_warn(&dvbdev->udev->dev, "no free buffers\n");
463 		cxdev->vbuf_sequence++;
464 		return;
465 	}
466 
467 	vbuf = list_first_entry(&cxdev->buflist, struct cxusb_medion_vbuffer,
468 				list);
469 	list_del(&vbuf->list);
470 
471 	vbuf->vb2.field = V4L2_FIELD_NONE;
472 	vbuf->vb2.sequence = cxdev->vbuf_sequence++;
473 	vbuf->vb2.vb2_buf.timestamp = ktime_get_ns();
474 
475 	buf = vb2_plane_vaddr(&vbuf->vb2.vb2_buf, 0);
476 
477 	for (i = 0, len = 0; i < urb->number_of_packets; i++) {
478 		memcpy(buf, urb->transfer_buffer +
479 		       urb->iso_frame_desc[i].offset,
480 		       urb->iso_frame_desc[i].actual_length);
481 
482 		buf += urb->iso_frame_desc[i].actual_length;
483 		len += urb->iso_frame_desc[i].actual_length;
484 	}
485 
486 	vb2_set_plane_payload(&vbuf->vb2.vb2_buf, 0, len);
487 
488 	vb2_buffer_done(&vbuf->vb2.vb2_buf, VB2_BUF_STATE_DONE);
489 }
490 
491 static bool cxusb_medion_v_process_auxbuf(struct cxusb_medion_dev *cxdev,
492 					  bool reset)
493 {
494 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
495 	struct cxusb_bt656_params *bt656 = &cxdev->bt656;
496 
497 	/*
498 	 * if this is a new frame
499 	 * fetch a buffer from list
500 	 */
501 	if (bt656->mode == NEW_FRAME) {
502 		if (!list_empty(&cxdev->buflist)) {
503 			cxdev->vbuf =
504 				list_first_entry(&cxdev->buflist,
505 						 struct cxusb_medion_vbuffer,
506 						 list);
507 			list_del(&cxdev->vbuf->list);
508 		} else {
509 			dev_warn(&dvbdev->udev->dev, "no free buffers\n");
510 		}
511 	}
512 
513 	if (bt656->mode == NEW_FRAME || reset) {
514 		cxusb_vprintk(dvbdev, URB, "will copy field 1\n");
515 		bt656->pos = 0;
516 		bt656->mode = FIRST_FIELD;
517 		bt656->fmode = START_SEARCH;
518 		bt656->line = 0;
519 
520 		if (cxdev->vbuf) {
521 			cxdev->vbuf->vb2.vb2_buf.timestamp = ktime_get_ns();
522 			bt656->buf = vb2_plane_vaddr(&cxdev->vbuf->vb2.vb2_buf,
523 						     0);
524 		}
525 	}
526 
527 	if (bt656->mode == FIRST_FIELD) {
528 		if (!cxusb_medion_copy_field(dvbdev, &cxdev->auxbuf, bt656,
529 					     true, cxdev->height / 2,
530 					     cxdev->width * 2))
531 			return false;
532 
533 		/*
534 		 * do not trim buffer there in case
535 		 * we need to reset the search later
536 		 */
537 
538 		cxusb_vprintk(dvbdev, URB, "will copy field 2\n");
539 		bt656->mode = SECOND_FIELD;
540 		bt656->fmode = START_SEARCH;
541 		bt656->line = 0;
542 	}
543 
544 	if (bt656->mode == SECOND_FIELD) {
545 		if (!cxusb_medion_copy_field(dvbdev, &cxdev->auxbuf, bt656,
546 					     false, cxdev->height / 2,
547 					     cxdev->width * 2))
548 			return false;
549 
550 		cxusb_auxbuf_head_trim(dvbdev, &cxdev->auxbuf, bt656->pos);
551 
552 		bt656->mode = NEW_FRAME;
553 
554 		if (cxdev->vbuf) {
555 			vb2_set_plane_payload(&cxdev->vbuf->vb2.vb2_buf, 0,
556 					      cxdev->width * cxdev->height * 2);
557 
558 			cxdev->vbuf->vb2.field = cxdev->field_order;
559 			cxdev->vbuf->vb2.sequence = cxdev->vbuf_sequence++;
560 
561 			vb2_buffer_done(&cxdev->vbuf->vb2.vb2_buf,
562 					VB2_BUF_STATE_DONE);
563 
564 			cxdev->vbuf = NULL;
565 			cxdev->bt656.buf = NULL;
566 
567 			cxusb_vprintk(dvbdev, URB, "frame done\n");
568 		} else {
569 			cxusb_vprintk(dvbdev, URB, "frame skipped\n");
570 			cxdev->vbuf_sequence++;
571 		}
572 	}
573 
574 	return true;
575 }
576 
577 static bool cxusb_medion_v_complete_handle_urb(struct cxusb_medion_dev *cxdev,
578 					       bool *auxbuf_reset)
579 {
580 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
581 	unsigned int urbn;
582 	struct urb *urb;
583 	int ret;
584 
585 	*auxbuf_reset = false;
586 
587 	urbn = cxdev->nexturb;
588 	if (!test_bit(urbn, &cxdev->urbcomplete))
589 		return false;
590 
591 	clear_bit(urbn, &cxdev->urbcomplete);
592 
593 	do {
594 		cxdev->nexturb++;
595 		cxdev->nexturb %= CXUSB_VIDEO_URBS;
596 		urb = cxdev->streamurbs[cxdev->nexturb];
597 	} while (!urb);
598 
599 	urb = cxdev->streamurbs[urbn];
600 	cxusb_vprintk(dvbdev, URB, "URB %u status = %d\n", urbn, urb->status);
601 
602 	if (urb->status == 0 || urb->status == -EXDEV) {
603 		int i;
604 		unsigned long len;
605 
606 		for (i = 0, len = 0; i < urb->number_of_packets; i++)
607 			len += urb->iso_frame_desc[i].actual_length;
608 
609 		cxusb_vprintk(dvbdev, URB, "URB %u data len = %lu\n", urbn,
610 			      len);
611 
612 		if (len > 0) {
613 			if (cxdev->raw_mode) {
614 				cxusb_medion_v_process_urb_raw(cxdev, urb);
615 			} else {
616 				cxusb_vprintk(dvbdev, URB, "appending URB\n");
617 
618 				/*
619 				 * append new data to auxbuf while
620 				 * overwriting old data if necessary
621 				 *
622 				 * if any overwrite happens then we can no
623 				 * longer rely on consistency of the whole
624 				 * data so let's start again the current
625 				 * auxbuf frame assembling process from
626 				 * the beginning
627 				 */
628 				*auxbuf_reset =
629 					!cxusb_auxbuf_append_urb(dvbdev,
630 								 &cxdev->auxbuf,
631 								 urb);
632 			}
633 		}
634 	}
635 
636 	cxusb_vprintk(dvbdev, URB, "URB %u resubmit\n", urbn);
637 
638 	ret = usb_submit_urb(urb, GFP_KERNEL);
639 	if (ret != 0)
640 		dev_err(&dvbdev->udev->dev,
641 			"unable to resubmit URB %u (%d), you'll have to restart streaming\n",
642 			urbn, ret);
643 
644 	/* next URB is complete already? reschedule us then to handle it */
645 	return test_bit(cxdev->nexturb, &cxdev->urbcomplete);
646 }
647 
648 static void cxusb_medion_v_complete_work(struct work_struct *work)
649 {
650 	struct cxusb_medion_dev *cxdev = container_of(work,
651 						      struct cxusb_medion_dev,
652 						      urbwork);
653 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
654 	bool auxbuf_reset;
655 	bool reschedule;
656 
657 	mutex_lock(cxdev->videodev->lock);
658 
659 	cxusb_vprintk(dvbdev, URB, "worker called, stop_streaming = %d\n",
660 		      (int)cxdev->stop_streaming);
661 
662 	if (cxdev->stop_streaming)
663 		goto unlock;
664 
665 	reschedule = cxusb_medion_v_complete_handle_urb(cxdev, &auxbuf_reset);
666 
667 	if (!cxdev->raw_mode && cxusb_medion_v_process_auxbuf(cxdev,
668 							      auxbuf_reset))
669 		/* reschedule us until auxbuf no longer can produce any frame */
670 		reschedule = true;
671 
672 	if (reschedule) {
673 		cxusb_vprintk(dvbdev, URB, "rescheduling worker\n");
674 		schedule_work(&cxdev->urbwork);
675 	}
676 
677 unlock:
678 	mutex_unlock(cxdev->videodev->lock);
679 }
680 
681 static void cxusb_medion_v_complete(struct urb *u)
682 {
683 	struct dvb_usb_device *dvbdev = u->context;
684 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
685 	unsigned int i;
686 
687 	for (i = 0; i < CXUSB_VIDEO_URBS; i++)
688 		if (cxdev->streamurbs[i] == u)
689 			break;
690 
691 	if (i >= CXUSB_VIDEO_URBS) {
692 		dev_err(&dvbdev->udev->dev,
693 			"complete on unknown URB\n");
694 		return;
695 	}
696 
697 	cxusb_vprintk(dvbdev, URB, "URB %u complete\n", i);
698 
699 	set_bit(i, &cxdev->urbcomplete);
700 	schedule_work(&cxdev->urbwork);
701 }
702 
703 static void cxusb_medion_urbs_free(struct cxusb_medion_dev *cxdev)
704 {
705 	unsigned int i;
706 
707 	for (i = 0; i < CXUSB_VIDEO_URBS; i++)
708 		if (cxdev->streamurbs[i]) {
709 			kfree(cxdev->streamurbs[i]->transfer_buffer);
710 			usb_free_urb(cxdev->streamurbs[i]);
711 			cxdev->streamurbs[i] = NULL;
712 		}
713 }
714 
715 static void cxusb_medion_return_buffers(struct cxusb_medion_dev *cxdev,
716 					bool requeue)
717 {
718 	struct cxusb_medion_vbuffer *vbuf, *vbuf_tmp;
719 
720 	list_for_each_entry_safe(vbuf, vbuf_tmp, &cxdev->buflist,
721 				 list) {
722 		list_del(&vbuf->list);
723 		vb2_buffer_done(&vbuf->vb2.vb2_buf,
724 				requeue ? VB2_BUF_STATE_QUEUED :
725 				VB2_BUF_STATE_ERROR);
726 	}
727 
728 	if (cxdev->vbuf) {
729 		vb2_buffer_done(&cxdev->vbuf->vb2.vb2_buf,
730 				requeue ? VB2_BUF_STATE_QUEUED :
731 				VB2_BUF_STATE_ERROR);
732 
733 		cxdev->vbuf = NULL;
734 		cxdev->bt656.buf = NULL;
735 	}
736 }
737 
738 static int cxusb_medion_v_ss_auxbuf_alloc(struct cxusb_medion_dev *cxdev,
739 					  int *npackets)
740 {
741 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
742 	u8 *buf;
743 	unsigned int framelen, urblen, auxbuflen;
744 
745 	framelen = (cxdev->width * 2 + 4 + 4) *
746 		(cxdev->height + 50 /* VBI lines */);
747 
748 	/*
749 	 * try to fit a whole frame into each URB, as long as doing so
750 	 * does not require very high order memory allocations
751 	 */
752 	BUILD_BUG_ON(CXUSB_VIDEO_URB_MAX_SIZE / CXUSB_VIDEO_PKT_SIZE >
753 		     CXUSB_VIDEO_MAX_FRAME_PKTS);
754 	*npackets = min_t(int, (framelen + CXUSB_VIDEO_PKT_SIZE - 1) /
755 			  CXUSB_VIDEO_PKT_SIZE,
756 			  CXUSB_VIDEO_URB_MAX_SIZE / CXUSB_VIDEO_PKT_SIZE);
757 	urblen = *npackets * CXUSB_VIDEO_PKT_SIZE;
758 
759 	cxusb_vprintk(dvbdev, URB,
760 		      "each URB will have %d packets for total of %u bytes (%u x %u @ %u)\n",
761 		      *npackets, urblen, (unsigned int)cxdev->width,
762 		      (unsigned int)cxdev->height, framelen);
763 
764 	auxbuflen = framelen + urblen;
765 
766 	buf = vmalloc(auxbuflen);
767 	if (!buf)
768 		return -ENOMEM;
769 
770 	cxusb_auxbuf_init(dvbdev, &cxdev->auxbuf, buf, auxbuflen);
771 
772 	return 0;
773 }
774 
775 static u32 cxusb_medion_norm2field_order(v4l2_std_id norm)
776 {
777 	bool is625 = norm & V4L2_STD_625_50;
778 	bool is525 = norm & V4L2_STD_525_60;
779 
780 	if (!is625 && !is525)
781 		return V4L2_FIELD_NONE;
782 
783 	if (is625 && is525)
784 		return V4L2_FIELD_NONE;
785 
786 	if (is625)
787 		return V4L2_FIELD_SEQ_TB;
788 	else /* is525 */
789 		return V4L2_FIELD_SEQ_BT;
790 }
791 
792 static u32 cxusb_medion_field_order(struct cxusb_medion_dev *cxdev)
793 {
794 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
795 	u32 field;
796 	int ret;
797 	v4l2_std_id norm;
798 
799 	/* TV tuner is PAL-only so it is always TB */
800 	if (cxdev->input == 0)
801 		return V4L2_FIELD_SEQ_TB;
802 
803 	field = cxusb_medion_norm2field_order(cxdev->norm);
804 	if (field != V4L2_FIELD_NONE)
805 		return field;
806 
807 	ret = v4l2_subdev_call(cxdev->cx25840, video, g_std, &norm);
808 	if (ret != 0) {
809 		cxusb_vprintk(dvbdev, OPS,
810 			      "cannot get current standard for input %u\n",
811 			      (unsigned int)cxdev->input);
812 	} else {
813 		field = cxusb_medion_norm2field_order(norm);
814 		if (field != V4L2_FIELD_NONE)
815 			return field;
816 	}
817 
818 	dev_warn(&dvbdev->udev->dev,
819 		 "cannot determine field order for the current standard setup and received signal, using TB\n");
820 	return V4L2_FIELD_SEQ_TB;
821 }
822 
823 static int cxusb_medion_v_start_streaming(struct vb2_queue *q,
824 					  unsigned int count)
825 {
826 	struct dvb_usb_device *dvbdev = vb2_get_drv_priv(q);
827 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
828 	u8 streamon_params[2] = { 0x03, 0x00 };
829 	int npackets, i;
830 	int ret;
831 
832 	cxusb_vprintk(dvbdev, OPS, "should start streaming\n");
833 
834 	if (cxdev->stop_streaming) {
835 		/* stream is being stopped */
836 		ret = -EBUSY;
837 		goto ret_retbufs;
838 	}
839 
840 	cxdev->field_order = cxusb_medion_field_order(cxdev);
841 
842 	ret = v4l2_subdev_call(cxdev->cx25840, video, s_stream, 1);
843 	if (ret != 0) {
844 		dev_err(&dvbdev->udev->dev,
845 			"unable to start stream (%d)\n", ret);
846 		goto ret_retbufs;
847 	}
848 
849 	ret = cxusb_ctrl_msg(dvbdev, CMD_STREAMING_ON, streamon_params, 2,
850 			     NULL, 0);
851 	if (ret != 0) {
852 		dev_err(&dvbdev->udev->dev,
853 			"unable to start streaming (%d)\n", ret);
854 		goto ret_unstream_cx;
855 	}
856 
857 	if (cxdev->raw_mode) {
858 		npackets = CXUSB_VIDEO_MAX_FRAME_PKTS;
859 	} else {
860 		ret = cxusb_medion_v_ss_auxbuf_alloc(cxdev, &npackets);
861 		if (ret != 0)
862 			goto ret_unstream_md;
863 	}
864 
865 	for (i = 0; i < CXUSB_VIDEO_URBS; i++) {
866 		int framen;
867 		u8 *streambuf;
868 		struct urb *surb;
869 
870 		/*
871 		 * TODO: change this to an array of single pages to avoid
872 		 * doing a large continuous allocation when (if)
873 		 * s-g isochronous USB transfers are supported
874 		 */
875 		streambuf = kmalloc(npackets * CXUSB_VIDEO_PKT_SIZE,
876 				    GFP_KERNEL);
877 		if (!streambuf) {
878 			if (i < 2) {
879 				ret = -ENOMEM;
880 				goto ret_freeab;
881 			}
882 			break;
883 		}
884 
885 		surb = usb_alloc_urb(npackets, GFP_KERNEL);
886 		if (!surb) {
887 			kfree(streambuf);
888 			ret = -ENOMEM;
889 			goto ret_freeu;
890 		}
891 
892 		cxdev->streamurbs[i] = surb;
893 		surb->dev = dvbdev->udev;
894 		surb->context = dvbdev;
895 		surb->pipe = usb_rcvisocpipe(dvbdev->udev, 2);
896 
897 		surb->interval = 1;
898 		surb->transfer_flags = URB_ISO_ASAP;
899 
900 		surb->transfer_buffer = streambuf;
901 
902 		surb->complete = cxusb_medion_v_complete;
903 		surb->number_of_packets = npackets;
904 		surb->transfer_buffer_length = npackets * CXUSB_VIDEO_PKT_SIZE;
905 
906 		for (framen = 0; framen < npackets; framen++) {
907 			surb->iso_frame_desc[framen].offset =
908 				CXUSB_VIDEO_PKT_SIZE * framen;
909 
910 			surb->iso_frame_desc[framen].length =
911 				CXUSB_VIDEO_PKT_SIZE;
912 		}
913 	}
914 
915 	cxdev->urbcomplete = 0;
916 	cxdev->nexturb = 0;
917 	cxdev->vbuf_sequence = 0;
918 
919 	if (!cxdev->raw_mode) {
920 		cxdev->vbuf = NULL;
921 		cxdev->bt656.mode = NEW_FRAME;
922 		cxdev->bt656.buf = NULL;
923 	}
924 
925 	for (i = 0; i < CXUSB_VIDEO_URBS; i++)
926 		if (cxdev->streamurbs[i]) {
927 			ret = usb_submit_urb(cxdev->streamurbs[i],
928 					     GFP_KERNEL);
929 			if (ret != 0)
930 				dev_err(&dvbdev->udev->dev,
931 					"URB %d submission failed (%d)\n", i,
932 					ret);
933 		}
934 
935 	return 0;
936 
937 ret_freeu:
938 	cxusb_medion_urbs_free(cxdev);
939 
940 ret_freeab:
941 	if (!cxdev->raw_mode)
942 		vfree(cxdev->auxbuf.buf);
943 
944 ret_unstream_md:
945 	cxusb_ctrl_msg(dvbdev, CMD_STREAMING_OFF, NULL, 0, NULL, 0);
946 
947 ret_unstream_cx:
948 	v4l2_subdev_call(cxdev->cx25840, video, s_stream, 0);
949 
950 ret_retbufs:
951 	cxusb_medion_return_buffers(cxdev, true);
952 
953 	return ret;
954 }
955 
956 static void cxusb_medion_v_stop_streaming(struct vb2_queue *q)
957 {
958 	struct dvb_usb_device *dvbdev = vb2_get_drv_priv(q);
959 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
960 	int ret;
961 	unsigned int i;
962 
963 	cxusb_vprintk(dvbdev, OPS, "should stop streaming\n");
964 
965 	if (WARN_ON(cxdev->stop_streaming))
966 		return;
967 
968 	cxdev->stop_streaming = true;
969 
970 	cxusb_ctrl_msg(dvbdev, CMD_STREAMING_OFF, NULL, 0, NULL, 0);
971 
972 	ret = v4l2_subdev_call(cxdev->cx25840, video, s_stream, 0);
973 	if (ret != 0)
974 		dev_err(&dvbdev->udev->dev, "unable to stop stream (%d)\n",
975 			ret);
976 
977 	/* let URB completion run */
978 	mutex_unlock(cxdev->videodev->lock);
979 
980 	for (i = 0; i < CXUSB_VIDEO_URBS; i++)
981 		if (cxdev->streamurbs[i])
982 			usb_kill_urb(cxdev->streamurbs[i]);
983 
984 	flush_work(&cxdev->urbwork);
985 
986 	mutex_lock(cxdev->videodev->lock);
987 
988 	/* free transfer buffer and URB */
989 	if (!cxdev->raw_mode)
990 		vfree(cxdev->auxbuf.buf);
991 
992 	cxusb_medion_urbs_free(cxdev);
993 
994 	cxusb_medion_return_buffers(cxdev, false);
995 
996 	cxdev->stop_streaming = false;
997 }
998 
999 static void cxusub_medion_v_buf_queue(struct vb2_buffer *vb)
1000 {
1001 	struct vb2_v4l2_buffer *v4l2buf = to_vb2_v4l2_buffer(vb);
1002 	struct cxusb_medion_vbuffer *vbuf =
1003 		container_of(v4l2buf, struct cxusb_medion_vbuffer, vb2);
1004 	struct dvb_usb_device *dvbdev = vb2_get_drv_priv(vb->vb2_queue);
1005 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1006 
1007 	/* cxusb_vprintk(dvbdev, OPS, "mmmm.. a fresh buffer...\n"); */
1008 
1009 	list_add_tail(&vbuf->list, &cxdev->buflist);
1010 }
1011 
1012 static const struct vb2_ops cxdev_video_qops = {
1013 	.queue_setup = cxusb_medion_v_queue_setup,
1014 	.buf_init = cxusb_medion_v_buf_init,
1015 	.start_streaming = cxusb_medion_v_start_streaming,
1016 	.stop_streaming = cxusb_medion_v_stop_streaming,
1017 	.buf_queue = cxusub_medion_v_buf_queue,
1018 	.wait_prepare = vb2_ops_wait_prepare,
1019 	.wait_finish = vb2_ops_wait_finish
1020 };
1021 
1022 static const __u32 videocaps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TUNER |
1023 	V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1024 static const __u32 radiocaps = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
1025 
1026 static int cxusb_medion_v_querycap(struct file *file, void *fh,
1027 				   struct v4l2_capability *cap)
1028 {
1029 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1030 
1031 	strscpy(cap->driver, dvbdev->udev->dev.driver->name,
1032 		sizeof(cap->driver));
1033 	strscpy(cap->card, "Medion 95700", sizeof(cap->card));
1034 	usb_make_path(dvbdev->udev, cap->bus_info, sizeof(cap->bus_info));
1035 
1036 	cap->capabilities = videocaps | radiocaps | V4L2_CAP_DEVICE_CAPS;
1037 
1038 	return 0;
1039 }
1040 
1041 static int cxusb_medion_v_enum_fmt_vid_cap(struct file *file, void *fh,
1042 					   struct v4l2_fmtdesc *f)
1043 {
1044 	if (f->index != 0)
1045 		return -EINVAL;
1046 
1047 	f->pixelformat = V4L2_PIX_FMT_UYVY;
1048 
1049 	return 0;
1050 }
1051 
1052 static int cxusb_medion_g_fmt_vid_cap(struct file *file, void *fh,
1053 				      struct v4l2_format *f)
1054 {
1055 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1056 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1057 
1058 	f->fmt.pix.width = cxdev->width;
1059 	f->fmt.pix.height = cxdev->height;
1060 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1061 	f->fmt.pix.field = vb2_start_streaming_called(&cxdev->videoqueue) ?
1062 		cxdev->field_order : cxusb_medion_field_order(cxdev);
1063 	f->fmt.pix.bytesperline = cxdev->raw_mode ? 0 : cxdev->width * 2;
1064 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1065 	f->fmt.pix.sizeimage =
1066 		cxdev->raw_mode ? CXUSB_VIDEO_MAX_FRAME_SIZE :
1067 		f->fmt.pix.bytesperline * f->fmt.pix.height;
1068 
1069 	return 0;
1070 }
1071 
1072 static int cxusb_medion_try_s_fmt_vid_cap(struct file *file,
1073 					  struct v4l2_format *f,
1074 					  bool isset)
1075 {
1076 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1077 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1078 	struct v4l2_subdev_format subfmt;
1079 	u32 field;
1080 	int ret;
1081 
1082 	if (isset && vb2_is_busy(&cxdev->videoqueue))
1083 		return -EBUSY;
1084 
1085 	field = vb2_start_streaming_called(&cxdev->videoqueue) ?
1086 		cxdev->field_order : cxusb_medion_field_order(cxdev);
1087 
1088 	memset(&subfmt, 0, sizeof(subfmt));
1089 	subfmt.which = isset ? V4L2_SUBDEV_FORMAT_ACTIVE :
1090 		V4L2_SUBDEV_FORMAT_TRY;
1091 	subfmt.format.width = f->fmt.pix.width & ~1;
1092 	subfmt.format.height = f->fmt.pix.height & ~1;
1093 	subfmt.format.code = MEDIA_BUS_FMT_FIXED;
1094 	subfmt.format.field = field;
1095 	subfmt.format.colorspace = V4L2_COLORSPACE_SMPTE170M;
1096 
1097 	ret = v4l2_subdev_call(cxdev->cx25840, pad, set_fmt, NULL, &subfmt);
1098 	if (ret != 0)
1099 		return ret;
1100 
1101 	f->fmt.pix.width = subfmt.format.width;
1102 	f->fmt.pix.height = subfmt.format.height;
1103 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;
1104 	f->fmt.pix.field = field;
1105 	f->fmt.pix.bytesperline = cxdev->raw_mode ? 0 : f->fmt.pix.width * 2;
1106 	f->fmt.pix.sizeimage =
1107 		cxdev->raw_mode ? CXUSB_VIDEO_MAX_FRAME_SIZE :
1108 		f->fmt.pix.bytesperline * f->fmt.pix.height;
1109 	f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1110 
1111 	if (isset) {
1112 		cxdev->width = f->fmt.pix.width;
1113 		cxdev->height = f->fmt.pix.height;
1114 	}
1115 
1116 	return 0;
1117 }
1118 
1119 static int cxusb_medion_try_fmt_vid_cap(struct file *file, void *fh,
1120 					struct v4l2_format *f)
1121 {
1122 	return cxusb_medion_try_s_fmt_vid_cap(file, f, false);
1123 }
1124 
1125 static int cxusb_medion_s_fmt_vid_cap(struct file *file, void *fh,
1126 				      struct v4l2_format *f)
1127 {
1128 	return cxusb_medion_try_s_fmt_vid_cap(file, f, true);
1129 }
1130 
1131 static const struct {
1132 	struct v4l2_input input;
1133 	u32 inputcfg;
1134 } cxusb_medion_inputs[] = {
1135 	{ .input = { .name = "TV tuner", .type = V4L2_INPUT_TYPE_TUNER,
1136 		     .tuner = 0, .std = V4L2_STD_PAL },
1137 	  .inputcfg = CX25840_COMPOSITE2, },
1138 
1139 	{  .input = { .name = "Composite", .type = V4L2_INPUT_TYPE_CAMERA,
1140 		     .std = V4L2_STD_ALL },
1141 	   .inputcfg = CX25840_COMPOSITE1, },
1142 
1143 	{  .input = { .name = "S-Video", .type = V4L2_INPUT_TYPE_CAMERA,
1144 		      .std = V4L2_STD_ALL },
1145 	   .inputcfg = CX25840_SVIDEO_LUMA3 | CX25840_SVIDEO_CHROMA4 }
1146 };
1147 
1148 #define CXUSB_INPUT_CNT ARRAY_SIZE(cxusb_medion_inputs)
1149 
1150 static int cxusb_medion_enum_input(struct file *file, void *fh,
1151 				   struct v4l2_input *inp)
1152 {
1153 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1154 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1155 	u32 index = inp->index;
1156 
1157 	if (index >= CXUSB_INPUT_CNT)
1158 		return -EINVAL;
1159 
1160 	*inp = cxusb_medion_inputs[index].input;
1161 	inp->index = index;
1162 	inp->capabilities |= V4L2_IN_CAP_STD;
1163 
1164 	if (index == cxdev->input) {
1165 		int ret;
1166 		u32 status = 0;
1167 
1168 		ret = v4l2_subdev_call(cxdev->cx25840, video, g_input_status,
1169 				       &status);
1170 		if (ret != 0)
1171 			dev_warn(&dvbdev->udev->dev,
1172 				 "cx25840 input status query failed (%d)\n",
1173 				 ret);
1174 		else
1175 			inp->status = status;
1176 	}
1177 
1178 	return 0;
1179 }
1180 
1181 static int cxusb_medion_g_input(struct file *file, void *fh,
1182 				unsigned int *i)
1183 {
1184 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1185 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1186 
1187 	*i = cxdev->input;
1188 
1189 	return 0;
1190 }
1191 
1192 static int cxusb_medion_set_norm(struct cxusb_medion_dev *cxdev,
1193 				 v4l2_std_id norm)
1194 {
1195 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
1196 	int ret;
1197 
1198 	cxusb_vprintk(dvbdev, OPS,
1199 		      "trying to set standard for input %u to %lx\n",
1200 		      (unsigned int)cxdev->input,
1201 		      (unsigned long)norm);
1202 
1203 	/* no autodetection support */
1204 	if (norm == V4L2_STD_UNKNOWN)
1205 		return -EINVAL;
1206 
1207 	/* on composite or S-Video any std is acceptable */
1208 	if (cxdev->input != 0) {
1209 		ret = v4l2_subdev_call(cxdev->cx25840, video, s_std, norm);
1210 		if (ret)
1211 			return ret;
1212 
1213 		goto ret_savenorm;
1214 	}
1215 
1216 	/* TV tuner is only able to demodulate PAL */
1217 	if ((norm & ~V4L2_STD_PAL) != 0)
1218 		return -EINVAL;
1219 
1220 	ret = v4l2_subdev_call(cxdev->tda9887, video, s_std, norm);
1221 	if (ret != 0) {
1222 		dev_err(&dvbdev->udev->dev,
1223 			"tda9887 norm setup failed (%d)\n",
1224 			ret);
1225 		return ret;
1226 	}
1227 
1228 	ret = v4l2_subdev_call(cxdev->tuner, video, s_std, norm);
1229 	if (ret != 0) {
1230 		dev_err(&dvbdev->udev->dev,
1231 			"tuner norm setup failed (%d)\n",
1232 			ret);
1233 		return ret;
1234 	}
1235 
1236 	ret = v4l2_subdev_call(cxdev->cx25840, video, s_std, norm);
1237 	if (ret != 0) {
1238 		dev_err(&dvbdev->udev->dev,
1239 			"cx25840 norm setup failed (%d)\n",
1240 			ret);
1241 		return ret;
1242 	}
1243 
1244 ret_savenorm:
1245 	cxdev->norm = norm;
1246 
1247 	return 0;
1248 }
1249 
1250 static int cxusb_medion_s_input(struct file *file, void *fh,
1251 				unsigned int i)
1252 {
1253 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1254 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1255 	int ret;
1256 	v4l2_std_id norm;
1257 
1258 	if (i >= CXUSB_INPUT_CNT)
1259 		return -EINVAL;
1260 
1261 	ret = v4l2_subdev_call(cxdev->cx25840, video, s_routing,
1262 			       cxusb_medion_inputs[i].inputcfg, 0, 0);
1263 	if (ret != 0)
1264 		return ret;
1265 
1266 	cxdev->input = i;
1267 	cxdev->videodev->tvnorms = cxusb_medion_inputs[i].input.std;
1268 
1269 	norm = cxdev->norm & cxusb_medion_inputs[i].input.std;
1270 	if (norm == 0)
1271 		norm = cxusb_medion_inputs[i].input.std;
1272 
1273 	cxusb_medion_set_norm(cxdev, norm);
1274 
1275 	return 0;
1276 }
1277 
1278 static int cxusb_medion_g_tuner(struct file *file, void *fh,
1279 				struct v4l2_tuner *tuner)
1280 {
1281 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1282 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1283 	struct video_device *vdev = video_devdata(file);
1284 	int ret;
1285 
1286 	if (tuner->index != 0)
1287 		return -EINVAL;
1288 
1289 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1290 		tuner->type = V4L2_TUNER_ANALOG_TV;
1291 	else
1292 		tuner->type = V4L2_TUNER_RADIO;
1293 
1294 	tuner->capability = 0;
1295 	tuner->afc = 0;
1296 
1297 	/*
1298 	 * fills:
1299 	 * always: capability (static), rangelow (static), rangehigh (static)
1300 	 * radio mode: afc (may fail silently), rxsubchans (static), audmode
1301 	 */
1302 	ret = v4l2_subdev_call(cxdev->tda9887, tuner, g_tuner, tuner);
1303 	if (ret != 0)
1304 		return ret;
1305 
1306 	/*
1307 	 * fills:
1308 	 * always: capability (static), rangelow (static), rangehigh (static)
1309 	 * radio mode: rxsubchans (always stereo), audmode,
1310 	 * signal (might be wrong)
1311 	 */
1312 	ret = v4l2_subdev_call(cxdev->tuner, tuner, g_tuner, tuner);
1313 	if (ret != 0)
1314 		return ret;
1315 
1316 	tuner->signal = 0;
1317 
1318 	/*
1319 	 * fills: TV mode: capability, rxsubchans, audmode, signal
1320 	 */
1321 	ret = v4l2_subdev_call(cxdev->cx25840, tuner, g_tuner, tuner);
1322 	if (ret != 0)
1323 		return ret;
1324 
1325 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1326 		strscpy(tuner->name, "TV tuner", sizeof(tuner->name));
1327 	else
1328 		strscpy(tuner->name, "Radio tuner", sizeof(tuner->name));
1329 
1330 	memset(tuner->reserved, 0, sizeof(tuner->reserved));
1331 
1332 	return 0;
1333 }
1334 
1335 static int cxusb_medion_s_tuner(struct file *file, void *fh,
1336 				const struct v4l2_tuner *tuner)
1337 {
1338 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1339 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1340 	struct video_device *vdev = video_devdata(file);
1341 	int ret;
1342 
1343 	if (tuner->index != 0)
1344 		return -EINVAL;
1345 
1346 	ret = v4l2_subdev_call(cxdev->tda9887, tuner, s_tuner, tuner);
1347 	if (ret != 0)
1348 		return ret;
1349 
1350 	ret = v4l2_subdev_call(cxdev->tuner, tuner, s_tuner, tuner);
1351 	if (ret != 0)
1352 		return ret;
1353 
1354 	/*
1355 	 * make sure that cx25840 is in a correct TV / radio mode,
1356 	 * since calls above may have changed it for tuner / IF demod
1357 	 */
1358 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1359 		v4l2_subdev_call(cxdev->cx25840, video, s_std, cxdev->norm);
1360 	else
1361 		v4l2_subdev_call(cxdev->cx25840, tuner, s_radio);
1362 
1363 	return v4l2_subdev_call(cxdev->cx25840, tuner, s_tuner, tuner);
1364 }
1365 
1366 static int cxusb_medion_g_frequency(struct file *file, void *fh,
1367 				    struct v4l2_frequency *freq)
1368 {
1369 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1370 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1371 
1372 	if (freq->tuner != 0)
1373 		return -EINVAL;
1374 
1375 	return v4l2_subdev_call(cxdev->tuner, tuner, g_frequency, freq);
1376 }
1377 
1378 static int cxusb_medion_s_frequency(struct file *file, void *fh,
1379 				    const struct v4l2_frequency *freq)
1380 {
1381 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1382 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1383 	struct video_device *vdev = video_devdata(file);
1384 	int ret;
1385 
1386 	if (freq->tuner != 0)
1387 		return -EINVAL;
1388 
1389 	ret = v4l2_subdev_call(cxdev->tda9887, tuner, s_frequency, freq);
1390 	if (ret != 0)
1391 		return ret;
1392 
1393 	ret = v4l2_subdev_call(cxdev->tuner, tuner, s_frequency, freq);
1394 	if (ret != 0)
1395 		return ret;
1396 
1397 	/*
1398 	 * make sure that cx25840 is in a correct TV / radio mode,
1399 	 * since calls above may have changed it for tuner / IF demod
1400 	 */
1401 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1402 		v4l2_subdev_call(cxdev->cx25840, video, s_std, cxdev->norm);
1403 	else
1404 		v4l2_subdev_call(cxdev->cx25840, tuner, s_radio);
1405 
1406 	return v4l2_subdev_call(cxdev->cx25840, tuner, s_frequency, freq);
1407 }
1408 
1409 static int cxusb_medion_g_std(struct file *file, void *fh,
1410 			      v4l2_std_id *norm)
1411 {
1412 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1413 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1414 
1415 	*norm = cxdev->norm;
1416 
1417 	if (*norm == V4L2_STD_UNKNOWN)
1418 		return -ENODATA;
1419 
1420 	return 0;
1421 }
1422 
1423 static int cxusb_medion_s_std(struct file *file, void *fh,
1424 			      v4l2_std_id norm)
1425 {
1426 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1427 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1428 
1429 	return cxusb_medion_set_norm(cxdev, norm);
1430 }
1431 
1432 static int cxusb_medion_querystd(struct file *file, void *fh,
1433 				 v4l2_std_id *norm)
1434 {
1435 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1436 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1437 	v4l2_std_id norm_mask;
1438 	int ret;
1439 
1440 	/*
1441 	 * make sure we don't have improper std bits set for the TV tuner
1442 	 * (could happen when no signal was present yet after reset)
1443 	 */
1444 	if (cxdev->input == 0)
1445 		norm_mask = V4L2_STD_PAL;
1446 	else
1447 		norm_mask = V4L2_STD_ALL;
1448 
1449 	ret = v4l2_subdev_call(cxdev->cx25840, video, querystd, norm);
1450 	if (ret != 0) {
1451 		cxusb_vprintk(dvbdev, OPS,
1452 			      "cannot get detected standard for input %u\n",
1453 			      (unsigned int)cxdev->input);
1454 		return ret;
1455 	}
1456 
1457 	cxusb_vprintk(dvbdev, OPS, "input %u detected standard is %lx\n",
1458 		      (unsigned int)cxdev->input, (unsigned long)*norm);
1459 	*norm &= norm_mask;
1460 
1461 	return 0;
1462 }
1463 
1464 static int cxusb_medion_g_s_parm(struct file *file, void *fh,
1465 				 struct v4l2_streamparm *param)
1466 {
1467 	v4l2_std_id std;
1468 
1469 	if (param->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1470 		return -EINVAL;
1471 
1472 	param->parm.capture.readbuffers = 2;
1473 
1474 	if (cxusb_medion_g_std(file, fh, &std) == 0)
1475 		v4l2_video_std_frame_period(std,
1476 					    &param->parm.capture.timeperframe);
1477 
1478 	return 0;
1479 }
1480 
1481 static int cxusb_medion_g_parm(struct file *file, void *fh,
1482 			       struct v4l2_streamparm *param)
1483 {
1484 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1485 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1486 	int ret;
1487 
1488 	ret = cxusb_medion_g_s_parm(file, fh, param);
1489 	if (ret != 0)
1490 		return ret;
1491 
1492 	if (cxdev->raw_mode)
1493 		param->parm.capture.extendedmode |=
1494 			CXUSB_EXTENDEDMODE_CAPTURE_RAW;
1495 
1496 	return 0;
1497 }
1498 
1499 static int cxusb_medion_s_parm(struct file *file, void *fh,
1500 			       struct v4l2_streamparm *param)
1501 {
1502 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1503 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1504 	int ret;
1505 	bool want_raw;
1506 
1507 	ret = cxusb_medion_g_s_parm(file, fh, param);
1508 	if (ret != 0)
1509 		return ret;
1510 
1511 	want_raw = param->parm.capture.extendedmode &
1512 		CXUSB_EXTENDEDMODE_CAPTURE_RAW;
1513 
1514 	if (want_raw != cxdev->raw_mode) {
1515 		if (vb2_start_streaming_called(&cxdev->videoqueue) ||
1516 		    cxdev->stop_streaming)
1517 			return -EBUSY;
1518 
1519 		cxdev->raw_mode = want_raw;
1520 	}
1521 
1522 	return 0;
1523 }
1524 
1525 static int cxusb_medion_log_status(struct file *file, void *fh)
1526 {
1527 	struct dvb_usb_device *dvbdev = video_drvdata(file);
1528 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1529 
1530 	v4l2_device_call_all(&cxdev->v4l2dev, 0, core, log_status);
1531 
1532 	return 0;
1533 }
1534 
1535 static const struct v4l2_ioctl_ops cxusb_video_ioctl = {
1536 	.vidioc_querycap = cxusb_medion_v_querycap,
1537 	.vidioc_enum_fmt_vid_cap = cxusb_medion_v_enum_fmt_vid_cap,
1538 	.vidioc_g_fmt_vid_cap = cxusb_medion_g_fmt_vid_cap,
1539 	.vidioc_s_fmt_vid_cap = cxusb_medion_s_fmt_vid_cap,
1540 	.vidioc_try_fmt_vid_cap = cxusb_medion_try_fmt_vid_cap,
1541 	.vidioc_enum_input = cxusb_medion_enum_input,
1542 	.vidioc_g_input = cxusb_medion_g_input,
1543 	.vidioc_s_input = cxusb_medion_s_input,
1544 	.vidioc_g_parm = cxusb_medion_g_parm,
1545 	.vidioc_s_parm = cxusb_medion_s_parm,
1546 	.vidioc_g_tuner = cxusb_medion_g_tuner,
1547 	.vidioc_s_tuner = cxusb_medion_s_tuner,
1548 	.vidioc_g_frequency = cxusb_medion_g_frequency,
1549 	.vidioc_s_frequency = cxusb_medion_s_frequency,
1550 	.vidioc_g_std = cxusb_medion_g_std,
1551 	.vidioc_s_std = cxusb_medion_s_std,
1552 	.vidioc_querystd = cxusb_medion_querystd,
1553 	.vidioc_log_status = cxusb_medion_log_status,
1554 	.vidioc_reqbufs = vb2_ioctl_reqbufs,
1555 	.vidioc_querybuf = vb2_ioctl_querybuf,
1556 	.vidioc_qbuf = vb2_ioctl_qbuf,
1557 	.vidioc_dqbuf = vb2_ioctl_dqbuf,
1558 	.vidioc_create_bufs = vb2_ioctl_create_bufs,
1559 	.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
1560 	.vidioc_streamon = vb2_ioctl_streamon,
1561 	.vidioc_streamoff = vb2_ioctl_streamoff
1562 };
1563 
1564 static const struct v4l2_ioctl_ops cxusb_radio_ioctl = {
1565 	.vidioc_querycap = cxusb_medion_v_querycap,
1566 	.vidioc_g_tuner = cxusb_medion_g_tuner,
1567 	.vidioc_s_tuner = cxusb_medion_s_tuner,
1568 	.vidioc_g_frequency = cxusb_medion_g_frequency,
1569 	.vidioc_s_frequency = cxusb_medion_s_frequency,
1570 	.vidioc_log_status = cxusb_medion_log_status
1571 };
1572 
1573 /*
1574  * in principle, this should be const, but s_io_pin_config is declared
1575  * to take non-const, and gcc complains
1576  */
1577 static struct v4l2_subdev_io_pin_config cxusub_medion_pin_config[] = {
1578 	{ .pin = CX25840_PIN_DVALID_PRGM0, .function = CX25840_PAD_DEFAULT,
1579 	  .strength = CX25840_PIN_DRIVE_MEDIUM },
1580 	{ .pin = CX25840_PIN_PLL_CLK_PRGM7, .function = CX25840_PAD_AUX_PLL },
1581 	{ .pin = CX25840_PIN_HRESET_PRGM2, .function = CX25840_PAD_ACTIVE,
1582 	  .strength = CX25840_PIN_DRIVE_MEDIUM }
1583 };
1584 
1585 int cxusb_medion_analog_init(struct dvb_usb_device *dvbdev)
1586 {
1587 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1588 	u8 tuner_analog_msg_data[] = { 0x9c, 0x60, 0x85, 0x54 };
1589 	struct i2c_msg tuner_analog_msg = { .addr = 0x61, .flags = 0,
1590 					    .buf = tuner_analog_msg_data,
1591 					    .len =
1592 					    sizeof(tuner_analog_msg_data) };
1593 	struct v4l2_subdev_format subfmt;
1594 	int ret;
1595 
1596 	/* switch tuner to analog mode so IF demod will become accessible */
1597 	ret = i2c_transfer(&dvbdev->i2c_adap, &tuner_analog_msg, 1);
1598 	if (ret != 1)
1599 		dev_warn(&dvbdev->udev->dev,
1600 			 "tuner analog switch failed (%d)\n", ret);
1601 
1602 	/*
1603 	 * cx25840 might have lost power during mode switching so we need
1604 	 * to set it again
1605 	 */
1606 	ret = v4l2_subdev_call(cxdev->cx25840, core, reset, 0);
1607 	if (ret != 0)
1608 		dev_warn(&dvbdev->udev->dev,
1609 			 "cx25840 reset failed (%d)\n", ret);
1610 
1611 	ret = v4l2_subdev_call(cxdev->cx25840, video, s_routing,
1612 			       CX25840_COMPOSITE1, 0, 0);
1613 	if (ret != 0)
1614 		dev_warn(&dvbdev->udev->dev,
1615 			 "cx25840 initial input setting failed (%d)\n", ret);
1616 
1617 	/* composite */
1618 	cxdev->input = 1;
1619 	cxdev->videodev->tvnorms = V4L2_STD_ALL;
1620 	cxdev->norm = V4L2_STD_PAL;
1621 
1622 	/* TODO: setup audio samples insertion */
1623 
1624 	ret = v4l2_subdev_call(cxdev->cx25840, core, s_io_pin_config,
1625 			       sizeof(cxusub_medion_pin_config) /
1626 			       sizeof(cxusub_medion_pin_config[0]),
1627 			       cxusub_medion_pin_config);
1628 	if (ret != 0)
1629 		dev_warn(&dvbdev->udev->dev,
1630 			 "cx25840 pin config failed (%d)\n", ret);
1631 
1632 	/* make sure that we aren't in radio mode */
1633 	v4l2_subdev_call(cxdev->tda9887, video, s_std, cxdev->norm);
1634 	v4l2_subdev_call(cxdev->tuner, video, s_std, cxdev->norm);
1635 	v4l2_subdev_call(cxdev->cx25840, video, s_std, cxdev->norm);
1636 
1637 	memset(&subfmt, 0, sizeof(subfmt));
1638 	subfmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
1639 	subfmt.format.width = cxdev->width;
1640 	subfmt.format.height = cxdev->height;
1641 	subfmt.format.code = MEDIA_BUS_FMT_FIXED;
1642 	subfmt.format.field = V4L2_FIELD_SEQ_TB;
1643 	subfmt.format.colorspace = V4L2_COLORSPACE_SMPTE170M;
1644 
1645 	ret = v4l2_subdev_call(cxdev->cx25840, pad, set_fmt, NULL, &subfmt);
1646 	if (ret != 0)
1647 		dev_warn(&dvbdev->udev->dev,
1648 			 "cx25840 format set failed (%d)\n", ret);
1649 
1650 	if (ret == 0) {
1651 		cxdev->width = subfmt.format.width;
1652 		cxdev->height = subfmt.format.height;
1653 	}
1654 
1655 	return 0;
1656 }
1657 
1658 static int cxusb_videoradio_open(struct file *f)
1659 {
1660 	struct dvb_usb_device *dvbdev = video_drvdata(f);
1661 	int ret;
1662 
1663 	/*
1664 	 * no locking needed since this call only modifies analog
1665 	 * state if there are no other analog handles currenly
1666 	 * opened so ops done via them cannot create a conflict
1667 	 */
1668 	ret = cxusb_medion_get(dvbdev, CXUSB_OPEN_ANALOG);
1669 	if (ret != 0)
1670 		return ret;
1671 
1672 	ret = v4l2_fh_open(f);
1673 	if (ret != 0)
1674 		goto ret_release;
1675 
1676 	cxusb_vprintk(dvbdev, OPS, "got open\n");
1677 
1678 	return 0;
1679 
1680 ret_release:
1681 	cxusb_medion_put(dvbdev);
1682 
1683 	return ret;
1684 }
1685 
1686 static int cxusb_videoradio_release(struct file *f)
1687 {
1688 	struct video_device *vdev = video_devdata(f);
1689 	struct dvb_usb_device *dvbdev = video_drvdata(f);
1690 	int ret;
1691 
1692 	cxusb_vprintk(dvbdev, OPS, "got release\n");
1693 
1694 	if (vdev->vfl_type == VFL_TYPE_GRABBER)
1695 		ret = vb2_fop_release(f);
1696 	else
1697 		ret = v4l2_fh_release(f);
1698 
1699 	cxusb_medion_put(dvbdev);
1700 
1701 	return ret;
1702 }
1703 
1704 static const struct v4l2_file_operations cxusb_video_fops = {
1705 	.owner = THIS_MODULE,
1706 	.read = vb2_fop_read,
1707 	.poll = vb2_fop_poll,
1708 	.unlocked_ioctl = video_ioctl2,
1709 	.mmap = vb2_fop_mmap,
1710 	.open = cxusb_videoradio_open,
1711 	.release = cxusb_videoradio_release
1712 };
1713 
1714 static const struct v4l2_file_operations cxusb_radio_fops = {
1715 	.owner = THIS_MODULE,
1716 	.unlocked_ioctl = video_ioctl2,
1717 	.open = cxusb_videoradio_open,
1718 	.release = cxusb_videoradio_release
1719 };
1720 
1721 static void cxusb_medion_v4l2_release(struct v4l2_device *v4l2_dev)
1722 {
1723 	struct cxusb_medion_dev *cxdev =
1724 		container_of(v4l2_dev, struct cxusb_medion_dev, v4l2dev);
1725 	struct dvb_usb_device *dvbdev = cxdev->dvbdev;
1726 
1727 	cxusb_vprintk(dvbdev, OPS, "v4l2 device release\n");
1728 
1729 	v4l2_device_unregister(&cxdev->v4l2dev);
1730 
1731 	mutex_destroy(&cxdev->dev_lock);
1732 
1733 	while (completion_done(&cxdev->v4l2_release))
1734 		schedule();
1735 
1736 	complete(&cxdev->v4l2_release);
1737 }
1738 
1739 static void cxusb_medion_videodev_release(struct video_device *vdev)
1740 {
1741 	struct dvb_usb_device *dvbdev = video_get_drvdata(vdev);
1742 
1743 	cxusb_vprintk(dvbdev, OPS, "video device release\n");
1744 
1745 	vb2_queue_release(vdev->queue);
1746 
1747 	video_device_release(vdev);
1748 }
1749 
1750 static int cxusb_medion_register_analog_video(struct dvb_usb_device *dvbdev)
1751 {
1752 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1753 	int ret;
1754 
1755 	cxdev->videoqueue.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1756 	cxdev->videoqueue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ |
1757 		VB2_DMABUF;
1758 	cxdev->videoqueue.ops = &cxdev_video_qops;
1759 	cxdev->videoqueue.mem_ops = &vb2_vmalloc_memops;
1760 	cxdev->videoqueue.drv_priv = dvbdev;
1761 	cxdev->videoqueue.buf_struct_size =
1762 		sizeof(struct cxusb_medion_vbuffer);
1763 	cxdev->videoqueue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1764 	cxdev->videoqueue.min_buffers_needed = 6;
1765 	cxdev->videoqueue.lock = &cxdev->dev_lock;
1766 
1767 	ret = vb2_queue_init(&cxdev->videoqueue);
1768 	if (ret) {
1769 		dev_err(&dvbdev->udev->dev,
1770 			"video queue init failed, ret = %d\n", ret);
1771 		return ret;
1772 	}
1773 
1774 	cxdev->videodev = video_device_alloc();
1775 	if (!cxdev->videodev) {
1776 		dev_err(&dvbdev->udev->dev, "video device alloc failed\n");
1777 		ret = -ENOMEM;
1778 		goto ret_qrelease;
1779 	}
1780 
1781 	cxdev->videodev->device_caps = videocaps;
1782 	cxdev->videodev->fops = &cxusb_video_fops;
1783 	cxdev->videodev->v4l2_dev = &cxdev->v4l2dev;
1784 	cxdev->videodev->queue = &cxdev->videoqueue;
1785 	strscpy(cxdev->videodev->name, "cxusb", sizeof(cxdev->videodev->name));
1786 	cxdev->videodev->vfl_dir = VFL_DIR_RX;
1787 	cxdev->videodev->ioctl_ops = &cxusb_video_ioctl;
1788 	cxdev->videodev->tvnorms = V4L2_STD_ALL;
1789 	cxdev->videodev->release = cxusb_medion_videodev_release;
1790 	cxdev->videodev->lock = &cxdev->dev_lock;
1791 	video_set_drvdata(cxdev->videodev, dvbdev);
1792 
1793 	ret = video_register_device(cxdev->videodev, VFL_TYPE_GRABBER, -1);
1794 	if (ret) {
1795 		dev_err(&dvbdev->udev->dev,
1796 			"video device register failed, ret = %d\n", ret);
1797 		goto ret_vrelease;
1798 	}
1799 
1800 	return 0;
1801 
1802 ret_vrelease:
1803 	video_device_release(cxdev->videodev);
1804 
1805 ret_qrelease:
1806 	vb2_queue_release(&cxdev->videoqueue);
1807 
1808 	return ret;
1809 }
1810 
1811 static int cxusb_medion_register_analog_radio(struct dvb_usb_device *dvbdev)
1812 {
1813 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1814 	int ret;
1815 
1816 	cxdev->radiodev = video_device_alloc();
1817 	if (!cxdev->radiodev) {
1818 		dev_err(&dvbdev->udev->dev, "radio device alloc failed\n");
1819 		return -ENOMEM;
1820 	}
1821 
1822 	cxdev->radiodev->device_caps = radiocaps;
1823 	cxdev->radiodev->fops = &cxusb_radio_fops;
1824 	cxdev->radiodev->v4l2_dev = &cxdev->v4l2dev;
1825 	strscpy(cxdev->radiodev->name, "cxusb", sizeof(cxdev->radiodev->name));
1826 	cxdev->radiodev->vfl_dir = VFL_DIR_RX;
1827 	cxdev->radiodev->ioctl_ops = &cxusb_radio_ioctl;
1828 	cxdev->radiodev->release = video_device_release;
1829 	cxdev->radiodev->lock = &cxdev->dev_lock;
1830 	video_set_drvdata(cxdev->radiodev, dvbdev);
1831 
1832 	ret = video_register_device(cxdev->radiodev, VFL_TYPE_RADIO, -1);
1833 	if (ret) {
1834 		dev_err(&dvbdev->udev->dev,
1835 			"radio device register failed, ret = %d\n", ret);
1836 		video_device_release(cxdev->radiodev);
1837 		return ret;
1838 	}
1839 
1840 	return 0;
1841 }
1842 
1843 static int cxusb_medion_register_analog_subdevs(struct dvb_usb_device *dvbdev)
1844 {
1845 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1846 	int ret;
1847 	struct tuner_setup tun_setup;
1848 
1849 	/* attach cx25840 capture chip */
1850 	cxdev->cx25840 = v4l2_i2c_new_subdev(&cxdev->v4l2dev,
1851 					     &dvbdev->i2c_adap,
1852 					     "cx25840", 0x44, NULL);
1853 	if (!cxdev->cx25840) {
1854 		dev_err(&dvbdev->udev->dev, "cx25840 not found\n");
1855 		return -ENODEV;
1856 	}
1857 
1858 	/*
1859 	 * Initialize cx25840 chip by calling its subdevice init core op.
1860 	 *
1861 	 * This switches it into the generic mode that disables some of
1862 	 * ivtv-related hacks in the cx25840 driver while allowing setting
1863 	 * of the chip video output configuration (passed in the call below
1864 	 * as the last argument).
1865 	 */
1866 	ret = v4l2_subdev_call(cxdev->cx25840, core, init,
1867 			       CX25840_VCONFIG_FMT_BT656 |
1868 			       CX25840_VCONFIG_RES_8BIT |
1869 			       CX25840_VCONFIG_VBIRAW_DISABLED |
1870 			       CX25840_VCONFIG_ANCDATA_DISABLED |
1871 			       CX25840_VCONFIG_ACTIVE_COMPOSITE |
1872 			       CX25840_VCONFIG_VALID_ANDACTIVE |
1873 			       CX25840_VCONFIG_HRESETW_NORMAL |
1874 			       CX25840_VCONFIG_CLKGATE_NONE |
1875 			       CX25840_VCONFIG_DCMODE_DWORDS);
1876 	if (ret != 0) {
1877 		dev_err(&dvbdev->udev->dev,
1878 			"cx25840 init failed (%d)\n", ret);
1879 		return ret;
1880 	}
1881 
1882 	/* attach analog tuner */
1883 	cxdev->tuner = v4l2_i2c_new_subdev(&cxdev->v4l2dev,
1884 					   &dvbdev->i2c_adap,
1885 					   "tuner", 0x61, NULL);
1886 	if (!cxdev->tuner) {
1887 		dev_err(&dvbdev->udev->dev, "tuner not found\n");
1888 		return -ENODEV;
1889 	}
1890 
1891 	/* configure it */
1892 	memset(&tun_setup, 0, sizeof(tun_setup));
1893 	tun_setup.addr = 0x61;
1894 	tun_setup.type = TUNER_PHILIPS_FMD1216ME_MK3;
1895 	tun_setup.mode_mask = T_RADIO | T_ANALOG_TV;
1896 	v4l2_subdev_call(cxdev->tuner, tuner, s_type_addr, &tun_setup);
1897 
1898 	/* attach IF demod */
1899 	cxdev->tda9887 = v4l2_i2c_new_subdev(&cxdev->v4l2dev,
1900 					     &dvbdev->i2c_adap,
1901 					     "tuner", 0x43, NULL);
1902 	if (!cxdev->tda9887) {
1903 		dev_err(&dvbdev->udev->dev, "tda9887 not found\n");
1904 		return -ENODEV;
1905 	}
1906 
1907 	return 0;
1908 }
1909 
1910 int cxusb_medion_register_analog(struct dvb_usb_device *dvbdev)
1911 {
1912 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1913 	int ret;
1914 
1915 	mutex_init(&cxdev->dev_lock);
1916 
1917 	init_completion(&cxdev->v4l2_release);
1918 
1919 	cxdev->v4l2dev.release = cxusb_medion_v4l2_release;
1920 
1921 	ret = v4l2_device_register(&dvbdev->udev->dev, &cxdev->v4l2dev);
1922 	if (ret != 0) {
1923 		dev_err(&dvbdev->udev->dev,
1924 			"V4L2 device registration failed, ret = %d\n", ret);
1925 		mutex_destroy(&cxdev->dev_lock);
1926 		return ret;
1927 	}
1928 
1929 	ret = cxusb_medion_register_analog_subdevs(dvbdev);
1930 	if (ret)
1931 		goto ret_unregister;
1932 
1933 	INIT_WORK(&cxdev->urbwork, cxusb_medion_v_complete_work);
1934 	INIT_LIST_HEAD(&cxdev->buflist);
1935 
1936 	cxdev->width = 320;
1937 	cxdev->height = 240;
1938 
1939 	ret = cxusb_medion_register_analog_video(dvbdev);
1940 	if (ret)
1941 		goto ret_unregister;
1942 
1943 	ret = cxusb_medion_register_analog_radio(dvbdev);
1944 	if (ret)
1945 		goto ret_vunreg;
1946 
1947 	return 0;
1948 
1949 ret_vunreg:
1950 	video_unregister_device(cxdev->videodev);
1951 
1952 ret_unregister:
1953 	v4l2_device_put(&cxdev->v4l2dev);
1954 	wait_for_completion(&cxdev->v4l2_release);
1955 
1956 	return ret;
1957 }
1958 
1959 void cxusb_medion_unregister_analog(struct dvb_usb_device *dvbdev)
1960 {
1961 	struct cxusb_medion_dev *cxdev = dvbdev->priv;
1962 
1963 	cxusb_vprintk(dvbdev, OPS, "unregistering analog\n");
1964 
1965 	video_unregister_device(cxdev->radiodev);
1966 	video_unregister_device(cxdev->videodev);
1967 
1968 	v4l2_device_put(&cxdev->v4l2dev);
1969 	wait_for_completion(&cxdev->v4l2_release);
1970 
1971 	cxusb_vprintk(dvbdev, OPS, "analog unregistered\n");
1972 }
1973