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