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