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