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