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