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