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 			for (j = 0; j < i; j++)
396 				usb_free_urb(dev->urb_list[j]);
397 			return -ENOMEM;
398 		}
399 		usb_fill_bulk_urb(dev->urb_list[i],
400 				dev->udev,
401 				usb_rcvbulkpipe(dev->udev, 0x81),
402 				dev->buf_list[i],
403 				BULK_BUFFER_SIZE,
404 				rtl2832_sdr_urb_complete, dev);
405 
406 		dev->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
407 		dev->urb_list[i]->transfer_dma = dev->dma_addr[i];
408 		dev->urbs_initialized++;
409 	}
410 
411 	return 0;
412 }
413 
414 /* Must be called with vb_queue_lock hold */
415 static void rtl2832_sdr_cleanup_queued_bufs(struct rtl2832_sdr_dev *dev)
416 {
417 	struct platform_device *pdev = dev->pdev;
418 	unsigned long flags;
419 
420 	dev_dbg(&pdev->dev, "\n");
421 
422 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
423 	while (!list_empty(&dev->queued_bufs)) {
424 		struct rtl2832_sdr_frame_buf *buf;
425 
426 		buf = list_entry(dev->queued_bufs.next,
427 				struct rtl2832_sdr_frame_buf, list);
428 		list_del(&buf->list);
429 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
430 	}
431 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
432 }
433 
434 static int rtl2832_sdr_querycap(struct file *file, void *fh,
435 		struct v4l2_capability *cap)
436 {
437 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
438 	struct platform_device *pdev = dev->pdev;
439 
440 	dev_dbg(&pdev->dev, "\n");
441 
442 	strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
443 	strlcpy(cap->card, dev->vdev.name, sizeof(cap->card));
444 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
445 	cap->device_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_STREAMING |
446 			V4L2_CAP_READWRITE | V4L2_CAP_TUNER;
447 	cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
448 	return 0;
449 }
450 
451 /* Videobuf2 operations */
452 static int rtl2832_sdr_queue_setup(struct vb2_queue *vq,
453 		unsigned int *nbuffers,
454 		unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[])
455 {
456 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
457 	struct platform_device *pdev = dev->pdev;
458 
459 	dev_dbg(&pdev->dev, "nbuffers=%d\n", *nbuffers);
460 
461 	/* Need at least 8 buffers */
462 	if (vq->num_buffers + *nbuffers < 8)
463 		*nbuffers = 8 - vq->num_buffers;
464 	*nplanes = 1;
465 	sizes[0] = PAGE_ALIGN(dev->buffersize);
466 	dev_dbg(&pdev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
467 	return 0;
468 }
469 
470 static int rtl2832_sdr_buf_prepare(struct vb2_buffer *vb)
471 {
472 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
473 
474 	/* Don't allow queing new buffers after device disconnection */
475 	if (!dev->udev)
476 		return -ENODEV;
477 
478 	return 0;
479 }
480 
481 static void rtl2832_sdr_buf_queue(struct vb2_buffer *vb)
482 {
483 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
484 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
485 	struct rtl2832_sdr_frame_buf *buf =
486 			container_of(vbuf, struct rtl2832_sdr_frame_buf, vb);
487 	unsigned long flags;
488 
489 	/* Check the device has not disconnected between prep and queuing */
490 	if (!dev->udev) {
491 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
492 		return;
493 	}
494 
495 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
496 	list_add_tail(&buf->list, &dev->queued_bufs);
497 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
498 }
499 
500 static int rtl2832_sdr_set_adc(struct rtl2832_sdr_dev *dev)
501 {
502 	struct platform_device *pdev = dev->pdev;
503 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
504 	struct dvb_frontend *fe = pdata->dvb_frontend;
505 	int ret;
506 	unsigned int f_sr, f_if;
507 	u8 buf[4], u8tmp1, u8tmp2;
508 	u64 u64tmp;
509 	u32 u32tmp;
510 
511 	dev_dbg(&pdev->dev, "f_adc=%u\n", dev->f_adc);
512 
513 	if (!test_bit(POWER_ON, &dev->flags))
514 		return 0;
515 
516 	if (dev->f_adc == 0)
517 		return 0;
518 
519 	f_sr = dev->f_adc;
520 
521 	ret = regmap_bulk_write(dev->regmap, 0x13e, "\x00\x00", 2);
522 	if (ret)
523 		goto err;
524 
525 	ret = regmap_bulk_write(dev->regmap, 0x115, "\x00\x00\x00\x00", 4);
526 	if (ret)
527 		goto err;
528 
529 	/* get IF from tuner */
530 	if (fe->ops.tuner_ops.get_if_frequency)
531 		ret = fe->ops.tuner_ops.get_if_frequency(fe, &f_if);
532 	else
533 		ret = -EINVAL;
534 
535 	if (ret)
536 		goto err;
537 
538 	/* program IF */
539 	u64tmp = f_if % pdata->clk;
540 	u64tmp *= 0x400000;
541 	u64tmp = div_u64(u64tmp, pdata->clk);
542 	u64tmp = -u64tmp;
543 	u32tmp = u64tmp & 0x3fffff;
544 
545 	dev_dbg(&pdev->dev, "f_if=%u if_ctl=%08x\n", f_if, u32tmp);
546 
547 	buf[0] = (u32tmp >> 16) & 0xff;
548 	buf[1] = (u32tmp >>  8) & 0xff;
549 	buf[2] = (u32tmp >>  0) & 0xff;
550 
551 	ret = regmap_bulk_write(dev->regmap, 0x119, buf, 3);
552 	if (ret)
553 		goto err;
554 
555 	/* BB / IF mode */
556 	/* POR: 0x1b1=0x1f, 0x008=0x0d, 0x006=0x80 */
557 	if (f_if) {
558 		u8tmp1 = 0x1a; /* disable Zero-IF */
559 		u8tmp2 = 0x8d; /* enable ADC I */
560 	} else {
561 		u8tmp1 = 0x1b; /* enable Zero-IF, DC, IQ */
562 		u8tmp2 = 0xcd; /* enable ADC I, ADC Q */
563 	}
564 
565 	ret = regmap_write(dev->regmap, 0x1b1, u8tmp1);
566 	if (ret)
567 		goto err;
568 
569 	ret = regmap_write(dev->regmap, 0x008, u8tmp2);
570 	if (ret)
571 		goto err;
572 
573 	ret = regmap_write(dev->regmap, 0x006, 0x80);
574 	if (ret)
575 		goto err;
576 
577 	/* program sampling rate (resampling down) */
578 	u32tmp = div_u64(pdata->clk * 0x400000ULL, f_sr * 4U);
579 	u32tmp <<= 2;
580 	buf[0] = (u32tmp >> 24) & 0xff;
581 	buf[1] = (u32tmp >> 16) & 0xff;
582 	buf[2] = (u32tmp >>  8) & 0xff;
583 	buf[3] = (u32tmp >>  0) & 0xff;
584 	ret = regmap_bulk_write(dev->regmap, 0x19f, buf, 4);
585 	if (ret)
586 		goto err;
587 
588 	/* low-pass filter */
589 	ret = regmap_bulk_write(dev->regmap, 0x11c,
590 				"\xca\xdc\xd7\xd8\xe0\xf2\x0e\x35\x06\x50\x9c\x0d\x71\x11\x14\x71\x74\x19\x41\xa5",
591 				20);
592 	if (ret)
593 		goto err;
594 
595 	ret = regmap_bulk_write(dev->regmap, 0x017, "\x11\x10", 2);
596 	if (ret)
597 		goto err;
598 
599 	/* mode */
600 	ret = regmap_write(dev->regmap, 0x019, 0x05);
601 	if (ret)
602 		goto err;
603 
604 	ret = regmap_bulk_write(dev->regmap, 0x01a,
605 				"\x1b\x16\x0d\x06\x01\xff", 6);
606 	if (ret)
607 		goto err;
608 
609 	/* FSM */
610 	ret = regmap_bulk_write(dev->regmap, 0x192, "\x00\xf0\x0f", 3);
611 	if (ret)
612 		goto err;
613 
614 	/* PID filter */
615 	ret = regmap_write(dev->regmap, 0x061, 0x60);
616 	if (ret)
617 		goto err;
618 
619 	/* used RF tuner based settings */
620 	switch (pdata->tuner) {
621 	case RTL2832_SDR_TUNER_E4000:
622 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
623 		ret = regmap_write(dev->regmap, 0x102, 0x40);
624 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
625 		ret = regmap_write(dev->regmap, 0x1c7, 0x30);
626 		ret = regmap_write(dev->regmap, 0x104, 0xd0);
627 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
628 		ret = regmap_write(dev->regmap, 0x1c8, 0x18);
629 		ret = regmap_write(dev->regmap, 0x106, 0x35);
630 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
631 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
632 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
633 		ret = regmap_write(dev->regmap, 0x107, 0x40);
634 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
635 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
636 		ret = regmap_write(dev->regmap, 0x108, 0x80);
637 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
638 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
639 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
640 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
641 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
642 		ret = regmap_write(dev->regmap, 0x011, 0xd4);
643 		ret = regmap_write(dev->regmap, 0x1e5, 0xf0);
644 		ret = regmap_write(dev->regmap, 0x1d9, 0x00);
645 		ret = regmap_write(dev->regmap, 0x1db, 0x00);
646 		ret = regmap_write(dev->regmap, 0x1dd, 0x14);
647 		ret = regmap_write(dev->regmap, 0x1de, 0xec);
648 		ret = regmap_write(dev->regmap, 0x1d8, 0x0c);
649 		ret = regmap_write(dev->regmap, 0x1e6, 0x02);
650 		ret = regmap_write(dev->regmap, 0x1d7, 0x09);
651 		ret = regmap_write(dev->regmap, 0x00d, 0x83);
652 		ret = regmap_write(dev->regmap, 0x010, 0x49);
653 		ret = regmap_write(dev->regmap, 0x00d, 0x87);
654 		ret = regmap_write(dev->regmap, 0x00d, 0x85);
655 		ret = regmap_write(dev->regmap, 0x013, 0x02);
656 		break;
657 	case RTL2832_SDR_TUNER_FC0012:
658 	case RTL2832_SDR_TUNER_FC0013:
659 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
660 		ret = regmap_write(dev->regmap, 0x102, 0x40);
661 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
662 		ret = regmap_write(dev->regmap, 0x1c7, 0x2c);
663 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
664 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
665 		ret = regmap_write(dev->regmap, 0x1c8, 0x16);
666 		ret = regmap_write(dev->regmap, 0x106, 0x35);
667 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
668 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
669 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
670 		ret = regmap_write(dev->regmap, 0x107, 0x40);
671 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
672 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
673 		ret = regmap_write(dev->regmap, 0x108, 0x80);
674 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
675 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
676 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
677 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
678 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
679 		ret = regmap_bulk_write(dev->regmap, 0x011, "\xe9\xbf", 2);
680 		ret = regmap_write(dev->regmap, 0x1e5, 0xf0);
681 		ret = regmap_write(dev->regmap, 0x1d9, 0x00);
682 		ret = regmap_write(dev->regmap, 0x1db, 0x00);
683 		ret = regmap_write(dev->regmap, 0x1dd, 0x11);
684 		ret = regmap_write(dev->regmap, 0x1de, 0xef);
685 		ret = regmap_write(dev->regmap, 0x1d8, 0x0c);
686 		ret = regmap_write(dev->regmap, 0x1e6, 0x02);
687 		ret = regmap_write(dev->regmap, 0x1d7, 0x09);
688 		break;
689 	case RTL2832_SDR_TUNER_R820T:
690 	case RTL2832_SDR_TUNER_R828D:
691 		ret = regmap_write(dev->regmap, 0x112, 0x5a);
692 		ret = regmap_write(dev->regmap, 0x102, 0x40);
693 		ret = regmap_write(dev->regmap, 0x115, 0x01);
694 		ret = regmap_write(dev->regmap, 0x103, 0x80);
695 		ret = regmap_write(dev->regmap, 0x1c7, 0x24);
696 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
697 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
698 		ret = regmap_write(dev->regmap, 0x1c8, 0x14);
699 		ret = regmap_write(dev->regmap, 0x106, 0x35);
700 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
701 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
702 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
703 		ret = regmap_write(dev->regmap, 0x107, 0x40);
704 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
705 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
706 		ret = regmap_write(dev->regmap, 0x108, 0x80);
707 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
708 		ret = regmap_write(dev->regmap, 0x10a, 0x80);
709 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
710 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
711 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
712 		ret = regmap_write(dev->regmap, 0x011, 0xf4);
713 		break;
714 	case RTL2832_SDR_TUNER_FC2580:
715 		ret = regmap_write(dev->regmap, 0x112, 0x39);
716 		ret = regmap_write(dev->regmap, 0x102, 0x40);
717 		ret = regmap_write(dev->regmap, 0x103, 0x5a);
718 		ret = regmap_write(dev->regmap, 0x1c7, 0x2c);
719 		ret = regmap_write(dev->regmap, 0x104, 0xcc);
720 		ret = regmap_write(dev->regmap, 0x105, 0xbe);
721 		ret = regmap_write(dev->regmap, 0x1c8, 0x16);
722 		ret = regmap_write(dev->regmap, 0x106, 0x35);
723 		ret = regmap_write(dev->regmap, 0x1c9, 0x21);
724 		ret = regmap_write(dev->regmap, 0x1ca, 0x21);
725 		ret = regmap_write(dev->regmap, 0x1cb, 0x00);
726 		ret = regmap_write(dev->regmap, 0x107, 0x40);
727 		ret = regmap_write(dev->regmap, 0x1cd, 0x10);
728 		ret = regmap_write(dev->regmap, 0x1ce, 0x10);
729 		ret = regmap_write(dev->regmap, 0x108, 0x80);
730 		ret = regmap_write(dev->regmap, 0x109, 0x7f);
731 		ret = regmap_write(dev->regmap, 0x10a, 0x9c);
732 		ret = regmap_write(dev->regmap, 0x10b, 0x7f);
733 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
734 		ret = regmap_write(dev->regmap, 0x00e, 0xfc);
735 		ret = regmap_bulk_write(dev->regmap, 0x011, "\xe9\xf4", 2);
736 		break;
737 	default:
738 		dev_notice(&pdev->dev, "Unsupported tuner\n");
739 	}
740 
741 	/* software reset */
742 	ret = regmap_update_bits(dev->regmap, 0x101, 0x04, 0x04);
743 	if (ret)
744 		goto err;
745 
746 	ret = regmap_update_bits(dev->regmap, 0x101, 0x04, 0x00);
747 	if (ret)
748 		goto err;
749 err:
750 	return ret;
751 };
752 
753 static void rtl2832_sdr_unset_adc(struct rtl2832_sdr_dev *dev)
754 {
755 	struct platform_device *pdev = dev->pdev;
756 	int ret;
757 
758 	dev_dbg(&pdev->dev, "\n");
759 
760 	/* PID filter */
761 	ret = regmap_write(dev->regmap, 0x061, 0xe0);
762 	if (ret)
763 		goto err;
764 
765 	/* mode */
766 	ret = regmap_write(dev->regmap, 0x019, 0x20);
767 	if (ret)
768 		goto err;
769 
770 	ret = regmap_bulk_write(dev->regmap, 0x017, "\x11\x10", 2);
771 	if (ret)
772 		goto err;
773 
774 	/* FSM */
775 	ret = regmap_bulk_write(dev->regmap, 0x192, "\x00\x0f\xff", 3);
776 	if (ret)
777 		goto err;
778 
779 	ret = regmap_bulk_write(dev->regmap, 0x13e, "\x40\x00", 2);
780 	if (ret)
781 		goto err;
782 
783 	ret = regmap_bulk_write(dev->regmap, 0x115, "\x06\x3f\xce\xcc", 4);
784 	if (ret)
785 		goto err;
786 err:
787 	return;
788 };
789 
790 static int rtl2832_sdr_set_tuner_freq(struct rtl2832_sdr_dev *dev)
791 {
792 	struct platform_device *pdev = dev->pdev;
793 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
794 	struct dvb_frontend *fe = pdata->dvb_frontend;
795 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
796 	struct v4l2_ctrl *bandwidth_auto;
797 	struct v4l2_ctrl *bandwidth;
798 
799 	/*
800 	 * tuner RF (Hz)
801 	 */
802 	if (dev->f_tuner == 0)
803 		return 0;
804 
805 	/*
806 	 * bandwidth (Hz)
807 	 */
808 	bandwidth_auto = v4l2_ctrl_find(&dev->hdl,
809 					V4L2_CID_RF_TUNER_BANDWIDTH_AUTO);
810 	bandwidth = v4l2_ctrl_find(&dev->hdl, V4L2_CID_RF_TUNER_BANDWIDTH);
811 	if (v4l2_ctrl_g_ctrl(bandwidth_auto)) {
812 		c->bandwidth_hz = dev->f_adc;
813 		v4l2_ctrl_s_ctrl(bandwidth, dev->f_adc);
814 	} else {
815 		c->bandwidth_hz = v4l2_ctrl_g_ctrl(bandwidth);
816 	}
817 
818 	c->frequency = dev->f_tuner;
819 	c->delivery_system = SYS_DVBT;
820 
821 	dev_dbg(&pdev->dev, "frequency=%u bandwidth=%d\n",
822 		c->frequency, c->bandwidth_hz);
823 
824 	if (!test_bit(POWER_ON, &dev->flags))
825 		return 0;
826 
827 	if (!V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_frequency)) {
828 		if (fe->ops.tuner_ops.set_params)
829 			fe->ops.tuner_ops.set_params(fe);
830 	}
831 
832 	return 0;
833 };
834 
835 static int rtl2832_sdr_set_tuner(struct rtl2832_sdr_dev *dev)
836 {
837 	struct platform_device *pdev = dev->pdev;
838 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
839 	struct dvb_frontend *fe = pdata->dvb_frontend;
840 
841 	dev_dbg(&pdev->dev, "\n");
842 
843 	if (fe->ops.tuner_ops.init)
844 		fe->ops.tuner_ops.init(fe);
845 
846 	return 0;
847 };
848 
849 static void rtl2832_sdr_unset_tuner(struct rtl2832_sdr_dev *dev)
850 {
851 	struct platform_device *pdev = dev->pdev;
852 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
853 	struct dvb_frontend *fe = pdata->dvb_frontend;
854 
855 	dev_dbg(&pdev->dev, "\n");
856 
857 	if (fe->ops.tuner_ops.sleep)
858 		fe->ops.tuner_ops.sleep(fe);
859 
860 	return;
861 };
862 
863 static int rtl2832_sdr_start_streaming(struct vb2_queue *vq, unsigned int count)
864 {
865 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
866 	struct platform_device *pdev = dev->pdev;
867 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
868 	struct dvb_usb_device *d = pdata->dvb_usb_device;
869 	int ret;
870 
871 	dev_dbg(&pdev->dev, "\n");
872 
873 	if (!dev->udev)
874 		return -ENODEV;
875 
876 	if (mutex_lock_interruptible(&dev->v4l2_lock))
877 		return -ERESTARTSYS;
878 
879 	if (d->props->power_ctrl)
880 		d->props->power_ctrl(d, 1);
881 
882 	/* enable ADC */
883 	if (d->props->frontend_ctrl)
884 		d->props->frontend_ctrl(pdata->dvb_frontend, 1);
885 
886 	set_bit(POWER_ON, &dev->flags);
887 
888 	/* wake-up tuner */
889 	if (V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, core, s_power))
890 		ret = v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 1);
891 	else
892 		ret = rtl2832_sdr_set_tuner(dev);
893 	if (ret)
894 		goto err;
895 
896 	ret = rtl2832_sdr_set_tuner_freq(dev);
897 	if (ret)
898 		goto err;
899 
900 	ret = rtl2832_sdr_set_adc(dev);
901 	if (ret)
902 		goto err;
903 
904 	ret = rtl2832_sdr_alloc_stream_bufs(dev);
905 	if (ret)
906 		goto err;
907 
908 	ret = rtl2832_sdr_alloc_urbs(dev);
909 	if (ret)
910 		goto err;
911 
912 	dev->sequence = 0;
913 
914 	ret = rtl2832_sdr_submit_urbs(dev);
915 	if (ret)
916 		goto err;
917 
918 err:
919 	mutex_unlock(&dev->v4l2_lock);
920 
921 	return ret;
922 }
923 
924 static void rtl2832_sdr_stop_streaming(struct vb2_queue *vq)
925 {
926 	struct rtl2832_sdr_dev *dev = vb2_get_drv_priv(vq);
927 	struct platform_device *pdev = dev->pdev;
928 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
929 	struct dvb_usb_device *d = pdata->dvb_usb_device;
930 
931 	dev_dbg(&pdev->dev, "\n");
932 
933 	mutex_lock(&dev->v4l2_lock);
934 
935 	rtl2832_sdr_kill_urbs(dev);
936 	rtl2832_sdr_free_urbs(dev);
937 	rtl2832_sdr_free_stream_bufs(dev);
938 	rtl2832_sdr_cleanup_queued_bufs(dev);
939 	rtl2832_sdr_unset_adc(dev);
940 
941 	/* sleep tuner */
942 	if (V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, core, s_power))
943 		v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 0);
944 	else
945 		rtl2832_sdr_unset_tuner(dev);
946 
947 	clear_bit(POWER_ON, &dev->flags);
948 
949 	/* disable ADC */
950 	if (d->props->frontend_ctrl)
951 		d->props->frontend_ctrl(pdata->dvb_frontend, 0);
952 
953 	if (d->props->power_ctrl)
954 		d->props->power_ctrl(d, 0);
955 
956 	mutex_unlock(&dev->v4l2_lock);
957 }
958 
959 static const struct vb2_ops rtl2832_sdr_vb2_ops = {
960 	.queue_setup            = rtl2832_sdr_queue_setup,
961 	.buf_prepare            = rtl2832_sdr_buf_prepare,
962 	.buf_queue              = rtl2832_sdr_buf_queue,
963 	.start_streaming        = rtl2832_sdr_start_streaming,
964 	.stop_streaming         = rtl2832_sdr_stop_streaming,
965 	.wait_prepare           = vb2_ops_wait_prepare,
966 	.wait_finish            = vb2_ops_wait_finish,
967 };
968 
969 static int rtl2832_sdr_g_tuner(struct file *file, void *priv,
970 		struct v4l2_tuner *v)
971 {
972 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
973 	struct platform_device *pdev = dev->pdev;
974 	int ret;
975 
976 	dev_dbg(&pdev->dev, "index=%d type=%d\n", v->index, v->type);
977 
978 	if (v->index == 0) {
979 		strlcpy(v->name, "ADC: Realtek RTL2832", sizeof(v->name));
980 		v->type = V4L2_TUNER_ADC;
981 		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
982 		v->rangelow =   300000;
983 		v->rangehigh = 3200000;
984 		ret = 0;
985 	} else if (v->index == 1 &&
986 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, g_tuner)) {
987 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_tuner, v);
988 	} else if (v->index == 1) {
989 		strlcpy(v->name, "RF: <unknown>", sizeof(v->name));
990 		v->type = V4L2_TUNER_RF;
991 		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
992 		v->rangelow =    50000000;
993 		v->rangehigh = 2000000000;
994 		ret = 0;
995 	} else {
996 		ret = -EINVAL;
997 	}
998 	return ret;
999 }
1000 
1001 static int rtl2832_sdr_s_tuner(struct file *file, void *priv,
1002 		const struct v4l2_tuner *v)
1003 {
1004 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1005 	struct platform_device *pdev = dev->pdev;
1006 	int ret;
1007 
1008 	dev_dbg(&pdev->dev, "\n");
1009 
1010 	if (v->index == 0) {
1011 		ret = 0;
1012 	} else if (v->index == 1 &&
1013 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_tuner)) {
1014 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_tuner, v);
1015 	} else if (v->index == 1) {
1016 		ret = 0;
1017 	} else {
1018 		ret = -EINVAL;
1019 	}
1020 	return ret;
1021 }
1022 
1023 static int rtl2832_sdr_enum_freq_bands(struct file *file, void *priv,
1024 		struct v4l2_frequency_band *band)
1025 {
1026 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1027 	struct platform_device *pdev = dev->pdev;
1028 	int ret;
1029 
1030 	dev_dbg(&pdev->dev, "tuner=%d type=%d index=%d\n",
1031 		band->tuner, band->type, band->index);
1032 
1033 	if (band->tuner == 0) {
1034 		if (band->index >= ARRAY_SIZE(bands_adc))
1035 			return -EINVAL;
1036 
1037 		*band = bands_adc[band->index];
1038 		ret = 0;
1039 	} else if (band->tuner == 1 &&
1040 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, enum_freq_bands)) {
1041 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, enum_freq_bands, band);
1042 	} else if (band->tuner == 1) {
1043 		if (band->index >= ARRAY_SIZE(bands_fm))
1044 			return -EINVAL;
1045 
1046 		*band = bands_fm[band->index];
1047 		ret = 0;
1048 	} else {
1049 		ret = -EINVAL;
1050 	}
1051 	return ret;
1052 }
1053 
1054 static int rtl2832_sdr_g_frequency(struct file *file, void *priv,
1055 		struct v4l2_frequency *f)
1056 {
1057 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1058 	struct platform_device *pdev = dev->pdev;
1059 	int ret;
1060 
1061 	dev_dbg(&pdev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
1062 
1063 	if (f->tuner == 0) {
1064 		f->frequency = dev->f_adc;
1065 		f->type = V4L2_TUNER_ADC;
1066 		ret = 0;
1067 	} else if (f->tuner == 1 &&
1068 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, g_frequency)) {
1069 		f->type = V4L2_TUNER_RF;
1070 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_frequency, f);
1071 	} else if (f->tuner == 1) {
1072 		f->frequency = dev->f_tuner;
1073 		f->type = V4L2_TUNER_RF;
1074 		ret = 0;
1075 	} else {
1076 		ret = -EINVAL;
1077 	}
1078 	return ret;
1079 }
1080 
1081 static int rtl2832_sdr_s_frequency(struct file *file, void *priv,
1082 		const struct v4l2_frequency *f)
1083 {
1084 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1085 	struct platform_device *pdev = dev->pdev;
1086 	int ret, band;
1087 
1088 	dev_dbg(&pdev->dev, "tuner=%d type=%d frequency=%u\n",
1089 		f->tuner, f->type, f->frequency);
1090 
1091 	/* ADC band midpoints */
1092 	#define BAND_ADC_0 ((bands_adc[0].rangehigh + bands_adc[1].rangelow) / 2)
1093 	#define BAND_ADC_1 ((bands_adc[1].rangehigh + bands_adc[2].rangelow) / 2)
1094 
1095 	if (f->tuner == 0 && f->type == V4L2_TUNER_ADC) {
1096 		if (f->frequency < BAND_ADC_0)
1097 			band = 0;
1098 		else if (f->frequency < BAND_ADC_1)
1099 			band = 1;
1100 		else
1101 			band = 2;
1102 
1103 		dev->f_adc = clamp_t(unsigned int, f->frequency,
1104 				     bands_adc[band].rangelow,
1105 				     bands_adc[band].rangehigh);
1106 
1107 		dev_dbg(&pdev->dev, "ADC frequency=%u Hz\n", dev->f_adc);
1108 		ret = rtl2832_sdr_set_adc(dev);
1109 	} else if (f->tuner == 1 &&
1110 		   V4L2_SUBDEV_HAS_OP(dev->v4l2_subdev, tuner, s_frequency)) {
1111 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_frequency, f);
1112 	} else if (f->tuner == 1) {
1113 		dev->f_tuner = clamp_t(unsigned int, f->frequency,
1114 				bands_fm[0].rangelow,
1115 				bands_fm[0].rangehigh);
1116 		dev_dbg(&pdev->dev, "RF frequency=%u Hz\n", f->frequency);
1117 
1118 		ret = rtl2832_sdr_set_tuner_freq(dev);
1119 	} else {
1120 		ret = -EINVAL;
1121 	}
1122 	return ret;
1123 }
1124 
1125 static int rtl2832_sdr_enum_fmt_sdr_cap(struct file *file, void *priv,
1126 		struct v4l2_fmtdesc *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 	if (f->index >= dev->num_formats)
1134 		return -EINVAL;
1135 
1136 	strlcpy(f->description, formats[f->index].name, sizeof(f->description));
1137 	f->pixelformat = formats[f->index].pixelformat;
1138 
1139 	return 0;
1140 }
1141 
1142 static int rtl2832_sdr_g_fmt_sdr_cap(struct file *file, void *priv,
1143 		struct v4l2_format *f)
1144 {
1145 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1146 	struct platform_device *pdev = dev->pdev;
1147 
1148 	dev_dbg(&pdev->dev, "\n");
1149 
1150 	f->fmt.sdr.pixelformat = dev->pixelformat;
1151 	f->fmt.sdr.buffersize = dev->buffersize;
1152 
1153 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
1154 
1155 	return 0;
1156 }
1157 
1158 static int rtl2832_sdr_s_fmt_sdr_cap(struct file *file, void *priv,
1159 		struct v4l2_format *f)
1160 {
1161 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1162 	struct platform_device *pdev = dev->pdev;
1163 	struct vb2_queue *q = &dev->vb_queue;
1164 	int i;
1165 
1166 	dev_dbg(&pdev->dev, "pixelformat fourcc %4.4s\n",
1167 		(char *)&f->fmt.sdr.pixelformat);
1168 
1169 	if (vb2_is_busy(q))
1170 		return -EBUSY;
1171 
1172 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
1173 	for (i = 0; i < dev->num_formats; i++) {
1174 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
1175 			dev->pixelformat = formats[i].pixelformat;
1176 			dev->buffersize = formats[i].buffersize;
1177 			f->fmt.sdr.buffersize = formats[i].buffersize;
1178 			return 0;
1179 		}
1180 	}
1181 
1182 	dev->pixelformat = formats[0].pixelformat;
1183 	dev->buffersize = formats[0].buffersize;
1184 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
1185 	f->fmt.sdr.buffersize = formats[0].buffersize;
1186 
1187 	return 0;
1188 }
1189 
1190 static int rtl2832_sdr_try_fmt_sdr_cap(struct file *file, void *priv,
1191 		struct v4l2_format *f)
1192 {
1193 	struct rtl2832_sdr_dev *dev = video_drvdata(file);
1194 	struct platform_device *pdev = dev->pdev;
1195 	int i;
1196 
1197 	dev_dbg(&pdev->dev, "pixelformat fourcc %4.4s\n",
1198 		(char *)&f->fmt.sdr.pixelformat);
1199 
1200 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
1201 	for (i = 0; i < dev->num_formats; i++) {
1202 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
1203 			f->fmt.sdr.buffersize = formats[i].buffersize;
1204 			return 0;
1205 		}
1206 	}
1207 
1208 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
1209 	f->fmt.sdr.buffersize = formats[0].buffersize;
1210 
1211 	return 0;
1212 }
1213 
1214 static const struct v4l2_ioctl_ops rtl2832_sdr_ioctl_ops = {
1215 	.vidioc_querycap          = rtl2832_sdr_querycap,
1216 
1217 	.vidioc_enum_fmt_sdr_cap  = rtl2832_sdr_enum_fmt_sdr_cap,
1218 	.vidioc_g_fmt_sdr_cap     = rtl2832_sdr_g_fmt_sdr_cap,
1219 	.vidioc_s_fmt_sdr_cap     = rtl2832_sdr_s_fmt_sdr_cap,
1220 	.vidioc_try_fmt_sdr_cap   = rtl2832_sdr_try_fmt_sdr_cap,
1221 
1222 	.vidioc_reqbufs           = vb2_ioctl_reqbufs,
1223 	.vidioc_create_bufs       = vb2_ioctl_create_bufs,
1224 	.vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1225 	.vidioc_querybuf          = vb2_ioctl_querybuf,
1226 	.vidioc_qbuf              = vb2_ioctl_qbuf,
1227 	.vidioc_dqbuf             = vb2_ioctl_dqbuf,
1228 
1229 	.vidioc_streamon          = vb2_ioctl_streamon,
1230 	.vidioc_streamoff         = vb2_ioctl_streamoff,
1231 
1232 	.vidioc_g_tuner           = rtl2832_sdr_g_tuner,
1233 	.vidioc_s_tuner           = rtl2832_sdr_s_tuner,
1234 
1235 	.vidioc_enum_freq_bands   = rtl2832_sdr_enum_freq_bands,
1236 	.vidioc_g_frequency       = rtl2832_sdr_g_frequency,
1237 	.vidioc_s_frequency       = rtl2832_sdr_s_frequency,
1238 
1239 	.vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1240 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1241 	.vidioc_log_status        = v4l2_ctrl_log_status,
1242 };
1243 
1244 static const struct v4l2_file_operations rtl2832_sdr_fops = {
1245 	.owner                    = THIS_MODULE,
1246 	.open                     = v4l2_fh_open,
1247 	.release                  = vb2_fop_release,
1248 	.read                     = vb2_fop_read,
1249 	.poll                     = vb2_fop_poll,
1250 	.mmap                     = vb2_fop_mmap,
1251 	.unlocked_ioctl           = video_ioctl2,
1252 };
1253 
1254 static struct video_device rtl2832_sdr_template = {
1255 	.name                     = "Realtek RTL2832 SDR",
1256 	.release                  = video_device_release_empty,
1257 	.fops                     = &rtl2832_sdr_fops,
1258 	.ioctl_ops                = &rtl2832_sdr_ioctl_ops,
1259 };
1260 
1261 static int rtl2832_sdr_s_ctrl(struct v4l2_ctrl *ctrl)
1262 {
1263 	struct rtl2832_sdr_dev *dev =
1264 			container_of(ctrl->handler, struct rtl2832_sdr_dev,
1265 					hdl);
1266 	struct platform_device *pdev = dev->pdev;
1267 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
1268 	struct dvb_frontend *fe = pdata->dvb_frontend;
1269 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1270 	int ret;
1271 
1272 	dev_dbg(&pdev->dev, "id=%d name=%s val=%d min=%lld max=%lld step=%lld\n",
1273 		ctrl->id, ctrl->name, ctrl->val, ctrl->minimum, ctrl->maximum,
1274 		ctrl->step);
1275 
1276 	switch (ctrl->id) {
1277 	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1278 	case V4L2_CID_RF_TUNER_BANDWIDTH:
1279 		/* TODO: these controls should be moved to tuner drivers */
1280 		if (dev->bandwidth_auto->val) {
1281 			/* Round towards the closest legal value */
1282 			s32 val = dev->f_adc + div_u64(dev->bandwidth->step, 2);
1283 			u32 offset;
1284 
1285 			val = clamp_t(s32, val, dev->bandwidth->minimum,
1286 				      dev->bandwidth->maximum);
1287 			offset = val - dev->bandwidth->minimum;
1288 			offset = dev->bandwidth->step *
1289 				div_u64(offset, dev->bandwidth->step);
1290 			dev->bandwidth->val = dev->bandwidth->minimum + offset;
1291 		}
1292 		c->bandwidth_hz = dev->bandwidth->val;
1293 
1294 		if (!test_bit(POWER_ON, &dev->flags))
1295 			return 0;
1296 
1297 		if (fe->ops.tuner_ops.set_params)
1298 			ret = fe->ops.tuner_ops.set_params(fe);
1299 		else
1300 			ret = 0;
1301 		break;
1302 	default:
1303 		ret = -EINVAL;
1304 	}
1305 
1306 	return ret;
1307 }
1308 
1309 static const struct v4l2_ctrl_ops rtl2832_sdr_ctrl_ops = {
1310 	.s_ctrl = rtl2832_sdr_s_ctrl,
1311 };
1312 
1313 static void rtl2832_sdr_video_release(struct v4l2_device *v)
1314 {
1315 	struct rtl2832_sdr_dev *dev =
1316 			container_of(v, struct rtl2832_sdr_dev, v4l2_dev);
1317 	struct platform_device *pdev = dev->pdev;
1318 
1319 	dev_dbg(&pdev->dev, "\n");
1320 
1321 	v4l2_ctrl_handler_free(&dev->hdl);
1322 	v4l2_device_unregister(&dev->v4l2_dev);
1323 	kfree(dev);
1324 }
1325 
1326 /* Platform driver interface */
1327 static int rtl2832_sdr_probe(struct platform_device *pdev)
1328 {
1329 	struct rtl2832_sdr_dev *dev;
1330 	struct rtl2832_sdr_platform_data *pdata = pdev->dev.platform_data;
1331 	const struct v4l2_ctrl_ops *ops = &rtl2832_sdr_ctrl_ops;
1332 	struct v4l2_subdev *subdev;
1333 	int ret;
1334 
1335 	dev_dbg(&pdev->dev, "\n");
1336 
1337 	if (!pdata) {
1338 		dev_err(&pdev->dev, "Cannot proceed without platform data\n");
1339 		ret = -EINVAL;
1340 		goto err;
1341 	}
1342 	if (!pdev->dev.parent->driver) {
1343 		dev_dbg(&pdev->dev, "No parent device\n");
1344 		ret = -EINVAL;
1345 		goto err;
1346 	}
1347 	/* try to refcount host drv since we are the consumer */
1348 	if (!try_module_get(pdev->dev.parent->driver->owner)) {
1349 		dev_err(&pdev->dev, "Refcount fail");
1350 		ret = -EINVAL;
1351 		goto err;
1352 	}
1353 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1354 	if (dev == NULL) {
1355 		ret = -ENOMEM;
1356 		goto err_module_put;
1357 	}
1358 
1359 	/* setup the state */
1360 	subdev = pdata->v4l2_subdev;
1361 	dev->v4l2_subdev = pdata->v4l2_subdev;
1362 	dev->pdev = pdev;
1363 	dev->regmap = pdata->regmap;
1364 	dev->udev = pdata->dvb_usb_device->udev;
1365 	dev->f_adc = bands_adc[0].rangelow;
1366 	dev->f_tuner = bands_fm[0].rangelow;
1367 	dev->pixelformat = formats[0].pixelformat;
1368 	dev->buffersize = formats[0].buffersize;
1369 	dev->num_formats = NUM_FORMATS;
1370 	if (!rtl2832_sdr_emulated_fmt)
1371 		dev->num_formats -= 1;
1372 
1373 	mutex_init(&dev->v4l2_lock);
1374 	mutex_init(&dev->vb_queue_lock);
1375 	spin_lock_init(&dev->queued_bufs_lock);
1376 	INIT_LIST_HEAD(&dev->queued_bufs);
1377 
1378 	/* Init videobuf2 queue structure */
1379 	dev->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1380 	dev->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1381 	dev->vb_queue.drv_priv = dev;
1382 	dev->vb_queue.buf_struct_size = sizeof(struct rtl2832_sdr_frame_buf);
1383 	dev->vb_queue.ops = &rtl2832_sdr_vb2_ops;
1384 	dev->vb_queue.mem_ops = &vb2_vmalloc_memops;
1385 	dev->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1386 	ret = vb2_queue_init(&dev->vb_queue);
1387 	if (ret) {
1388 		dev_err(&pdev->dev, "Could not initialize vb2 queue\n");
1389 		goto err_kfree;
1390 	}
1391 
1392 	/* Register controls */
1393 	switch (pdata->tuner) {
1394 	case RTL2832_SDR_TUNER_E4000:
1395 		v4l2_ctrl_handler_init(&dev->hdl, 9);
1396 		if (subdev)
1397 			v4l2_ctrl_add_handler(&dev->hdl, subdev->ctrl_handler, NULL);
1398 		break;
1399 	case RTL2832_SDR_TUNER_R820T:
1400 	case RTL2832_SDR_TUNER_R828D:
1401 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1402 		dev->bandwidth_auto = v4l2_ctrl_new_std(&dev->hdl, ops,
1403 							V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1404 							0, 1, 1, 1);
1405 		dev->bandwidth = v4l2_ctrl_new_std(&dev->hdl, ops,
1406 						   V4L2_CID_RF_TUNER_BANDWIDTH,
1407 						   0, 8000000, 100000, 0);
1408 		v4l2_ctrl_auto_cluster(2, &dev->bandwidth_auto, 0, false);
1409 		break;
1410 	case RTL2832_SDR_TUNER_FC0012:
1411 	case RTL2832_SDR_TUNER_FC0013:
1412 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1413 		dev->bandwidth_auto = v4l2_ctrl_new_std(&dev->hdl, ops,
1414 							V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1415 							0, 1, 1, 1);
1416 		dev->bandwidth = v4l2_ctrl_new_std(&dev->hdl, ops,
1417 						   V4L2_CID_RF_TUNER_BANDWIDTH,
1418 						   6000000, 8000000, 1000000,
1419 						   6000000);
1420 		v4l2_ctrl_auto_cluster(2, &dev->bandwidth_auto, 0, false);
1421 		break;
1422 	case RTL2832_SDR_TUNER_FC2580:
1423 		v4l2_ctrl_handler_init(&dev->hdl, 2);
1424 		if (subdev)
1425 			v4l2_ctrl_add_handler(&dev->hdl, subdev->ctrl_handler,
1426 					      NULL);
1427 		break;
1428 	default:
1429 		v4l2_ctrl_handler_init(&dev->hdl, 0);
1430 		dev_err(&pdev->dev, "Unsupported tuner\n");
1431 		goto err_v4l2_ctrl_handler_free;
1432 	}
1433 	if (dev->hdl.error) {
1434 		ret = dev->hdl.error;
1435 		dev_err(&pdev->dev, "Could not initialize controls\n");
1436 		goto err_v4l2_ctrl_handler_free;
1437 	}
1438 
1439 	/* Init video_device structure */
1440 	dev->vdev = rtl2832_sdr_template;
1441 	dev->vdev.queue = &dev->vb_queue;
1442 	dev->vdev.queue->lock = &dev->vb_queue_lock;
1443 	video_set_drvdata(&dev->vdev, dev);
1444 
1445 	/* Register the v4l2_device structure */
1446 	dev->v4l2_dev.release = rtl2832_sdr_video_release;
1447 	ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
1448 	if (ret) {
1449 		dev_err(&pdev->dev, "Failed to register v4l2-device %d\n", ret);
1450 		goto err_v4l2_ctrl_handler_free;
1451 	}
1452 
1453 	dev->v4l2_dev.ctrl_handler = &dev->hdl;
1454 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
1455 	dev->vdev.lock = &dev->v4l2_lock;
1456 	dev->vdev.vfl_dir = VFL_DIR_RX;
1457 
1458 	ret = video_register_device(&dev->vdev, VFL_TYPE_SDR, -1);
1459 	if (ret) {
1460 		dev_err(&pdev->dev, "Failed to register as video device %d\n",
1461 			ret);
1462 		goto err_v4l2_device_unregister;
1463 	}
1464 	dev_info(&pdev->dev, "Registered as %s\n",
1465 		 video_device_node_name(&dev->vdev));
1466 	dev_info(&pdev->dev, "Realtek RTL2832 SDR attached\n");
1467 	dev_notice(&pdev->dev,
1468 		   "SDR API is still slightly experimental and functionality changes may follow\n");
1469 	platform_set_drvdata(pdev, dev);
1470 	return 0;
1471 err_v4l2_device_unregister:
1472 	v4l2_device_unregister(&dev->v4l2_dev);
1473 err_v4l2_ctrl_handler_free:
1474 	v4l2_ctrl_handler_free(&dev->hdl);
1475 err_kfree:
1476 	kfree(dev);
1477 err_module_put:
1478 	module_put(pdev->dev.parent->driver->owner);
1479 err:
1480 	return ret;
1481 }
1482 
1483 static int rtl2832_sdr_remove(struct platform_device *pdev)
1484 {
1485 	struct rtl2832_sdr_dev *dev = platform_get_drvdata(pdev);
1486 
1487 	dev_dbg(&pdev->dev, "\n");
1488 
1489 	mutex_lock(&dev->vb_queue_lock);
1490 	mutex_lock(&dev->v4l2_lock);
1491 	/* No need to keep the urbs around after disconnection */
1492 	dev->udev = NULL;
1493 	v4l2_device_disconnect(&dev->v4l2_dev);
1494 	video_unregister_device(&dev->vdev);
1495 	mutex_unlock(&dev->v4l2_lock);
1496 	mutex_unlock(&dev->vb_queue_lock);
1497 	v4l2_device_put(&dev->v4l2_dev);
1498 	module_put(pdev->dev.parent->driver->owner);
1499 
1500 	return 0;
1501 }
1502 
1503 static struct platform_driver rtl2832_sdr_driver = {
1504 	.driver = {
1505 		.name   = "rtl2832_sdr",
1506 	},
1507 	.probe          = rtl2832_sdr_probe,
1508 	.remove         = rtl2832_sdr_remove,
1509 };
1510 module_platform_driver(rtl2832_sdr_driver);
1511 
1512 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1513 MODULE_DESCRIPTION("Realtek RTL2832 SDR driver");
1514 MODULE_LICENSE("GPL");
1515