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