1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Realtek RTL2832U SDR driver
4  *
5  * Copyright (C) 2013 Antti Palosaari <crope@iki.fi>
6  *
7  * GNU Radio plugin "gr-kernel" for device usage will be on:
8  * https://git.linuxtv.org/anttip/gr-kernel.git
9  */
10 
11 #include "rtl2832_sdr.h"
12 #include "dvb_usb.h"
13 
14 #include <media/v4l2-device.h>
15 #include <media/v4l2-ioctl.h>
16 #include <media/v4l2-ctrls.h>
17 #include <media/v4l2-event.h>
18 #include <media/videobuf2-v4l2.h>
19 #include <media/videobuf2-vmalloc.h>
20 
21 #include <linux/platform_device.h>
22 #include <linux/jiffies.h>
23 #include <linux/math64.h>
24 #include <linux/regmap.h>
25 
26 static bool rtl2832_sdr_emulated_fmt;
27 module_param_named(emulated_formats, rtl2832_sdr_emulated_fmt, bool, 0644);
28 MODULE_PARM_DESC(emulated_formats, "enable emulated formats (disappears in future)");
29 
30 /* Original macro does not contain enough null pointer checks for our need */
31 #define V4L2_SUBDEV_HAS_OP(sd, o, f) \
32 	((sd) && (sd)->ops && (sd)->ops->o && (sd)->ops->o->f)
33 
34 #define MAX_BULK_BUFS            (10)
35 #define BULK_BUFFER_SIZE         (128 * 512)
36 
37 static const struct v4l2_frequency_band bands_adc[] = {
38 	{
39 		.tuner = 0,
40 		.type = V4L2_TUNER_ADC,
41 		.index = 0,
42 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
43 		.rangelow   =  300000,
44 		.rangehigh  =  300000,
45 	},
46 	{
47 		.tuner = 0,
48 		.type = V4L2_TUNER_ADC,
49 		.index = 1,
50 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
51 		.rangelow   =  900001,
52 		.rangehigh  = 2800000,
53 	},
54 	{
55 		.tuner = 0,
56 		.type = V4L2_TUNER_ADC,
57 		.index = 2,
58 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
59 		.rangelow   = 3200000,
60 		.rangehigh  = 3200000,
61 	},
62 };
63 
64 static const struct v4l2_frequency_band bands_fm[] = {
65 	{
66 		.tuner = 1,
67 		.type = V4L2_TUNER_RF,
68 		.index = 0,
69 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
70 		.rangelow   =    50000000,
71 		.rangehigh  =  2000000000,
72 	},
73 };
74 
75 /* stream formats */
76 struct rtl2832_sdr_format {
77 	char	*name;
78 	u32	pixelformat;
79 	u32	buffersize;
80 };
81 
82 static struct rtl2832_sdr_format formats[] = {
83 	{
84 		.pixelformat	= V4L2_SDR_FMT_CU8,
85 		.buffersize	= BULK_BUFFER_SIZE,
86 	}, {
87 		.pixelformat	= V4L2_SDR_FMT_CU16LE,
88 		.buffersize	= BULK_BUFFER_SIZE * 2,
89 	},
90 };
91 
92 static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
93 
94 /* intermediate buffers with raw data from the USB device */
95 struct rtl2832_sdr_frame_buf {
96 	/* common v4l buffer stuff -- must be first */
97 	struct vb2_v4l2_buffer vb;
98 	struct list_head list;
99 };
100 
101 struct rtl2832_sdr_dev {
102 #define POWER_ON           0  /* BIT(0) */
103 #define URB_BUF            1  /* BIT(1) */
104 	unsigned long flags;
105 
106 	struct platform_device *pdev;
107 	struct regmap *regmap;
108 
109 	struct video_device vdev;
110 	struct v4l2_device v4l2_dev;
111 	struct v4l2_subdev *v4l2_subdev;
112 
113 	/* videobuf2 queue and queued buffers list */
114 	struct vb2_queue vb_queue;
115 	struct list_head queued_bufs;
116 	spinlock_t queued_bufs_lock; /* Protects queued_bufs */
117 	unsigned sequence;	     /* buffer sequence counter */
118 
119 	/* Note if taking both locks v4l2_lock must always be locked first! */
120 	struct mutex v4l2_lock;      /* Protects everything else */
121 	struct mutex vb_queue_lock;  /* Protects vb_queue and capt_file */
122 
123 	/* Pointer to our usb_device, will be NULL after unplug */
124 	struct usb_device *udev; /* Both mutexes most be hold when setting! */
125 
126 	unsigned int vb_full; /* vb is full and packets dropped */
127 
128 	struct urb     *urb_list[MAX_BULK_BUFS];
129 	int            buf_num;
130 	unsigned long  buf_size;
131 	u8             *buf_list[MAX_BULK_BUFS];
132 	dma_addr_t     dma_addr[MAX_BULK_BUFS];
133 	int urbs_initialized;
134 	int urbs_submitted;
135 
136 	unsigned int f_adc, f_tuner;
137 	u32 pixelformat;
138 	u32 buffersize;
139 	unsigned int num_formats;
140 
141 	/* Controls */
142 	struct v4l2_ctrl_handler hdl;
143 	struct v4l2_ctrl *bandwidth_auto;
144 	struct v4l2_ctrl *bandwidth;
145 
146 	/* for sample rate calc */
147 	unsigned int sample;
148 	unsigned int sample_measured;
149 	unsigned long jiffies_next;
150 };
151 
152 /* Private functions */
153 static struct rtl2832_sdr_frame_buf *rtl2832_sdr_get_next_fill_buf(
154 		struct rtl2832_sdr_dev *dev)
155 {
156 	unsigned long flags;
157 	struct rtl2832_sdr_frame_buf *buf = NULL;
158 
159 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
160 	if (list_empty(&dev->queued_bufs))
161 		goto leave;
162 
163 	buf = list_entry(dev->queued_bufs.next,
164 			struct rtl2832_sdr_frame_buf, list);
165 	list_del(&buf->list);
166 leave:
167 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
168 	return buf;
169 }
170 
171 static unsigned int rtl2832_sdr_convert_stream(struct rtl2832_sdr_dev *dev,
172 		void *dst, const u8 *src, unsigned int src_len)
173 {
174 	struct platform_device *pdev = dev->pdev;
175 	unsigned int dst_len;
176 
177 	if (dev->pixelformat ==  V4L2_SDR_FMT_CU8) {
178 		/* native stream, no need to convert */
179 		memcpy(dst, src, src_len);
180 		dst_len = src_len;
181 	} else if (dev->pixelformat == V4L2_SDR_FMT_CU16LE) {
182 		/* convert u8 to u16 */
183 		unsigned int i;
184 		u16 *u16dst = dst;
185 
186 		for (i = 0; i < src_len; i++)
187 			*u16dst++ = (src[i] << 8) | (src[i] >> 0);
188 		dst_len = 2 * src_len;
189 	} else {
190 		dst_len = 0;
191 	}
192 
193 	/* calculate sample rate and output it in 10 seconds intervals */
194 	if (unlikely(time_is_before_jiffies(dev->jiffies_next))) {
195 		#define MSECS 10000UL
196 		unsigned int msecs = jiffies_to_msecs(jiffies -
197 				dev->jiffies_next + msecs_to_jiffies(MSECS));
198 		unsigned int samples = dev->sample - dev->sample_measured;
199 
200 		dev->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
201 		dev->sample_measured = dev->sample;
202 		dev_dbg(&pdev->dev,
203 			"slen=%u samples=%u msecs=%u sample rate=%lu\n",
204 			src_len, samples, msecs, samples * 1000UL / msecs);
205 	}
206 
207 	/* total number of I+Q pairs */
208 	dev->sample += src_len / 2;
209 
210 	return dst_len;
211 }
212 
213 /*
214  * This gets called for the bulk stream pipe. This is done in interrupt
215  * time, so it has to be fast, not crash, and not stall. Neat.
216  */
217 static void rtl2832_sdr_urb_complete(struct urb *urb)
218 {
219 	struct rtl2832_sdr_dev *dev = urb->context;
220 	struct platform_device *pdev = dev->pdev;
221 	struct rtl2832_sdr_frame_buf *fbuf;
222 
223 	dev_dbg_ratelimited(&pdev->dev, "status=%d length=%d/%d errors=%d\n",
224 			    urb->status, urb->actual_length,
225 			    urb->transfer_buffer_length, urb->error_count);
226 
227 	switch (urb->status) {
228 	case 0:             /* success */
229 	case -ETIMEDOUT:    /* NAK */
230 		break;
231 	case -ECONNRESET:   /* kill */
232 	case -ENOENT:
233 	case -ESHUTDOWN:
234 		return;
235 	default:            /* error */
236 		dev_err_ratelimited(&pdev->dev, "urb failed=%d\n", urb->status);
237 		break;
238 	}
239 
240 	if (likely(urb->actual_length > 0)) {
241 		void *ptr;
242 		unsigned int len;
243 		/* get free framebuffer */
244 		fbuf = rtl2832_sdr_get_next_fill_buf(dev);
245 		if (unlikely(fbuf == NULL)) {
246 			dev->vb_full++;
247 			dev_notice_ratelimited(&pdev->dev,
248 					       "videobuf is full, %d packets dropped\n",
249 					       dev->vb_full);
250 			goto skip;
251 		}
252 
253 		/* fill framebuffer */
254 		ptr = vb2_plane_vaddr(&fbuf->vb.vb2_buf, 0);
255 		len = rtl2832_sdr_convert_stream(dev, ptr, urb->transfer_buffer,
256 				urb->actual_length);
257 		vb2_set_plane_payload(&fbuf->vb.vb2_buf, 0, len);
258 		fbuf->vb.vb2_buf.timestamp = ktime_get_ns();
259 		fbuf->vb.sequence = dev->sequence++;
260 		vb2_buffer_done(&fbuf->vb.vb2_buf, VB2_BUF_STATE_DONE);
261 	}
262 skip:
263 	usb_submit_urb(urb, GFP_ATOMIC);
264 }
265 
266 static int rtl2832_sdr_kill_urbs(struct rtl2832_sdr_dev *dev)
267 {
268 	struct platform_device *pdev = dev->pdev;
269 	int i;
270 
271 	for (i = dev->urbs_submitted - 1; i >= 0; i--) {
272 		dev_dbg(&pdev->dev, "kill urb=%d\n", i);
273 		/* stop the URB */
274 		usb_kill_urb(dev->urb_list[i]);
275 	}
276 	dev->urbs_submitted = 0;
277 
278 	return 0;
279 }
280 
281 static int rtl2832_sdr_submit_urbs(struct rtl2832_sdr_dev *dev)
282 {
283 	struct platform_device *pdev = dev->pdev;
284 	int i, ret;
285 
286 	for (i = 0; i < dev->urbs_initialized; i++) {
287 		dev_dbg(&pdev->dev, "submit urb=%d\n", i);
288 		ret = usb_submit_urb(dev->urb_list[i], GFP_KERNEL);
289 		if (ret) {
290 			dev_err(&pdev->dev,
291 				"Could not submit urb no. %d - get them all back\n",
292 				i);
293 			rtl2832_sdr_kill_urbs(dev);
294 			return ret;
295 		}
296 		dev->urbs_submitted++;
297 	}
298 
299 	return 0;
300 }
301 
302 static int rtl2832_sdr_free_stream_bufs(struct rtl2832_sdr_dev *dev)
303 {
304 	struct platform_device *pdev = dev->pdev;
305 
306 	if (test_bit(URB_BUF, &dev->flags)) {
307 		while (dev->buf_num) {
308 			dev->buf_num--;
309 			dev_dbg(&pdev->dev, "free buf=%d\n", dev->buf_num);
310 			usb_free_coherent(dev->udev, dev->buf_size,
311 					  dev->buf_list[dev->buf_num],
312 					  dev->dma_addr[dev->buf_num]);
313 		}
314 	}
315 	clear_bit(URB_BUF, &dev->flags);
316 
317 	return 0;
318 }
319 
320 static int rtl2832_sdr_alloc_stream_bufs(struct rtl2832_sdr_dev *dev)
321 {
322 	struct platform_device *pdev = dev->pdev;
323 
324 	dev->buf_num = 0;
325 	dev->buf_size = BULK_BUFFER_SIZE;
326 
327 	dev_dbg(&pdev->dev, "all in all I will use %u bytes for streaming\n",
328 		MAX_BULK_BUFS * BULK_BUFFER_SIZE);
329 
330 	for (dev->buf_num = 0; dev->buf_num < MAX_BULK_BUFS; dev->buf_num++) {
331 		dev->buf_list[dev->buf_num] = usb_alloc_coherent(dev->udev,
332 				BULK_BUFFER_SIZE, GFP_KERNEL,
333 				&dev->dma_addr[dev->buf_num]);
334 		if (!dev->buf_list[dev->buf_num]) {
335 			dev_dbg(&pdev->dev, "alloc buf=%d failed\n",
336 				dev->buf_num);
337 			rtl2832_sdr_free_stream_bufs(dev);
338 			return -ENOMEM;
339 		}
340 
341 		dev_dbg(&pdev->dev, "alloc buf=%d %p (dma %llu)\n",
342 			dev->buf_num, dev->buf_list[dev->buf_num],
343 			(long long)dev->dma_addr[dev->buf_num]);
344 		set_bit(URB_BUF, &dev->flags);
345 	}
346 
347 	return 0;
348 }
349 
350 static int rtl2832_sdr_free_urbs(struct rtl2832_sdr_dev *dev)
351 {
352 	struct platform_device *pdev = dev->pdev;
353 	int i;
354 
355 	rtl2832_sdr_kill_urbs(dev);
356 
357 	for (i = dev->urbs_initialized - 1; i >= 0; i--) {
358 		if (dev->urb_list[i]) {
359 			dev_dbg(&pdev->dev, "free urb=%d\n", i);
360 			/* free the URBs */
361 			usb_free_urb(dev->urb_list[i]);
362 		}
363 	}
364 	dev->urbs_initialized = 0;
365 
366 	return 0;
367 }
368 
369 static int rtl2832_sdr_alloc_urbs(struct rtl2832_sdr_dev *dev)
370 {
371 	struct platform_device *pdev = dev->pdev;
372 	int i, j;
373 
374 	/* allocate the URBs */
375 	for (i = 0; i < MAX_BULK_BUFS; i++) {
376 		dev_dbg(&pdev->dev, "alloc urb=%d\n", i);
377 		dev->urb_list[i] = usb_alloc_urb(0, GFP_KERNEL);
378 		if (!dev->urb_list[i]) {
379 			for (j = 0; j < i; j++) {
380 				usb_free_urb(dev->urb_list[j]);
381 				dev->urb_list[j] = NULL;
382 			}
383 			dev->urbs_initialized = 0;
384 			return -ENOMEM;
385 		}
386 		usb_fill_bulk_urb(dev->urb_list[i],
387 				dev->udev,
388 				usb_rcvbulkpipe(dev->udev, 0x81),
389 				dev->buf_list[i],
390 				BULK_BUFFER_SIZE,
391 				rtl2832_sdr_urb_complete, dev);
392 
393 		dev->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
394 		dev->urb_list[i]->transfer_dma = dev->dma_addr[i];
395 		dev->urbs_initialized++;
396 	}
397 
398 	return 0;
399 }
400 
401 /* Must be called with vb_queue_lock hold */
402 static void rtl2832_sdr_cleanup_queued_bufs(struct rtl2832_sdr_dev *dev)
403 {
404 	struct platform_device *pdev = dev->pdev;
405 	unsigned long flags;
406 
407 	dev_dbg(&pdev->dev, "\n");
408 
409 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
410 	while (!list_empty(&dev->queued_bufs)) {
411 		struct rtl2832_sdr_frame_buf *buf;
412 
413 		buf = list_entry(dev->queued_bufs.next,
414 				struct rtl2832_sdr_frame_buf, list);
415 		list_del(&buf->list);
416 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
417 	}
418 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
419 }
420 
421 static int rtl2832_sdr_querycap(struct file *file, void *fh,
422 		struct v4l2_capability *cap)
423 {
424 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
425 	struct platform_device *pdev = dev->pdev;
426 
427 	dev_dbg(&pdev->dev, "\n");
428 
429 	strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
430 	strscpy(cap->card, dev->vdev.name, sizeof(cap->card));
431 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
432 	return 0;
433 }
434 
435 /* Videobuf2 operations */
436 static int rtl2832_sdr_queue_setup(struct vb2_queue *vq,
437 		unsigned int *nbuffers,
438 		unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[])
439 {
440 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
441 	struct platform_device *pdev = dev->pdev;
442 
443 	dev_dbg(&pdev->dev, "nbuffers=%d\n", *nbuffers);
444 
445 	/* Need at least 8 buffers */
446 	if (vq->num_buffers + *nbuffers < 8)
447 		*nbuffers = 8 - vq->num_buffers;
448 	*nplanes = 1;
449 	sizes[0] = PAGE_ALIGN(dev->buffersize);
450 	dev_dbg(&pdev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
451 	return 0;
452 }
453 
454 static int rtl2832_sdr_buf_prepare(struct vb2_buffer *vb)
455 {
456 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
457 
458 	/* Don't allow queueing new buffers after device disconnection */
459 	if (!dev->udev)
460 		return -ENODEV;
461 
462 	return 0;
463 }
464 
465 static void rtl2832_sdr_buf_queue(struct vb2_buffer *vb)
466 {
467 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
468 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
469 	struct rtl2832_sdr_frame_buf *buf =
470 			container_of(vbuf, struct rtl2832_sdr_frame_buf, vb);
471 	unsigned long flags;
472 
473 	/* Check the device has not disconnected between prep and queuing */
474 	if (!dev->udev) {
475 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
476 		return;
477 	}
478 
479 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
480 	list_add_tail(&buf->list, &dev->queued_bufs);
481 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
482 }
483 
484 static int rtl2832_sdr_set_adc(struct rtl2832_sdr_dev *dev)
485 {
486 	struct platform_device *pdev = dev->pdev;
487 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
488 	struct dvb_frontend *fe = pdata->dvb_frontend;
489 	int ret;
490 	unsigned int f_sr, f_if;
491 	u8 buf[4], u8tmp1, u8tmp2;
492 	u64 u64tmp;
493 	u32 u32tmp;
494 
495 	dev_dbg(&pdev->dev, "f_adc=%u\n", dev->f_adc);
496 
497 	if (!test_bit(POWER_ON, &dev->flags))
498 		return 0;
499 
500 	if (dev->f_adc == 0)
501 		return 0;
502 
503 	f_sr = dev->f_adc;
504 
505 	ret = regmap_bulk_write(dev->regmap, 0x13e, "\x00\x00", 2);
506 	if (ret)
507 		goto err;
508 
509 	ret = regmap_bulk_write(dev->regmap, 0x115, "\x00\x00\x00\x00", 4);
510 	if (ret)
511 		goto err;
512 
513 	/* get IF from tuner */
514 	if (fe->ops.tuner_ops.get_if_frequency)
515 		ret = fe->ops.tuner_ops.get_if_frequency(fe, &f_if);
516 	else
517 		ret = -EINVAL;
518 
519 	if (ret)
520 		goto err;
521 
522 	/* program IF */
523 	u64tmp = f_if % pdata->clk;
524 	u64tmp *= 0x400000;
525 	u64tmp = div_u64(u64tmp, pdata->clk);
526 	u64tmp = -u64tmp;
527 	u32tmp = u64tmp & 0x3fffff;
528 
529 	dev_dbg(&pdev->dev, "f_if=%u if_ctl=%08x\n", f_if, u32tmp);
530 
531 	buf[0] = (u32tmp >> 16) & 0xff;
532 	buf[1] = (u32tmp >>  8) & 0xff;
533 	buf[2] = (u32tmp >>  0) & 0xff;
534 
535 	ret = regmap_bulk_write(dev->regmap, 0x119, buf, 3);
536 	if (ret)
537 		goto err;
538 
539 	/* BB / IF mode */
540 	/* POR: 0x1b1=0x1f, 0x008=0x0d, 0x006=0x80 */
541 	if (f_if) {
542 		u8tmp1 = 0x1a; /* disable Zero-IF */
543 		u8tmp2 = 0x8d; /* enable ADC I */
544 	} else {
545 		u8tmp1 = 0x1b; /* enable Zero-IF, DC, IQ */
546 		u8tmp2 = 0xcd; /* enable ADC I, ADC Q */
547 	}
548 
549 	ret = regmap_write(dev->regmap, 0x1b1, u8tmp1);
550 	if (ret)
551 		goto err;
552 
553 	ret = regmap_write(dev->regmap, 0x008, u8tmp2);
554 	if (ret)
555 		goto err;
556 
557 	ret = regmap_write(dev->regmap, 0x006, 0x80);
558 	if (ret)
559 		goto err;
560 
561 	/* program sampling rate (resampling down) */
562 	u32tmp = div_u64(pdata->clk * 0x400000ULL, f_sr * 4U);
563 	u32tmp <<= 2;
564 	buf[0] = (u32tmp >> 24) & 0xff;
565 	buf[1] = (u32tmp >> 16) & 0xff;
566 	buf[2] = (u32tmp >>  8) & 0xff;
567 	buf[3] = (u32tmp >>  0) & 0xff;
568 	ret = regmap_bulk_write(dev->regmap, 0x19f, buf, 4);
569 	if (ret)
570 		goto err;
571 
572 	/* low-pass filter */
573 	ret = regmap_bulk_write(dev->regmap, 0x11c,
574 				"\xca\xdc\xd7\xd8\xe0\xf2\x0e\x35\x06\x50\x9c\x0d\x71\x11\x14\x71\x74\x19\x41\xa5",
575 				20);
576 	if (ret)
577 		goto err;
578 
579 	ret = regmap_bulk_write(dev->regmap, 0x017, "\x11\x10", 2);
580 	if (ret)
581 		goto err;
582 
583 	/* mode */
584 	ret = regmap_write(dev->regmap, 0x019, 0x05);
585 	if (ret)
586 		goto err;
587 
588 	ret = regmap_bulk_write(dev->regmap, 0x01a,
589 				"\x1b\x16\x0d\x06\x01\xff", 6);
590 	if (ret)
591 		goto err;
592 
593 	/* FSM */
594 	ret = regmap_bulk_write(dev->regmap, 0x192, "\x00\xf0\x0f", 3);
595 	if (ret)
596 		goto err;
597 
598 	/* PID filter */
599 	ret = regmap_write(dev->regmap, 0x061, 0x60);
600 	if (ret)
601 		goto err;
602 
603 	/* used RF tuner based settings */
604 	switch (pdata->tuner) {
605 	case RTL2832_SDR_TUNER_E4000:
606 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
607 		ret = regmap_write(dev->regmap, 0x102, 0x40);
608 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
609 		ret = regmap_write(dev->regmap, 0x1c7, 0x30);
610 		ret = regmap_write(dev->regmap, 0x104, 0xd0);
611 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
612 		ret = regmap_write(dev->regmap, 0x1c8, 0x18);
613 		ret = regmap_write(dev->regmap, 0x106, 0x35);
614 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
615 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
616 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
617 		ret = regmap_write(dev->regmap, 0x107, 0x40);
618 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
619 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
620 		ret = regmap_write(dev->regmap, 0x108, 0x80);
621 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
622 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
623 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
624 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
625 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
626 		ret = regmap_write(dev->regmap, 0x011, 0xd4);
627 		ret = regmap_write(dev->regmap, 0x1e5, 0xf0);
628 		ret = regmap_write(dev->regmap, 0x1d9, 0x00);
629 		ret = regmap_write(dev->regmap, 0x1db, 0x00);
630 		ret = regmap_write(dev->regmap, 0x1dd, 0x14);
631 		ret = regmap_write(dev->regmap, 0x1de, 0xec);
632 		ret = regmap_write(dev->regmap, 0x1d8, 0x0c);
633 		ret = regmap_write(dev->regmap, 0x1e6, 0x02);
634 		ret = regmap_write(dev->regmap, 0x1d7, 0x09);
635 		ret = regmap_write(dev->regmap, 0x00d, 0x83);
636 		ret = regmap_write(dev->regmap, 0x010, 0x49);
637 		ret = regmap_write(dev->regmap, 0x00d, 0x87);
638 		ret = regmap_write(dev->regmap, 0x00d, 0x85);
639 		ret = regmap_write(dev->regmap, 0x013, 0x02);
640 		break;
641 	case RTL2832_SDR_TUNER_FC0012:
642 	case RTL2832_SDR_TUNER_FC0013:
643 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
644 		ret = regmap_write(dev->regmap, 0x102, 0x40);
645 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
646 		ret = regmap_write(dev->regmap, 0x1c7, 0x2c);
647 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
648 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
649 		ret = regmap_write(dev->regmap, 0x1c8, 0x16);
650 		ret = regmap_write(dev->regmap, 0x106, 0x35);
651 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
652 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
653 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
654 		ret = regmap_write(dev->regmap, 0x107, 0x40);
655 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
656 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
657 		ret = regmap_write(dev->regmap, 0x108, 0x80);
658 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
659 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
660 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
661 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
662 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
663 		ret = regmap_bulk_write(dev->regmap, 0x011, "\xe9\xbf", 2);
664 		ret = regmap_write(dev->regmap, 0x1e5, 0xf0);
665 		ret = regmap_write(dev->regmap, 0x1d9, 0x00);
666 		ret = regmap_write(dev->regmap, 0x1db, 0x00);
667 		ret = regmap_write(dev->regmap, 0x1dd, 0x11);
668 		ret = regmap_write(dev->regmap, 0x1de, 0xef);
669 		ret = regmap_write(dev->regmap, 0x1d8, 0x0c);
670 		ret = regmap_write(dev->regmap, 0x1e6, 0x02);
671 		ret = regmap_write(dev->regmap, 0x1d7, 0x09);
672 		break;
673 	case RTL2832_SDR_TUNER_R820T:
674 	case RTL2832_SDR_TUNER_R828D:
675 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
676 		ret = regmap_write(dev->regmap, 0x102, 0x40);
677 		ret = regmap_write(dev->regmap, 0x115, 0x01);
678 		ret = regmap_write(dev->regmap, 0x103, 0x80);
679 		ret = regmap_write(dev->regmap, 0x1c7, 0x24);
680 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
681 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
682 		ret = regmap_write(dev->regmap, 0x1c8, 0x14);
683 		ret = regmap_write(dev->regmap, 0x106, 0x35);
684 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
685 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
686 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
687 		ret = regmap_write(dev->regmap, 0x107, 0x40);
688 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
689 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
690 		ret = regmap_write(dev->regmap, 0x108, 0x80);
691 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
692 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
693 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
694 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
695 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
696 		ret = regmap_write(dev->regmap, 0x011, 0xf4);
697 		break;
698 	case RTL2832_SDR_TUNER_FC2580:
699 		ret = regmap_write(dev->regmap, 0x112, 0x39);
700 		ret = regmap_write(dev->regmap, 0x102, 0x40);
701 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
702 		ret = regmap_write(dev->regmap, 0x1c7, 0x2c);
703 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
704 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
705 		ret = regmap_write(dev->regmap, 0x1c8, 0x16);
706 		ret = regmap_write(dev->regmap, 0x106, 0x35);
707 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
708 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
709 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
710 		ret = regmap_write(dev->regmap, 0x107, 0x40);
711 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
712 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
713 		ret = regmap_write(dev->regmap, 0x108, 0x80);
714 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
715 		ret = regmap_write(dev->regmap, 0x10a, 0x9c);
716 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
717 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
718 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
719 		ret = regmap_bulk_write(dev->regmap, 0x011, "\xe9\xf4", 2);
720 		break;
721 	default:
722 		dev_notice(&pdev->dev, "Unsupported tuner\n");
723 	}
724 
725 	/* software reset */
726 	ret = regmap_update_bits(dev->regmap, 0x101, 0x04, 0x04);
727 	if (ret)
728 		goto err;
729 
730 	ret = regmap_update_bits(dev->regmap, 0x101, 0x04, 0x00);
731 	if (ret)
732 		goto err;
733 err:
734 	return ret;
735 };
736 
737 static void rtl2832_sdr_unset_adc(struct rtl2832_sdr_dev *dev)
738 {
739 	struct platform_device *pdev = dev->pdev;
740 	int ret;
741 
742 	dev_dbg(&pdev->dev, "\n");
743 
744 	/* PID filter */
745 	ret = regmap_write(dev->regmap, 0x061, 0xe0);
746 	if (ret)
747 		goto err;
748 
749 	/* mode */
750 	ret = regmap_write(dev->regmap, 0x019, 0x20);
751 	if (ret)
752 		goto err;
753 
754 	ret = regmap_bulk_write(dev->regmap, 0x017, "\x11\x10", 2);
755 	if (ret)
756 		goto err;
757 
758 	/* FSM */
759 	ret = regmap_bulk_write(dev->regmap, 0x192, "\x00\x0f\xff", 3);
760 	if (ret)
761 		goto err;
762 
763 	ret = regmap_bulk_write(dev->regmap, 0x13e, "\x40\x00", 2);
764 	if (ret)
765 		goto err;
766 
767 	ret = regmap_bulk_write(dev->regmap, 0x115, "\x06\x3f\xce\xcc", 4);
768 	if (ret)
769 		goto err;
770 err:
771 	return;
772 };
773 
774 static int rtl2832_sdr_set_tuner_freq(struct rtl2832_sdr_dev *dev)
775 {
776 	struct platform_device *pdev = dev->pdev;
777 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
778 	struct dvb_frontend *fe = pdata->dvb_frontend;
779 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
780 	struct v4l2_ctrl *bandwidth_auto;
781 	struct v4l2_ctrl *bandwidth;
782 
783 	/*
784 	 * tuner RF (Hz)
785 	 */
786 	if (dev->f_tuner == 0)
787 		return 0;
788 
789 	/*
790 	 * bandwidth (Hz)
791 	 */
792 	bandwidth_auto = v4l2_ctrl_find(&dev->hdl,
793 					V4L2_CID_RF_TUNER_BANDWIDTH_AUTO);
794 	bandwidth = v4l2_ctrl_find(&dev->hdl, V4L2_CID_RF_TUNER_BANDWIDTH);
795 	if (v4l2_ctrl_g_ctrl(bandwidth_auto)) {
796 		c->bandwidth_hz = dev->f_adc;
797 		v4l2_ctrl_s_ctrl(bandwidth, dev->f_adc);
798 	} else {
799 		c->bandwidth_hz = v4l2_ctrl_g_ctrl(bandwidth);
800 	}
801 
802 	c->frequency = dev->f_tuner;
803 	c->delivery_system = SYS_DVBT;
804 
805 	dev_dbg(&pdev->dev, "frequency=%u bandwidth=%d\n",
806 		c->frequency, c->bandwidth_hz);
807 
808 	if (!test_bit(POWER_ON, &dev->flags))
809 		return 0;
810 
811 	if (!V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_frequency)) {
812 		if (fe->ops.tuner_ops.set_params)
813 			fe->ops.tuner_ops.set_params(fe);
814 	}
815 
816 	return 0;
817 };
818 
819 static int rtl2832_sdr_set_tuner(struct rtl2832_sdr_dev *dev)
820 {
821 	struct platform_device *pdev = dev->pdev;
822 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
823 	struct dvb_frontend *fe = pdata->dvb_frontend;
824 
825 	dev_dbg(&pdev->dev, "\n");
826 
827 	if (fe->ops.tuner_ops.init)
828 		fe->ops.tuner_ops.init(fe);
829 
830 	return 0;
831 };
832 
833 static void rtl2832_sdr_unset_tuner(struct rtl2832_sdr_dev *dev)
834 {
835 	struct platform_device *pdev = dev->pdev;
836 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
837 	struct dvb_frontend *fe = pdata->dvb_frontend;
838 
839 	dev_dbg(&pdev->dev, "\n");
840 
841 	if (fe->ops.tuner_ops.sleep)
842 		fe->ops.tuner_ops.sleep(fe);
843 
844 	return;
845 };
846 
847 static int rtl2832_sdr_start_streaming(struct vb2_queue *vq, unsigned int count)
848 {
849 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
850 	struct platform_device *pdev = dev->pdev;
851 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
852 	struct dvb_usb_device *d = pdata->dvb_usb_device;
853 	int ret;
854 
855 	dev_dbg(&pdev->dev, "\n");
856 
857 	if (!dev->udev)
858 		return -ENODEV;
859 
860 	if (mutex_lock_interruptible(&dev->v4l2_lock))
861 		return -ERESTARTSYS;
862 
863 	if (d->props->power_ctrl)
864 		d->props->power_ctrl(d, 1);
865 
866 	/* enable ADC */
867 	if (d->props->frontend_ctrl)
868 		d->props->frontend_ctrl(pdata->dvb_frontend, 1);
869 
870 	set_bit(POWER_ON, &dev->flags);
871 
872 	/* wake-up tuner */
873 	if (V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, core, s_power))
874 		ret = v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 1);
875 	else
876 		ret = rtl2832_sdr_set_tuner(dev);
877 	if (ret)
878 		goto err;
879 
880 	ret = rtl2832_sdr_set_tuner_freq(dev);
881 	if (ret)
882 		goto err;
883 
884 	ret = rtl2832_sdr_set_adc(dev);
885 	if (ret)
886 		goto err;
887 
888 	ret = rtl2832_sdr_alloc_stream_bufs(dev);
889 	if (ret)
890 		goto err;
891 
892 	ret = rtl2832_sdr_alloc_urbs(dev);
893 	if (ret)
894 		goto err;
895 
896 	dev->sequence = 0;
897 
898 	ret = rtl2832_sdr_submit_urbs(dev);
899 	if (ret)
900 		goto err;
901 
902 err:
903 	mutex_unlock(&dev->v4l2_lock);
904 
905 	return ret;
906 }
907 
908 static void rtl2832_sdr_stop_streaming(struct vb2_queue *vq)
909 {
910 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
911 	struct platform_device *pdev = dev->pdev;
912 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
913 	struct dvb_usb_device *d = pdata->dvb_usb_device;
914 
915 	dev_dbg(&pdev->dev, "\n");
916 
917 	mutex_lock(&dev->v4l2_lock);
918 
919 	rtl2832_sdr_kill_urbs(dev);
920 	rtl2832_sdr_free_urbs(dev);
921 	rtl2832_sdr_free_stream_bufs(dev);
922 	rtl2832_sdr_cleanup_queued_bufs(dev);
923 	rtl2832_sdr_unset_adc(dev);
924 
925 	/* sleep tuner */
926 	if (V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, core, s_power))
927 		v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 0);
928 	else
929 		rtl2832_sdr_unset_tuner(dev);
930 
931 	clear_bit(POWER_ON, &dev->flags);
932 
933 	/* disable ADC */
934 	if (d->props->frontend_ctrl)
935 		d->props->frontend_ctrl(pdata->dvb_frontend, 0);
936 
937 	if (d->props->power_ctrl)
938 		d->props->power_ctrl(d, 0);
939 
940 	mutex_unlock(&dev->v4l2_lock);
941 }
942 
943 static const struct vb2_ops rtl2832_sdr_vb2_ops = {
944 	.queue_setup            = rtl2832_sdr_queue_setup,
945 	.buf_prepare            = rtl2832_sdr_buf_prepare,
946 	.buf_queue              = rtl2832_sdr_buf_queue,
947 	.start_streaming        = rtl2832_sdr_start_streaming,
948 	.stop_streaming         = rtl2832_sdr_stop_streaming,
949 	.wait_prepare           = vb2_ops_wait_prepare,
950 	.wait_finish            = vb2_ops_wait_finish,
951 };
952 
953 static int rtl2832_sdr_g_tuner(struct file *file, void *priv,
954 		struct v4l2_tuner *v)
955 {
956 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
957 	struct platform_device *pdev = dev->pdev;
958 	int ret;
959 
960 	dev_dbg(&pdev->dev, "index=%d type=%d\n", v->index, v->type);
961 
962 	if (v->index == 0) {
963 		strscpy(v->name, "ADC: Realtek RTL2832", sizeof(v->name));
964 		v->type = V4L2_TUNER_ADC;
965 		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
966 		v->rangelow =   300000;
967 		v->rangehigh = 3200000;
968 		ret = 0;
969 	} else if (v->index == 1 &&
970 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, g_tuner)) {
971 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_tuner, v);
972 	} else if (v->index == 1) {
973 		strscpy(v->name, "RF: <unknown>", sizeof(v->name));
974 		v->type = V4L2_TUNER_RF;
975 		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
976 		v->rangelow =    50000000;
977 		v->rangehigh = 2000000000;
978 		ret = 0;
979 	} else {
980 		ret = -EINVAL;
981 	}
982 	return ret;
983 }
984 
985 static int rtl2832_sdr_s_tuner(struct file *file, void *priv,
986 		const struct v4l2_tuner *v)
987 {
988 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
989 	struct platform_device *pdev = dev->pdev;
990 	int ret;
991 
992 	dev_dbg(&pdev->dev, "\n");
993 
994 	if (v->index == 0) {
995 		ret = 0;
996 	} else if (v->index == 1 &&
997 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_tuner)) {
998 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_tuner, v);
999 	} else if (v->index == 1) {
1000 		ret = 0;
1001 	} else {
1002 		ret = -EINVAL;
1003 	}
1004 	return ret;
1005 }
1006 
1007 static int rtl2832_sdr_enum_freq_bands(struct file *file, void *priv,
1008 		struct v4l2_frequency_band *band)
1009 {
1010 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1011 	struct platform_device *pdev = dev->pdev;
1012 	int ret;
1013 
1014 	dev_dbg(&pdev->dev, "tuner=%d type=%d index=%d\n",
1015 		band->tuner, band->type, band->index);
1016 
1017 	if (band->tuner == 0) {
1018 		if (band->index >= ARRAY_SIZE(bands_adc))
1019 			return -EINVAL;
1020 
1021 		*band = bands_adc[band->index];
1022 		ret = 0;
1023 	} else if (band->tuner == 1 &&
1024 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, enum_freq_bands)) {
1025 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, enum_freq_bands, band);
1026 	} else if (band->tuner == 1) {
1027 		if (band->index >= ARRAY_SIZE(bands_fm))
1028 			return -EINVAL;
1029 
1030 		*band = bands_fm[band->index];
1031 		ret = 0;
1032 	} else {
1033 		ret = -EINVAL;
1034 	}
1035 	return ret;
1036 }
1037 
1038 static int rtl2832_sdr_g_frequency(struct file *file, void *priv,
1039 		struct v4l2_frequency *f)
1040 {
1041 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1042 	struct platform_device *pdev = dev->pdev;
1043 	int ret;
1044 
1045 	dev_dbg(&pdev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
1046 
1047 	if (f->tuner == 0) {
1048 		f->frequency = dev->f_adc;
1049 		f->type = V4L2_TUNER_ADC;
1050 		ret = 0;
1051 	} else if (f->tuner == 1 &&
1052 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, g_frequency)) {
1053 		f->type = V4L2_TUNER_RF;
1054 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_frequency, f);
1055 	} else if (f->tuner == 1) {
1056 		f->frequency = dev->f_tuner;
1057 		f->type = V4L2_TUNER_RF;
1058 		ret = 0;
1059 	} else {
1060 		ret = -EINVAL;
1061 	}
1062 	return ret;
1063 }
1064 
1065 static int rtl2832_sdr_s_frequency(struct file *file, void *priv,
1066 		const struct v4l2_frequency *f)
1067 {
1068 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1069 	struct platform_device *pdev = dev->pdev;
1070 	int ret, band;
1071 
1072 	dev_dbg(&pdev->dev, "tuner=%d type=%d frequency=%u\n",
1073 		f->tuner, f->type, f->frequency);
1074 
1075 	/* ADC band midpoints */
1076 	#define BAND_ADC_0 ((bands_adc[0].rangehigh + bands_adc[1].rangelow) / 2)
1077 	#define BAND_ADC_1 ((bands_adc[1].rangehigh + bands_adc[2].rangelow) / 2)
1078 
1079 	if (f->tuner == 0 && f->type == V4L2_TUNER_ADC) {
1080 		if (f->frequency < BAND_ADC_0)
1081 			band = 0;
1082 		else if (f->frequency < BAND_ADC_1)
1083 			band = 1;
1084 		else
1085 			band = 2;
1086 
1087 		dev->f_adc = clamp_t(unsigned int, f->frequency,
1088 				     bands_adc[band].rangelow,
1089 				     bands_adc[band].rangehigh);
1090 
1091 		dev_dbg(&pdev->dev, "ADC frequency=%u Hz\n", dev->f_adc);
1092 		ret = rtl2832_sdr_set_adc(dev);
1093 	} else if (f->tuner == 1 &&
1094 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_frequency)) {
1095 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_frequency, f);
1096 	} else if (f->tuner == 1) {
1097 		dev->f_tuner = clamp_t(unsigned int, f->frequency,
1098 				bands_fm[0].rangelow,
1099 				bands_fm[0].rangehigh);
1100 		dev_dbg(&pdev->dev, "RF frequency=%u Hz\n", f->frequency);
1101 
1102 		ret = rtl2832_sdr_set_tuner_freq(dev);
1103 	} else {
1104 		ret = -EINVAL;
1105 	}
1106 	return ret;
1107 }
1108 
1109 static int rtl2832_sdr_enum_fmt_sdr_cap(struct file *file, void *priv,
1110 		struct v4l2_fmtdesc *f)
1111 {
1112 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1113 	struct platform_device *pdev = dev->pdev;
1114 
1115 	dev_dbg(&pdev->dev, "\n");
1116 
1117 	if (f->index >= dev->num_formats)
1118 		return -EINVAL;
1119 
1120 	f->pixelformat = formats[f->index].pixelformat;
1121 
1122 	return 0;
1123 }
1124 
1125 static int rtl2832_sdr_g_fmt_sdr_cap(struct file *file, void *priv,
1126 		struct v4l2_format *f)
1127 {
1128 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1129 	struct platform_device *pdev = dev->pdev;
1130 
1131 	dev_dbg(&pdev->dev, "\n");
1132 
1133 	f->fmt.sdr.pixelformat = dev->pixelformat;
1134 	f->fmt.sdr.buffersize = dev->buffersize;
1135 
1136 	return 0;
1137 }
1138 
1139 static int rtl2832_sdr_s_fmt_sdr_cap(struct file *file, void *priv,
1140 		struct v4l2_format *f)
1141 {
1142 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1143 	struct platform_device *pdev = dev->pdev;
1144 	struct vb2_queue *q = &dev->vb_queue;
1145 	int i;
1146 
1147 	dev_dbg(&pdev->dev, "pixelformat fourcc %4.4s\n",
1148 		(char *)&f->fmt.sdr.pixelformat);
1149 
1150 	if (vb2_is_busy(q))
1151 		return -EBUSY;
1152 
1153 	for (i = 0; i < dev->num_formats; i++) {
1154 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
1155 			dev->pixelformat = formats[i].pixelformat;
1156 			dev->buffersize = formats[i].buffersize;
1157 			f->fmt.sdr.buffersize = formats[i].buffersize;
1158 			return 0;
1159 		}
1160 	}
1161 
1162 	dev->pixelformat = formats[0].pixelformat;
1163 	dev->buffersize = formats[0].buffersize;
1164 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
1165 	f->fmt.sdr.buffersize = formats[0].buffersize;
1166 
1167 	return 0;
1168 }
1169 
1170 static int rtl2832_sdr_try_fmt_sdr_cap(struct file *file, void *priv,
1171 		struct v4l2_format *f)
1172 {
1173 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1174 	struct platform_device *pdev = dev->pdev;
1175 	int i;
1176 
1177 	dev_dbg(&pdev->dev, "pixelformat fourcc %4.4s\n",
1178 		(char *)&f->fmt.sdr.pixelformat);
1179 
1180 	for (i = 0; i < dev->num_formats; i++) {
1181 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
1182 			f->fmt.sdr.buffersize = formats[i].buffersize;
1183 			return 0;
1184 		}
1185 	}
1186 
1187 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
1188 	f->fmt.sdr.buffersize = formats[0].buffersize;
1189 
1190 	return 0;
1191 }
1192 
1193 static const struct v4l2_ioctl_ops rtl2832_sdr_ioctl_ops = {
1194 	.vidioc_querycap          = rtl2832_sdr_querycap,
1195 
1196 	.vidioc_enum_fmt_sdr_cap  = rtl2832_sdr_enum_fmt_sdr_cap,
1197 	.vidioc_g_fmt_sdr_cap     = rtl2832_sdr_g_fmt_sdr_cap,
1198 	.vidioc_s_fmt_sdr_cap     = rtl2832_sdr_s_fmt_sdr_cap,
1199 	.vidioc_try_fmt_sdr_cap   = rtl2832_sdr_try_fmt_sdr_cap,
1200 
1201 	.vidioc_reqbufs           = vb2_ioctl_reqbufs,
1202 	.vidioc_create_bufs       = vb2_ioctl_create_bufs,
1203 	.vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1204 	.vidioc_querybuf          = vb2_ioctl_querybuf,
1205 	.vidioc_qbuf              = vb2_ioctl_qbuf,
1206 	.vidioc_dqbuf             = vb2_ioctl_dqbuf,
1207 
1208 	.vidioc_streamon          = vb2_ioctl_streamon,
1209 	.vidioc_streamoff         = vb2_ioctl_streamoff,
1210 
1211 	.vidioc_g_tuner           = rtl2832_sdr_g_tuner,
1212 	.vidioc_s_tuner           = rtl2832_sdr_s_tuner,
1213 
1214 	.vidioc_enum_freq_bands   = rtl2832_sdr_enum_freq_bands,
1215 	.vidioc_g_frequency       = rtl2832_sdr_g_frequency,
1216 	.vidioc_s_frequency       = rtl2832_sdr_s_frequency,
1217 
1218 	.vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1219 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1220 	.vidioc_log_status        = v4l2_ctrl_log_status,
1221 };
1222 
1223 static const struct v4l2_file_operations rtl2832_sdr_fops = {
1224 	.owner                    = THIS_MODULE,
1225 	.open                     = v4l2_fh_open,
1226 	.release                  = vb2_fop_release,
1227 	.read                     = vb2_fop_read,
1228 	.poll                     = vb2_fop_poll,
1229 	.mmap                     = vb2_fop_mmap,
1230 	.unlocked_ioctl           = video_ioctl2,
1231 };
1232 
1233 static struct video_device rtl2832_sdr_template = {
1234 	.name                     = "Realtek RTL2832 SDR",
1235 	.release                  = video_device_release_empty,
1236 	.fops                     = &rtl2832_sdr_fops,
1237 	.ioctl_ops                = &rtl2832_sdr_ioctl_ops,
1238 	.device_caps		  = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_STREAMING |
1239 				    V4L2_CAP_READWRITE | V4L2_CAP_TUNER,
1240 };
1241 
1242 static int rtl2832_sdr_s_ctrl(struct v4l2_ctrl *ctrl)
1243 {
1244 	struct rtl2832_sdr_dev *dev =
1245 			container_of(ctrl->handler, struct rtl2832_sdr_dev,
1246 					hdl);
1247 	struct platform_device *pdev = dev->pdev;
1248 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
1249 	struct dvb_frontend *fe = pdata->dvb_frontend;
1250 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1251 	int ret;
1252 
1253 	dev_dbg(&pdev->dev, "id=%d name=%s val=%d min=%lld max=%lld step=%lld\n",
1254 		ctrl->id, ctrl->name, ctrl->val, ctrl->minimum, ctrl->maximum,
1255 		ctrl->step);
1256 
1257 	switch (ctrl->id) {
1258 	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1259 	case V4L2_CID_RF_TUNER_BANDWIDTH:
1260 		/* TODO: these controls should be moved to tuner drivers */
1261 		if (dev->bandwidth_auto->val) {
1262 			/* Round towards the closest legal value */
1263 			s32 val = dev->f_adc + div_u64(dev->bandwidth->step, 2);
1264 			u32 offset;
1265 
1266 			val = clamp_t(s32, val, dev->bandwidth->minimum,
1267 				      dev->bandwidth->maximum);
1268 			offset = val - dev->bandwidth->minimum;
1269 			offset = dev->bandwidth->step *
1270 				div_u64(offset, dev->bandwidth->step);
1271 			dev->bandwidth->val = dev->bandwidth->minimum + offset;
1272 		}
1273 		c->bandwidth_hz = dev->bandwidth->val;
1274 
1275 		if (!test_bit(POWER_ON, &dev->flags))
1276 			return 0;
1277 
1278 		if (fe->ops.tuner_ops.set_params)
1279 			ret = fe->ops.tuner_ops.set_params(fe);
1280 		else
1281 			ret = 0;
1282 		break;
1283 	default:
1284 		ret = -EINVAL;
1285 	}
1286 
1287 	return ret;
1288 }
1289 
1290 static const struct v4l2_ctrl_ops rtl2832_sdr_ctrl_ops = {
1291 	.s_ctrl = rtl2832_sdr_s_ctrl,
1292 };
1293 
1294 static void rtl2832_sdr_video_release(struct v4l2_device *v)
1295 {
1296 	struct rtl2832_sdr_dev *dev =
1297 			container_of(v, struct rtl2832_sdr_dev, v4l2_dev);
1298 	struct platform_device *pdev = dev->pdev;
1299 
1300 	dev_dbg(&pdev->dev, "\n");
1301 
1302 	v4l2_ctrl_handler_free(&dev->hdl);
1303 	v4l2_device_unregister(&dev->v4l2_dev);
1304 	kfree(dev);
1305 }
1306 
1307 /* Platform driver interface */
1308 static int rtl2832_sdr_probe(struct platform_device *pdev)
1309 {
1310 	struct rtl2832_sdr_dev *dev;
1311 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
1312 	const struct v4l2_ctrl_ops *ops = &rtl2832_sdr_ctrl_ops;
1313 	struct v4l2_subdev *subdev;
1314 	int ret;
1315 
1316 	dev_dbg(&pdev->dev, "\n");
1317 
1318 	if (!pdata) {
1319 		dev_err(&pdev->dev, "Cannot proceed without platform data\n");
1320 		ret = -EINVAL;
1321 		goto err;
1322 	}
1323 	if (!pdev->dev.parent->driver) {
1324 		dev_dbg(&pdev->dev, "No parent device\n");
1325 		ret = -EINVAL;
1326 		goto err;
1327 	}
1328 	/* try to refcount host drv since we are the consumer */
1329 	if (!try_module_get(pdev->dev.parent->driver->owner)) {
1330 		dev_err(&pdev->dev, "Refcount fail");
1331 		ret = -EINVAL;
1332 		goto err;
1333 	}
1334 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1335 	if (dev == NULL) {
1336 		ret = -ENOMEM;
1337 		goto err_module_put;
1338 	}
1339 
1340 	/* setup the state */
1341 	subdev = pdata->v4l2_subdev;
1342 	dev->v4l2_subdev = pdata->v4l2_subdev;
1343 	dev->pdev = pdev;
1344 	dev->regmap = pdata->regmap;
1345 	dev->udev = pdata->dvb_usb_device->udev;
1346 	dev->f_adc = bands_adc[0].rangelow;
1347 	dev->f_tuner = bands_fm[0].rangelow;
1348 	dev->pixelformat = formats[0].pixelformat;
1349 	dev->buffersize = formats[0].buffersize;
1350 	dev->num_formats = NUM_FORMATS;
1351 	if (!rtl2832_sdr_emulated_fmt)
1352 		dev->num_formats -= 1;
1353 
1354 	mutex_init(&dev->v4l2_lock);
1355 	mutex_init(&dev->vb_queue_lock);
1356 	spin_lock_init(&dev->queued_bufs_lock);
1357 	INIT_LIST_HEAD(&dev->queued_bufs);
1358 
1359 	/* Init videobuf2 queue structure */
1360 	dev->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1361 	dev->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1362 	dev->vb_queue.drv_priv = dev;
1363 	dev->vb_queue.buf_struct_size = sizeof(struct rtl2832_sdr_frame_buf);
1364 	dev->vb_queue.ops = &rtl2832_sdr_vb2_ops;
1365 	dev->vb_queue.mem_ops = &vb2_vmalloc_memops;
1366 	dev->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1367 	ret = vb2_queue_init(&dev->vb_queue);
1368 	if (ret) {
1369 		dev_err(&pdev->dev, "Could not initialize vb2 queue\n");
1370 		goto err_kfree;
1371 	}
1372 
1373 	/* Register controls */
1374 	switch (pdata->tuner) {
1375 	case RTL2832_SDR_TUNER_E4000:
1376 		v4l2_ctrl_handler_init(&dev->hdl, 9);
1377 		if (subdev)
1378 			v4l2_ctrl_add_handler(&dev->hdl, subdev->ctrl_handler,
1379 					      NULL, true);
1380 		break;
1381 	case RTL2832_SDR_TUNER_R820T:
1382 	case RTL2832_SDR_TUNER_R828D:
1383 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1384 		dev->bandwidth_auto = v4l2_ctrl_new_std(&dev->hdl, ops,
1385 							V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1386 							0, 1, 1, 1);
1387 		dev->bandwidth = v4l2_ctrl_new_std(&dev->hdl, ops,
1388 						   V4L2_CID_RF_TUNER_BANDWIDTH,
1389 						   0, 8000000, 100000, 0);
1390 		v4l2_ctrl_auto_cluster(2, &dev->bandwidth_auto, 0, false);
1391 		break;
1392 	case RTL2832_SDR_TUNER_FC0012:
1393 	case RTL2832_SDR_TUNER_FC0013:
1394 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1395 		dev->bandwidth_auto = v4l2_ctrl_new_std(&dev->hdl, ops,
1396 							V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1397 							0, 1, 1, 1);
1398 		dev->bandwidth = v4l2_ctrl_new_std(&dev->hdl, ops,
1399 						   V4L2_CID_RF_TUNER_BANDWIDTH,
1400 						   6000000, 8000000, 1000000,
1401 						   6000000);
1402 		v4l2_ctrl_auto_cluster(2, &dev->bandwidth_auto, 0, false);
1403 		break;
1404 	case RTL2832_SDR_TUNER_FC2580:
1405 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1406 		if (subdev)
1407 			v4l2_ctrl_add_handler(&dev->hdl, subdev->ctrl_handler,
1408 					      NULL, true);
1409 		break;
1410 	default:
1411 		v4l2_ctrl_handler_init(&dev->hdl, 0);
1412 		dev_err(&pdev->dev, "Unsupported tuner\n");
1413 		ret = -ENODEV;
1414 		goto err_v4l2_ctrl_handler_free;
1415 	}
1416 	if (dev->hdl.error) {
1417 		ret = dev->hdl.error;
1418 		dev_err(&pdev->dev, "Could not initialize controls\n");
1419 		goto err_v4l2_ctrl_handler_free;
1420 	}
1421 
1422 	/* Init video_device structure */
1423 	dev->vdev = rtl2832_sdr_template;
1424 	dev->vdev.queue = &dev->vb_queue;
1425 	dev->vdev.queue->lock = &dev->vb_queue_lock;
1426 	video_set_drvdata(&dev->vdev, dev);
1427 
1428 	/* Register the v4l2_device structure */
1429 	dev->v4l2_dev.release = rtl2832_sdr_video_release;
1430 	ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
1431 	if (ret) {
1432 		dev_err(&pdev->dev, "Failed to register v4l2-device %d\n", ret);
1433 		goto err_v4l2_ctrl_handler_free;
1434 	}
1435 
1436 	dev->v4l2_dev.ctrl_handler = &dev->hdl;
1437 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
1438 	dev->vdev.lock = &dev->v4l2_lock;
1439 	dev->vdev.vfl_dir = VFL_DIR_RX;
1440 
1441 	ret = video_register_device(&dev->vdev, VFL_TYPE_SDR, -1);
1442 	if (ret) {
1443 		dev_err(&pdev->dev, "Failed to register as video device %d\n",
1444 			ret);
1445 		goto err_v4l2_device_unregister;
1446 	}
1447 	dev_info(&pdev->dev, "Registered as %s\n",
1448 		 video_device_node_name(&dev->vdev));
1449 	dev_info(&pdev->dev, "Realtek RTL2832 SDR attached\n");
1450 	dev_notice(&pdev->dev,
1451 		   "SDR API is still slightly experimental and functionality changes may follow\n");
1452 	platform_set_drvdata(pdev, dev);
1453 	return 0;
1454 err_v4l2_device_unregister:
1455 	v4l2_device_unregister(&dev->v4l2_dev);
1456 err_v4l2_ctrl_handler_free:
1457 	v4l2_ctrl_handler_free(&dev->hdl);
1458 err_kfree:
1459 	kfree(dev);
1460 err_module_put:
1461 	module_put(pdev->dev.parent->driver->owner);
1462 err:
1463 	return ret;
1464 }
1465 
1466 static int rtl2832_sdr_remove(struct platform_device *pdev)
1467 {
1468 	struct rtl2832_sdr_dev *dev = platform_get_drvdata(pdev);
1469 
1470 	dev_dbg(&pdev->dev, "\n");
1471 
1472 	mutex_lock(&dev->vb_queue_lock);
1473 	mutex_lock(&dev->v4l2_lock);
1474 	/* No need to keep the urbs around after disconnection */
1475 	dev->udev = NULL;
1476 	v4l2_device_disconnect(&dev->v4l2_dev);
1477 	video_unregister_device(&dev->vdev);
1478 	mutex_unlock(&dev->v4l2_lock);
1479 	mutex_unlock(&dev->vb_queue_lock);
1480 	v4l2_device_put(&dev->v4l2_dev);
1481 	module_put(pdev->dev.parent->driver->owner);
1482 
1483 	return 0;
1484 }
1485 
1486 static struct platform_driver rtl2832_sdr_driver = {
1487 	.driver = {
1488 		.name   = "rtl2832_sdr",
1489 	},
1490 	.probe          = rtl2832_sdr_probe,
1491 	.remove         = rtl2832_sdr_remove,
1492 };
1493 module_platform_driver(rtl2832_sdr_driver);
1494 
1495 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1496 MODULE_DESCRIPTION("Realtek RTL2832 SDR driver");
1497 MODULE_LICENSE("GPL");
1498