xref: /linux/drivers/media/usb/msi2500/msi2500.c (revision e9a83bd2322035ed9d7dcf35753d3f984d76c6a5)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Mirics MSi2500 driver
4  * Mirics MSi3101 SDR Dongle driver
5  *
6  * Copyright (C) 2013 Antti Palosaari <crope@iki.fi>
7  *
8  * That driver is somehow based of pwc driver:
9  *  (C) 1999-2004 Nemosoft Unv.
10  *  (C) 2004-2006 Luc Saillard (luc@saillard.org)
11  *  (C) 2011 Hans de Goede <hdegoede@redhat.com>
12  */
13 
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <asm/div64.h>
17 #include <media/v4l2-device.h>
18 #include <media/v4l2-ioctl.h>
19 #include <media/v4l2-ctrls.h>
20 #include <media/v4l2-event.h>
21 #include <linux/usb.h>
22 #include <media/videobuf2-v4l2.h>
23 #include <media/videobuf2-vmalloc.h>
24 #include <linux/spi/spi.h>
25 
26 static bool msi2500_emulated_fmt;
27 module_param_named(emulated_formats, msi2500_emulated_fmt, bool, 0644);
28 MODULE_PARM_DESC(emulated_formats, "enable emulated formats (disappears in future)");
29 
30 /*
31  *   iConfiguration          0
32  *     bInterfaceNumber        0
33  *     bAlternateSetting       1
34  *     bNumEndpoints           1
35  *       bEndpointAddress     0x81  EP 1 IN
36  *       bmAttributes            1
37  *         Transfer Type            Isochronous
38  *       wMaxPacketSize     0x1400  3x 1024 bytes
39  *       bInterval               1
40  */
41 #define MAX_ISO_BUFS            (8)
42 #define ISO_FRAMES_PER_DESC     (8)
43 #define ISO_MAX_FRAME_SIZE      (3 * 1024)
44 #define ISO_BUFFER_SIZE         (ISO_FRAMES_PER_DESC * ISO_MAX_FRAME_SIZE)
45 #define MAX_ISOC_ERRORS         20
46 
47 /*
48  * TODO: These formats should be moved to V4L2 API. Formats are currently
49  * disabled from formats[] table, not visible to userspace.
50  */
51  /* signed 12-bit */
52 #define MSI2500_PIX_FMT_SDR_S12         v4l2_fourcc('D', 'S', '1', '2')
53 /* Mirics MSi2500 format 384 */
54 #define MSI2500_PIX_FMT_SDR_MSI2500_384 v4l2_fourcc('M', '3', '8', '4')
55 
56 static const struct v4l2_frequency_band bands[] = {
57 	{
58 		.tuner = 0,
59 		.type = V4L2_TUNER_ADC,
60 		.index = 0,
61 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
62 		.rangelow   =  1200000,
63 		.rangehigh  = 15000000,
64 	},
65 };
66 
67 /* stream formats */
68 struct msi2500_format {
69 	char	*name;
70 	u32	pixelformat;
71 	u32	buffersize;
72 };
73 
74 /* format descriptions for capture and preview */
75 static struct msi2500_format formats[] = {
76 	{
77 		.name		= "Complex S8",
78 		.pixelformat	= V4L2_SDR_FMT_CS8,
79 		.buffersize	= 3 * 1008,
80 #if 0
81 	}, {
82 		.name		= "10+2-bit signed",
83 		.pixelformat	= MSI2500_PIX_FMT_SDR_MSI2500_384,
84 	}, {
85 		.name		= "12-bit signed",
86 		.pixelformat	= MSI2500_PIX_FMT_SDR_S12,
87 #endif
88 	}, {
89 		.name		= "Complex S14LE",
90 		.pixelformat	= V4L2_SDR_FMT_CS14LE,
91 		.buffersize	= 3 * 1008,
92 	}, {
93 		.name		= "Complex U8 (emulated)",
94 		.pixelformat	= V4L2_SDR_FMT_CU8,
95 		.buffersize	= 3 * 1008,
96 	}, {
97 		.name		= "Complex U16LE (emulated)",
98 		.pixelformat	=  V4L2_SDR_FMT_CU16LE,
99 		.buffersize	= 3 * 1008,
100 	},
101 };
102 
103 static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
104 
105 /* intermediate buffers with raw data from the USB device */
106 struct msi2500_frame_buf {
107 	/* common v4l buffer stuff -- must be first */
108 	struct vb2_v4l2_buffer vb;
109 	struct list_head list;
110 };
111 
112 struct msi2500_dev {
113 	struct device *dev;
114 	struct video_device vdev;
115 	struct v4l2_device v4l2_dev;
116 	struct v4l2_subdev *v4l2_subdev;
117 	struct spi_master *master;
118 
119 	/* videobuf2 queue and queued buffers list */
120 	struct vb2_queue vb_queue;
121 	struct list_head queued_bufs;
122 	spinlock_t queued_bufs_lock; /* Protects queued_bufs */
123 
124 	/* Note if taking both locks v4l2_lock must always be locked first! */
125 	struct mutex v4l2_lock;      /* Protects everything else */
126 	struct mutex vb_queue_lock;  /* Protects vb_queue and capt_file */
127 
128 	/* Pointer to our usb_device, will be NULL after unplug */
129 	struct usb_device *udev; /* Both mutexes most be hold when setting! */
130 
131 	unsigned int f_adc;
132 	u32 pixelformat;
133 	u32 buffersize;
134 	unsigned int num_formats;
135 
136 	unsigned int isoc_errors; /* number of contiguous ISOC errors */
137 	unsigned int vb_full; /* vb is full and packets dropped */
138 
139 	struct urb *urbs[MAX_ISO_BUFS];
140 
141 	/* Controls */
142 	struct v4l2_ctrl_handler hdl;
143 
144 	u32 next_sample; /* for track lost packets */
145 	u32 sample; /* for sample rate calc */
146 	unsigned long jiffies_next;
147 };
148 
149 /* Private functions */
150 static struct msi2500_frame_buf *msi2500_get_next_fill_buf(
151 							struct msi2500_dev *dev)
152 {
153 	unsigned long flags;
154 	struct msi2500_frame_buf *buf = NULL;
155 
156 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
157 	if (list_empty(&dev->queued_bufs))
158 		goto leave;
159 
160 	buf = list_entry(dev->queued_bufs.next, struct msi2500_frame_buf, list);
161 	list_del(&buf->list);
162 leave:
163 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
164 	return buf;
165 }
166 
167 /*
168  * +===========================================================================
169  * |   00-1023 | USB packet type '504'
170  * +===========================================================================
171  * |   00-  03 | sequence number of first sample in that USB packet
172  * +---------------------------------------------------------------------------
173  * |   04-  15 | garbage
174  * +---------------------------------------------------------------------------
175  * |   16-1023 | samples
176  * +---------------------------------------------------------------------------
177  * signed 8-bit sample
178  * 504 * 2 = 1008 samples
179  *
180  *
181  * +===========================================================================
182  * |   00-1023 | USB packet type '384'
183  * +===========================================================================
184  * |   00-  03 | sequence number of first sample in that USB packet
185  * +---------------------------------------------------------------------------
186  * |   04-  15 | garbage
187  * +---------------------------------------------------------------------------
188  * |   16- 175 | samples
189  * +---------------------------------------------------------------------------
190  * |  176- 179 | control bits for previous samples
191  * +---------------------------------------------------------------------------
192  * |  180- 339 | samples
193  * +---------------------------------------------------------------------------
194  * |  340- 343 | control bits for previous samples
195  * +---------------------------------------------------------------------------
196  * |  344- 503 | samples
197  * +---------------------------------------------------------------------------
198  * |  504- 507 | control bits for previous samples
199  * +---------------------------------------------------------------------------
200  * |  508- 667 | samples
201  * +---------------------------------------------------------------------------
202  * |  668- 671 | control bits for previous samples
203  * +---------------------------------------------------------------------------
204  * |  672- 831 | samples
205  * +---------------------------------------------------------------------------
206  * |  832- 835 | control bits for previous samples
207  * +---------------------------------------------------------------------------
208  * |  836- 995 | samples
209  * +---------------------------------------------------------------------------
210  * |  996- 999 | control bits for previous samples
211  * +---------------------------------------------------------------------------
212  * | 1000-1023 | garbage
213  * +---------------------------------------------------------------------------
214  *
215  * Bytes 4 - 7 could have some meaning?
216  *
217  * Control bits for previous samples is 32-bit field, containing 16 x 2-bit
218  * numbers. This results one 2-bit number for 8 samples. It is likely used for
219  * for bit shifting sample by given bits, increasing actual sampling resolution.
220  * Number 2 (0b10) was never seen.
221  *
222  * 6 * 16 * 2 * 4 = 768 samples. 768 * 4 = 3072 bytes
223  *
224  *
225  * +===========================================================================
226  * |   00-1023 | USB packet type '336'
227  * +===========================================================================
228  * |   00-  03 | sequence number of first sample in that USB packet
229  * +---------------------------------------------------------------------------
230  * |   04-  15 | garbage
231  * +---------------------------------------------------------------------------
232  * |   16-1023 | samples
233  * +---------------------------------------------------------------------------
234  * signed 12-bit sample
235  *
236  *
237  * +===========================================================================
238  * |   00-1023 | USB packet type '252'
239  * +===========================================================================
240  * |   00-  03 | sequence number of first sample in that USB packet
241  * +---------------------------------------------------------------------------
242  * |   04-  15 | garbage
243  * +---------------------------------------------------------------------------
244  * |   16-1023 | samples
245  * +---------------------------------------------------------------------------
246  * signed 14-bit sample
247  */
248 
249 static int msi2500_convert_stream(struct msi2500_dev *dev, u8 *dst, u8 *src,
250 				  unsigned int src_len)
251 {
252 	unsigned int i, j, transactions, dst_len = 0;
253 	u32 sample[3];
254 
255 	/* There could be 1-3 1024 byte transactions per packet */
256 	transactions = src_len / 1024;
257 
258 	for (i = 0; i < transactions; i++) {
259 		sample[i] = src[3] << 24 | src[2] << 16 | src[1] << 8 |
260 				src[0] << 0;
261 		if (i == 0 && dev->next_sample != sample[0]) {
262 			dev_dbg_ratelimited(dev->dev,
263 					    "%d samples lost, %d %08x:%08x\n",
264 					    sample[0] - dev->next_sample,
265 					    src_len, dev->next_sample,
266 					    sample[0]);
267 		}
268 
269 		/*
270 		 * Dump all unknown 'garbage' data - maybe we will discover
271 		 * someday if there is something rational...
272 		 */
273 		dev_dbg_ratelimited(dev->dev, "%*ph\n", 12, &src[4]);
274 
275 		src += 16; /* skip header */
276 
277 		switch (dev->pixelformat) {
278 		case V4L2_SDR_FMT_CU8: /* 504 x IQ samples */
279 		{
280 			s8 *s8src = (s8 *)src;
281 			u8 *u8dst = (u8 *)dst;
282 
283 			for (j = 0; j < 1008; j++)
284 				*u8dst++ = *s8src++ + 128;
285 
286 			src += 1008;
287 			dst += 1008;
288 			dst_len += 1008;
289 			dev->next_sample = sample[i] + 504;
290 			break;
291 		}
292 		case  V4L2_SDR_FMT_CU16LE: /* 252 x IQ samples */
293 		{
294 			s16 *s16src = (s16 *)src;
295 			u16 *u16dst = (u16 *)dst;
296 			struct {signed int x:14; } se; /* sign extension */
297 			unsigned int utmp;
298 
299 			for (j = 0; j < 1008; j += 2) {
300 				/* sign extension from 14-bit to signed int */
301 				se.x = *s16src++;
302 				/* from signed int to unsigned int */
303 				utmp = se.x + 8192;
304 				/* from 14-bit to 16-bit */
305 				*u16dst++ = utmp << 2 | utmp >> 12;
306 			}
307 
308 			src += 1008;
309 			dst += 1008;
310 			dst_len += 1008;
311 			dev->next_sample = sample[i] + 252;
312 			break;
313 		}
314 		case MSI2500_PIX_FMT_SDR_MSI2500_384: /* 384 x IQ samples */
315 			/* Dump unknown 'garbage' data */
316 			dev_dbg_ratelimited(dev->dev, "%*ph\n", 24, &src[1000]);
317 			memcpy(dst, src, 984);
318 			src += 984 + 24;
319 			dst += 984;
320 			dst_len += 984;
321 			dev->next_sample = sample[i] + 384;
322 			break;
323 		case V4L2_SDR_FMT_CS8:         /* 504 x IQ samples */
324 			memcpy(dst, src, 1008);
325 			src += 1008;
326 			dst += 1008;
327 			dst_len += 1008;
328 			dev->next_sample = sample[i] + 504;
329 			break;
330 		case MSI2500_PIX_FMT_SDR_S12:  /* 336 x IQ samples */
331 			memcpy(dst, src, 1008);
332 			src += 1008;
333 			dst += 1008;
334 			dst_len += 1008;
335 			dev->next_sample = sample[i] + 336;
336 			break;
337 		case V4L2_SDR_FMT_CS14LE:      /* 252 x IQ samples */
338 			memcpy(dst, src, 1008);
339 			src += 1008;
340 			dst += 1008;
341 			dst_len += 1008;
342 			dev->next_sample = sample[i] + 252;
343 			break;
344 		default:
345 			break;
346 		}
347 	}
348 
349 	/* calculate sample rate and output it in 10 seconds intervals */
350 	if (unlikely(time_is_before_jiffies(dev->jiffies_next))) {
351 		#define MSECS 10000UL
352 		unsigned int msecs = jiffies_to_msecs(jiffies -
353 				dev->jiffies_next + msecs_to_jiffies(MSECS));
354 		unsigned int samples = dev->next_sample - dev->sample;
355 
356 		dev->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
357 		dev->sample = dev->next_sample;
358 		dev_dbg(dev->dev, "size=%u samples=%u msecs=%u sample rate=%lu\n",
359 			src_len, samples, msecs,
360 			samples * 1000UL / msecs);
361 	}
362 
363 	return dst_len;
364 }
365 
366 /*
367  * This gets called for the Isochronous pipe (stream). This is done in interrupt
368  * time, so it has to be fast, not crash, and not stall. Neat.
369  */
370 static void msi2500_isoc_handler(struct urb *urb)
371 {
372 	struct msi2500_dev *dev = (struct msi2500_dev *)urb->context;
373 	int i, flen, fstatus;
374 	unsigned char *iso_buf = NULL;
375 	struct msi2500_frame_buf *fbuf;
376 
377 	if (unlikely(urb->status == -ENOENT ||
378 		     urb->status == -ECONNRESET ||
379 		     urb->status == -ESHUTDOWN)) {
380 		dev_dbg(dev->dev, "URB (%p) unlinked %ssynchronously\n",
381 			urb, urb->status == -ENOENT ? "" : "a");
382 		return;
383 	}
384 
385 	if (unlikely(urb->status != 0)) {
386 		dev_dbg(dev->dev, "called with status %d\n", urb->status);
387 		/* Give up after a number of contiguous errors */
388 		if (++dev->isoc_errors > MAX_ISOC_ERRORS)
389 			dev_dbg(dev->dev, "Too many ISOC errors, bailing out\n");
390 		goto handler_end;
391 	} else {
392 		/* Reset ISOC error counter. We did get here, after all. */
393 		dev->isoc_errors = 0;
394 	}
395 
396 	/* Compact data */
397 	for (i = 0; i < urb->number_of_packets; i++) {
398 		void *ptr;
399 
400 		/* Check frame error */
401 		fstatus = urb->iso_frame_desc[i].status;
402 		if (unlikely(fstatus)) {
403 			dev_dbg_ratelimited(dev->dev,
404 					    "frame=%d/%d has error %d skipping\n",
405 					    i, urb->number_of_packets, fstatus);
406 			continue;
407 		}
408 
409 		/* Check if that frame contains data */
410 		flen = urb->iso_frame_desc[i].actual_length;
411 		if (unlikely(flen == 0))
412 			continue;
413 
414 		iso_buf = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
415 
416 		/* Get free framebuffer */
417 		fbuf = msi2500_get_next_fill_buf(dev);
418 		if (unlikely(fbuf == NULL)) {
419 			dev->vb_full++;
420 			dev_dbg_ratelimited(dev->dev,
421 					    "videobuf is full, %d packets dropped\n",
422 					    dev->vb_full);
423 			continue;
424 		}
425 
426 		/* fill framebuffer */
427 		ptr = vb2_plane_vaddr(&fbuf->vb.vb2_buf, 0);
428 		flen = msi2500_convert_stream(dev, ptr, iso_buf, flen);
429 		vb2_set_plane_payload(&fbuf->vb.vb2_buf, 0, flen);
430 		vb2_buffer_done(&fbuf->vb.vb2_buf, VB2_BUF_STATE_DONE);
431 	}
432 
433 handler_end:
434 	i = usb_submit_urb(urb, GFP_ATOMIC);
435 	if (unlikely(i != 0))
436 		dev_dbg(dev->dev, "Error (%d) re-submitting urb\n", i);
437 }
438 
439 static void msi2500_iso_stop(struct msi2500_dev *dev)
440 {
441 	int i;
442 
443 	dev_dbg(dev->dev, "\n");
444 
445 	/* Unlinking ISOC buffers one by one */
446 	for (i = 0; i < MAX_ISO_BUFS; i++) {
447 		if (dev->urbs[i]) {
448 			dev_dbg(dev->dev, "Unlinking URB %p\n", dev->urbs[i]);
449 			usb_kill_urb(dev->urbs[i]);
450 		}
451 	}
452 }
453 
454 static void msi2500_iso_free(struct msi2500_dev *dev)
455 {
456 	int i;
457 
458 	dev_dbg(dev->dev, "\n");
459 
460 	/* Freeing ISOC buffers one by one */
461 	for (i = 0; i < MAX_ISO_BUFS; i++) {
462 		if (dev->urbs[i]) {
463 			dev_dbg(dev->dev, "Freeing URB\n");
464 			if (dev->urbs[i]->transfer_buffer) {
465 				usb_free_coherent(dev->udev,
466 					dev->urbs[i]->transfer_buffer_length,
467 					dev->urbs[i]->transfer_buffer,
468 					dev->urbs[i]->transfer_dma);
469 			}
470 			usb_free_urb(dev->urbs[i]);
471 			dev->urbs[i] = NULL;
472 		}
473 	}
474 }
475 
476 /* Both v4l2_lock and vb_queue_lock should be locked when calling this */
477 static void msi2500_isoc_cleanup(struct msi2500_dev *dev)
478 {
479 	dev_dbg(dev->dev, "\n");
480 
481 	msi2500_iso_stop(dev);
482 	msi2500_iso_free(dev);
483 }
484 
485 /* Both v4l2_lock and vb_queue_lock should be locked when calling this */
486 static int msi2500_isoc_init(struct msi2500_dev *dev)
487 {
488 	struct urb *urb;
489 	int i, j, ret;
490 
491 	dev_dbg(dev->dev, "\n");
492 
493 	dev->isoc_errors = 0;
494 
495 	ret = usb_set_interface(dev->udev, 0, 1);
496 	if (ret)
497 		return ret;
498 
499 	/* Allocate and init Isochronuous urbs */
500 	for (i = 0; i < MAX_ISO_BUFS; i++) {
501 		urb = usb_alloc_urb(ISO_FRAMES_PER_DESC, GFP_KERNEL);
502 		if (urb == NULL) {
503 			msi2500_isoc_cleanup(dev);
504 			return -ENOMEM;
505 		}
506 		dev->urbs[i] = urb;
507 		dev_dbg(dev->dev, "Allocated URB at 0x%p\n", urb);
508 
509 		urb->interval = 1;
510 		urb->dev = dev->udev;
511 		urb->pipe = usb_rcvisocpipe(dev->udev, 0x81);
512 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
513 		urb->transfer_buffer = usb_alloc_coherent(dev->udev,
514 				ISO_BUFFER_SIZE,
515 				GFP_KERNEL, &urb->transfer_dma);
516 		if (urb->transfer_buffer == NULL) {
517 			dev_err(dev->dev,
518 				"Failed to allocate urb buffer %d\n", i);
519 			msi2500_isoc_cleanup(dev);
520 			return -ENOMEM;
521 		}
522 		urb->transfer_buffer_length = ISO_BUFFER_SIZE;
523 		urb->complete = msi2500_isoc_handler;
524 		urb->context = dev;
525 		urb->start_frame = 0;
526 		urb->number_of_packets = ISO_FRAMES_PER_DESC;
527 		for (j = 0; j < ISO_FRAMES_PER_DESC; j++) {
528 			urb->iso_frame_desc[j].offset = j * ISO_MAX_FRAME_SIZE;
529 			urb->iso_frame_desc[j].length = ISO_MAX_FRAME_SIZE;
530 		}
531 	}
532 
533 	/* link */
534 	for (i = 0; i < MAX_ISO_BUFS; i++) {
535 		ret = usb_submit_urb(dev->urbs[i], GFP_KERNEL);
536 		if (ret) {
537 			dev_err(dev->dev,
538 				"usb_submit_urb %d failed with error %d\n",
539 				i, ret);
540 			msi2500_isoc_cleanup(dev);
541 			return ret;
542 		}
543 		dev_dbg(dev->dev, "URB 0x%p submitted.\n", dev->urbs[i]);
544 	}
545 
546 	/* All is done... */
547 	return 0;
548 }
549 
550 /* Must be called with vb_queue_lock hold */
551 static void msi2500_cleanup_queued_bufs(struct msi2500_dev *dev)
552 {
553 	unsigned long flags;
554 
555 	dev_dbg(dev->dev, "\n");
556 
557 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
558 	while (!list_empty(&dev->queued_bufs)) {
559 		struct msi2500_frame_buf *buf;
560 
561 		buf = list_entry(dev->queued_bufs.next,
562 				 struct msi2500_frame_buf, list);
563 		list_del(&buf->list);
564 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
565 	}
566 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
567 }
568 
569 /* The user yanked out the cable... */
570 static void msi2500_disconnect(struct usb_interface *intf)
571 {
572 	struct v4l2_device *v = usb_get_intfdata(intf);
573 	struct msi2500_dev *dev =
574 			container_of(v, struct msi2500_dev, v4l2_dev);
575 
576 	dev_dbg(dev->dev, "\n");
577 
578 	mutex_lock(&dev->vb_queue_lock);
579 	mutex_lock(&dev->v4l2_lock);
580 	/* No need to keep the urbs around after disconnection */
581 	dev->udev = NULL;
582 	v4l2_device_disconnect(&dev->v4l2_dev);
583 	video_unregister_device(&dev->vdev);
584 	spi_unregister_master(dev->master);
585 	mutex_unlock(&dev->v4l2_lock);
586 	mutex_unlock(&dev->vb_queue_lock);
587 
588 	v4l2_device_put(&dev->v4l2_dev);
589 }
590 
591 static int msi2500_querycap(struct file *file, void *fh,
592 			    struct v4l2_capability *cap)
593 {
594 	struct msi2500_dev *dev = video_drvdata(file);
595 
596 	dev_dbg(dev->dev, "\n");
597 
598 	strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
599 	strscpy(cap->card, dev->vdev.name, sizeof(cap->card));
600 	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
601 	return 0;
602 }
603 
604 /* Videobuf2 operations */
605 static int msi2500_queue_setup(struct vb2_queue *vq,
606 			       unsigned int *nbuffers,
607 			       unsigned int *nplanes, unsigned int sizes[],
608 			       struct device *alloc_devs[])
609 {
610 	struct msi2500_dev *dev = vb2_get_drv_priv(vq);
611 
612 	dev_dbg(dev->dev, "nbuffers=%d\n", *nbuffers);
613 
614 	/* Absolute min and max number of buffers available for mmap() */
615 	*nbuffers = clamp_t(unsigned int, *nbuffers, 8, 32);
616 	*nplanes = 1;
617 	sizes[0] = PAGE_ALIGN(dev->buffersize);
618 	dev_dbg(dev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
619 	return 0;
620 }
621 
622 static void msi2500_buf_queue(struct vb2_buffer *vb)
623 {
624 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
625 	struct msi2500_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
626 	struct msi2500_frame_buf *buf = container_of(vbuf,
627 						     struct msi2500_frame_buf,
628 						     vb);
629 	unsigned long flags;
630 
631 	/* Check the device has not disconnected between prep and queuing */
632 	if (unlikely(!dev->udev)) {
633 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
634 		return;
635 	}
636 
637 	spin_lock_irqsave(&dev->queued_bufs_lock, flags);
638 	list_add_tail(&buf->list, &dev->queued_bufs);
639 	spin_unlock_irqrestore(&dev->queued_bufs_lock, flags);
640 }
641 
642 #define CMD_WREG               0x41
643 #define CMD_START_STREAMING    0x43
644 #define CMD_STOP_STREAMING     0x45
645 #define CMD_READ_UNKNOWN       0x48
646 
647 #define msi2500_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
648 	char *_direction; \
649 	if (_t & USB_DIR_IN) \
650 		_direction = "<<<"; \
651 	else \
652 		_direction = ">>>"; \
653 	dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
654 			_t, _r, _v & 0xff, _v >> 8, _i & 0xff, _i >> 8, \
655 			_l & 0xff, _l >> 8, _direction, _l, _b); \
656 }
657 
658 static int msi2500_ctrl_msg(struct msi2500_dev *dev, u8 cmd, u32 data)
659 {
660 	int ret;
661 	u8 request = cmd;
662 	u8 requesttype = USB_DIR_OUT | USB_TYPE_VENDOR;
663 	u16 value = (data >> 0) & 0xffff;
664 	u16 index = (data >> 16) & 0xffff;
665 
666 	msi2500_dbg_usb_control_msg(dev->dev, request, requesttype,
667 				    value, index, NULL, 0);
668 	ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), request,
669 			      requesttype, value, index, NULL, 0, 2000);
670 	if (ret)
671 		dev_err(dev->dev, "failed %d, cmd %02x, data %04x\n",
672 			ret, cmd, data);
673 
674 	return ret;
675 }
676 
677 static int msi2500_set_usb_adc(struct msi2500_dev *dev)
678 {
679 	int ret;
680 	unsigned int f_vco, f_sr, div_n, k, k_cw, div_out;
681 	u32 reg3, reg4, reg7;
682 	struct v4l2_ctrl *bandwidth_auto;
683 	struct v4l2_ctrl *bandwidth;
684 
685 	f_sr = dev->f_adc;
686 
687 	/* set tuner, subdev, filters according to sampling rate */
688 	bandwidth_auto = v4l2_ctrl_find(&dev->hdl,
689 			V4L2_CID_RF_TUNER_BANDWIDTH_AUTO);
690 	if (v4l2_ctrl_g_ctrl(bandwidth_auto)) {
691 		bandwidth = v4l2_ctrl_find(&dev->hdl,
692 				V4L2_CID_RF_TUNER_BANDWIDTH);
693 		v4l2_ctrl_s_ctrl(bandwidth, dev->f_adc);
694 	}
695 
696 	/* select stream format */
697 	switch (dev->pixelformat) {
698 	case V4L2_SDR_FMT_CU8:
699 		reg7 = 0x000c9407; /* 504 */
700 		break;
701 	case  V4L2_SDR_FMT_CU16LE:
702 		reg7 = 0x00009407; /* 252 */
703 		break;
704 	case V4L2_SDR_FMT_CS8:
705 		reg7 = 0x000c9407; /* 504 */
706 		break;
707 	case MSI2500_PIX_FMT_SDR_MSI2500_384:
708 		reg7 = 0x0000a507; /* 384 */
709 		break;
710 	case MSI2500_PIX_FMT_SDR_S12:
711 		reg7 = 0x00008507; /* 336 */
712 		break;
713 	case V4L2_SDR_FMT_CS14LE:
714 		reg7 = 0x00009407; /* 252 */
715 		break;
716 	default:
717 		reg7 = 0x000c9407; /* 504 */
718 		break;
719 	}
720 
721 	/*
722 	 * Fractional-N synthesizer
723 	 *
724 	 *           +----------------------------------------+
725 	 *           v                                        |
726 	 *  Fref   +----+     +-------+     +-----+         +------+     +---+
727 	 * ------> | PD | --> |  VCO  | --> | /2  | ------> | /N.F | <-- | K |
728 	 *         +----+     +-------+     +-----+         +------+     +---+
729 	 *                      |
730 	 *                      |
731 	 *                      v
732 	 *                    +-------+     +-----+  Fout
733 	 *                    | /Rout | --> | /12 | ------>
734 	 *                    +-------+     +-----+
735 	 */
736 	/*
737 	 * Synthesizer config is just a educated guess...
738 	 *
739 	 * [7:0]   0x03, register address
740 	 * [8]     1, power control
741 	 * [9]     ?, power control
742 	 * [12:10] output divider
743 	 * [13]    0 ?
744 	 * [14]    0 ?
745 	 * [15]    fractional MSB, bit 20
746 	 * [16:19] N
747 	 * [23:20] ?
748 	 * [24:31] 0x01
749 	 *
750 	 * output divider
751 	 * val   div
752 	 *   0     - (invalid)
753 	 *   1     4
754 	 *   2     6
755 	 *   3     8
756 	 *   4    10
757 	 *   5    12
758 	 *   6    14
759 	 *   7    16
760 	 *
761 	 * VCO 202000000 - 720000000++
762 	 */
763 
764 	#define F_REF 24000000
765 	#define DIV_PRE_N 2
766 	#define DIV_LO_OUT 12
767 	reg3 = 0x01000303;
768 	reg4 = 0x00000004;
769 
770 	/* XXX: Filters? AGC? VCO band? */
771 	if (f_sr < 6000000)
772 		reg3 |= 0x1 << 20;
773 	else if (f_sr < 7000000)
774 		reg3 |= 0x5 << 20;
775 	else if (f_sr < 8500000)
776 		reg3 |= 0x9 << 20;
777 	else
778 		reg3 |= 0xd << 20;
779 
780 	for (div_out = 4; div_out < 16; div_out += 2) {
781 		f_vco = f_sr * div_out * DIV_LO_OUT;
782 		dev_dbg(dev->dev, "div_out=%u f_vco=%u\n", div_out, f_vco);
783 		if (f_vco >= 202000000)
784 			break;
785 	}
786 
787 	/* Calculate PLL integer and fractional control word. */
788 	div_n = div_u64_rem(f_vco, DIV_PRE_N * F_REF, &k);
789 	k_cw = div_u64((u64) k * 0x200000, DIV_PRE_N * F_REF);
790 
791 	reg3 |= div_n << 16;
792 	reg3 |= (div_out / 2 - 1) << 10;
793 	reg3 |= ((k_cw >> 20) & 0x000001) << 15; /* [20] */
794 	reg4 |= ((k_cw >>  0) & 0x0fffff) <<  8; /* [19:0] */
795 
796 	dev_dbg(dev->dev,
797 		"f_sr=%u f_vco=%u div_n=%u k=%u div_out=%u reg3=%08x reg4=%08x\n",
798 		f_sr, f_vco, div_n, k, div_out, reg3, reg4);
799 
800 	ret = msi2500_ctrl_msg(dev, CMD_WREG, 0x00608008);
801 	if (ret)
802 		goto err;
803 
804 	ret = msi2500_ctrl_msg(dev, CMD_WREG, 0x00000c05);
805 	if (ret)
806 		goto err;
807 
808 	ret = msi2500_ctrl_msg(dev, CMD_WREG, 0x00020000);
809 	if (ret)
810 		goto err;
811 
812 	ret = msi2500_ctrl_msg(dev, CMD_WREG, 0x00480102);
813 	if (ret)
814 		goto err;
815 
816 	ret = msi2500_ctrl_msg(dev, CMD_WREG, 0x00f38008);
817 	if (ret)
818 		goto err;
819 
820 	ret = msi2500_ctrl_msg(dev, CMD_WREG, reg7);
821 	if (ret)
822 		goto err;
823 
824 	ret = msi2500_ctrl_msg(dev, CMD_WREG, reg4);
825 	if (ret)
826 		goto err;
827 
828 	ret = msi2500_ctrl_msg(dev, CMD_WREG, reg3);
829 err:
830 	return ret;
831 }
832 
833 static int msi2500_start_streaming(struct vb2_queue *vq, unsigned int count)
834 {
835 	struct msi2500_dev *dev = vb2_get_drv_priv(vq);
836 	int ret;
837 
838 	dev_dbg(dev->dev, "\n");
839 
840 	if (!dev->udev)
841 		return -ENODEV;
842 
843 	if (mutex_lock_interruptible(&dev->v4l2_lock))
844 		return -ERESTARTSYS;
845 
846 	/* wake-up tuner */
847 	v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 1);
848 
849 	ret = msi2500_set_usb_adc(dev);
850 
851 	ret = msi2500_isoc_init(dev);
852 	if (ret)
853 		msi2500_cleanup_queued_bufs(dev);
854 
855 	ret = msi2500_ctrl_msg(dev, CMD_START_STREAMING, 0);
856 
857 	mutex_unlock(&dev->v4l2_lock);
858 
859 	return ret;
860 }
861 
862 static void msi2500_stop_streaming(struct vb2_queue *vq)
863 {
864 	struct msi2500_dev *dev = vb2_get_drv_priv(vq);
865 
866 	dev_dbg(dev->dev, "\n");
867 
868 	mutex_lock(&dev->v4l2_lock);
869 
870 	if (dev->udev)
871 		msi2500_isoc_cleanup(dev);
872 
873 	msi2500_cleanup_queued_bufs(dev);
874 
875 	/* according to tests, at least 700us delay is required  */
876 	msleep(20);
877 	if (!msi2500_ctrl_msg(dev, CMD_STOP_STREAMING, 0)) {
878 		/* sleep USB IF / ADC */
879 		msi2500_ctrl_msg(dev, CMD_WREG, 0x01000003);
880 	}
881 
882 	/* sleep tuner */
883 	v4l2_subdev_call(dev->v4l2_subdev, core, s_power, 0);
884 
885 	mutex_unlock(&dev->v4l2_lock);
886 }
887 
888 static const struct vb2_ops msi2500_vb2_ops = {
889 	.queue_setup            = msi2500_queue_setup,
890 	.buf_queue              = msi2500_buf_queue,
891 	.start_streaming        = msi2500_start_streaming,
892 	.stop_streaming         = msi2500_stop_streaming,
893 	.wait_prepare           = vb2_ops_wait_prepare,
894 	.wait_finish            = vb2_ops_wait_finish,
895 };
896 
897 static int msi2500_enum_fmt_sdr_cap(struct file *file, void *priv,
898 				    struct v4l2_fmtdesc *f)
899 {
900 	struct msi2500_dev *dev = video_drvdata(file);
901 
902 	dev_dbg(dev->dev, "index=%d\n", f->index);
903 
904 	if (f->index >= dev->num_formats)
905 		return -EINVAL;
906 
907 	strscpy(f->description, formats[f->index].name, sizeof(f->description));
908 	f->pixelformat = formats[f->index].pixelformat;
909 
910 	return 0;
911 }
912 
913 static int msi2500_g_fmt_sdr_cap(struct file *file, void *priv,
914 				 struct v4l2_format *f)
915 {
916 	struct msi2500_dev *dev = video_drvdata(file);
917 
918 	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
919 		(char *)&dev->pixelformat);
920 
921 	f->fmt.sdr.pixelformat = dev->pixelformat;
922 	f->fmt.sdr.buffersize = dev->buffersize;
923 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
924 
925 	return 0;
926 }
927 
928 static int msi2500_s_fmt_sdr_cap(struct file *file, void *priv,
929 				 struct v4l2_format *f)
930 {
931 	struct msi2500_dev *dev = video_drvdata(file);
932 	struct vb2_queue *q = &dev->vb_queue;
933 	int i;
934 
935 	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
936 		(char *)&f->fmt.sdr.pixelformat);
937 
938 	if (vb2_is_busy(q))
939 		return -EBUSY;
940 
941 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
942 	for (i = 0; i < dev->num_formats; i++) {
943 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
944 			dev->pixelformat = formats[i].pixelformat;
945 			dev->buffersize = formats[i].buffersize;
946 			f->fmt.sdr.buffersize = formats[i].buffersize;
947 			return 0;
948 		}
949 	}
950 
951 	dev->pixelformat = formats[0].pixelformat;
952 	dev->buffersize = formats[0].buffersize;
953 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
954 	f->fmt.sdr.buffersize = formats[0].buffersize;
955 
956 	return 0;
957 }
958 
959 static int msi2500_try_fmt_sdr_cap(struct file *file, void *priv,
960 				   struct v4l2_format *f)
961 {
962 	struct msi2500_dev *dev = video_drvdata(file);
963 	int i;
964 
965 	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
966 		(char *)&f->fmt.sdr.pixelformat);
967 
968 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
969 	for (i = 0; i < dev->num_formats; i++) {
970 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
971 			f->fmt.sdr.buffersize = formats[i].buffersize;
972 			return 0;
973 		}
974 	}
975 
976 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
977 	f->fmt.sdr.buffersize = formats[0].buffersize;
978 
979 	return 0;
980 }
981 
982 static int msi2500_s_tuner(struct file *file, void *priv,
983 			   const struct v4l2_tuner *v)
984 {
985 	struct msi2500_dev *dev = video_drvdata(file);
986 	int ret;
987 
988 	dev_dbg(dev->dev, "index=%d\n", v->index);
989 
990 	if (v->index == 0)
991 		ret = 0;
992 	else if (v->index == 1)
993 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_tuner, v);
994 	else
995 		ret = -EINVAL;
996 
997 	return ret;
998 }
999 
1000 static int msi2500_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
1001 {
1002 	struct msi2500_dev *dev = video_drvdata(file);
1003 	int ret;
1004 
1005 	dev_dbg(dev->dev, "index=%d\n", v->index);
1006 
1007 	if (v->index == 0) {
1008 		strscpy(v->name, "Mirics MSi2500", sizeof(v->name));
1009 		v->type = V4L2_TUNER_ADC;
1010 		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1011 		v->rangelow =   1200000;
1012 		v->rangehigh = 15000000;
1013 		ret = 0;
1014 	} else if (v->index == 1) {
1015 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_tuner, v);
1016 	} else {
1017 		ret = -EINVAL;
1018 	}
1019 
1020 	return ret;
1021 }
1022 
1023 static int msi2500_g_frequency(struct file *file, void *priv,
1024 			       struct v4l2_frequency *f)
1025 {
1026 	struct msi2500_dev *dev = video_drvdata(file);
1027 	int ret  = 0;
1028 
1029 	dev_dbg(dev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
1030 
1031 	if (f->tuner == 0) {
1032 		f->frequency = dev->f_adc;
1033 		ret = 0;
1034 	} else if (f->tuner == 1) {
1035 		f->type = V4L2_TUNER_RF;
1036 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, g_frequency, f);
1037 	} else {
1038 		ret = -EINVAL;
1039 	}
1040 
1041 	return ret;
1042 }
1043 
1044 static int msi2500_s_frequency(struct file *file, void *priv,
1045 			       const struct v4l2_frequency *f)
1046 {
1047 	struct msi2500_dev *dev = video_drvdata(file);
1048 	int ret;
1049 
1050 	dev_dbg(dev->dev, "tuner=%d type=%d frequency=%u\n",
1051 		f->tuner, f->type, f->frequency);
1052 
1053 	if (f->tuner == 0) {
1054 		dev->f_adc = clamp_t(unsigned int, f->frequency,
1055 				     bands[0].rangelow,
1056 				     bands[0].rangehigh);
1057 		dev_dbg(dev->dev, "ADC frequency=%u Hz\n", dev->f_adc);
1058 		ret = msi2500_set_usb_adc(dev);
1059 	} else if (f->tuner == 1) {
1060 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner, s_frequency, f);
1061 	} else {
1062 		ret = -EINVAL;
1063 	}
1064 
1065 	return ret;
1066 }
1067 
1068 static int msi2500_enum_freq_bands(struct file *file, void *priv,
1069 				   struct v4l2_frequency_band *band)
1070 {
1071 	struct msi2500_dev *dev = video_drvdata(file);
1072 	int ret;
1073 
1074 	dev_dbg(dev->dev, "tuner=%d type=%d index=%d\n",
1075 		band->tuner, band->type, band->index);
1076 
1077 	if (band->tuner == 0) {
1078 		if (band->index >= ARRAY_SIZE(bands)) {
1079 			ret = -EINVAL;
1080 		} else {
1081 			*band = bands[band->index];
1082 			ret = 0;
1083 		}
1084 	} else if (band->tuner == 1) {
1085 		ret = v4l2_subdev_call(dev->v4l2_subdev, tuner,
1086 				       enum_freq_bands, band);
1087 	} else {
1088 		ret = -EINVAL;
1089 	}
1090 
1091 	return ret;
1092 }
1093 
1094 static const struct v4l2_ioctl_ops msi2500_ioctl_ops = {
1095 	.vidioc_querycap          = msi2500_querycap,
1096 
1097 	.vidioc_enum_fmt_sdr_cap  = msi2500_enum_fmt_sdr_cap,
1098 	.vidioc_g_fmt_sdr_cap     = msi2500_g_fmt_sdr_cap,
1099 	.vidioc_s_fmt_sdr_cap     = msi2500_s_fmt_sdr_cap,
1100 	.vidioc_try_fmt_sdr_cap   = msi2500_try_fmt_sdr_cap,
1101 
1102 	.vidioc_reqbufs           = vb2_ioctl_reqbufs,
1103 	.vidioc_create_bufs       = vb2_ioctl_create_bufs,
1104 	.vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1105 	.vidioc_querybuf          = vb2_ioctl_querybuf,
1106 	.vidioc_qbuf              = vb2_ioctl_qbuf,
1107 	.vidioc_dqbuf             = vb2_ioctl_dqbuf,
1108 
1109 	.vidioc_streamon          = vb2_ioctl_streamon,
1110 	.vidioc_streamoff         = vb2_ioctl_streamoff,
1111 
1112 	.vidioc_g_tuner           = msi2500_g_tuner,
1113 	.vidioc_s_tuner           = msi2500_s_tuner,
1114 
1115 	.vidioc_g_frequency       = msi2500_g_frequency,
1116 	.vidioc_s_frequency       = msi2500_s_frequency,
1117 	.vidioc_enum_freq_bands   = msi2500_enum_freq_bands,
1118 
1119 	.vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1120 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1121 	.vidioc_log_status        = v4l2_ctrl_log_status,
1122 };
1123 
1124 static const struct v4l2_file_operations msi2500_fops = {
1125 	.owner                    = THIS_MODULE,
1126 	.open                     = v4l2_fh_open,
1127 	.release                  = vb2_fop_release,
1128 	.read                     = vb2_fop_read,
1129 	.poll                     = vb2_fop_poll,
1130 	.mmap                     = vb2_fop_mmap,
1131 	.unlocked_ioctl           = video_ioctl2,
1132 };
1133 
1134 static const struct video_device msi2500_template = {
1135 	.name                     = "Mirics MSi3101 SDR Dongle",
1136 	.release                  = video_device_release_empty,
1137 	.fops                     = &msi2500_fops,
1138 	.ioctl_ops                = &msi2500_ioctl_ops,
1139 };
1140 
1141 static void msi2500_video_release(struct v4l2_device *v)
1142 {
1143 	struct msi2500_dev *dev = container_of(v, struct msi2500_dev, v4l2_dev);
1144 
1145 	v4l2_ctrl_handler_free(&dev->hdl);
1146 	v4l2_device_unregister(&dev->v4l2_dev);
1147 	kfree(dev);
1148 }
1149 
1150 static int msi2500_transfer_one_message(struct spi_master *master,
1151 					struct spi_message *m)
1152 {
1153 	struct msi2500_dev *dev = spi_master_get_devdata(master);
1154 	struct spi_transfer *t;
1155 	int ret = 0;
1156 	u32 data;
1157 
1158 	list_for_each_entry(t, &m->transfers, transfer_list) {
1159 		dev_dbg(dev->dev, "msg=%*ph\n", t->len, t->tx_buf);
1160 		data = 0x09; /* reg 9 is SPI adapter */
1161 		data |= ((u8 *)t->tx_buf)[0] << 8;
1162 		data |= ((u8 *)t->tx_buf)[1] << 16;
1163 		data |= ((u8 *)t->tx_buf)[2] << 24;
1164 		ret = msi2500_ctrl_msg(dev, CMD_WREG, data);
1165 	}
1166 
1167 	m->status = ret;
1168 	spi_finalize_current_message(master);
1169 	return ret;
1170 }
1171 
1172 static int msi2500_probe(struct usb_interface *intf,
1173 			 const struct usb_device_id *id)
1174 {
1175 	struct msi2500_dev *dev;
1176 	struct v4l2_subdev *sd;
1177 	struct spi_master *master;
1178 	int ret;
1179 	static struct spi_board_info board_info = {
1180 		.modalias		= "msi001",
1181 		.bus_num		= 0,
1182 		.chip_select		= 0,
1183 		.max_speed_hz		= 12000000,
1184 	};
1185 
1186 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1187 	if (!dev) {
1188 		ret = -ENOMEM;
1189 		goto err;
1190 	}
1191 
1192 	mutex_init(&dev->v4l2_lock);
1193 	mutex_init(&dev->vb_queue_lock);
1194 	spin_lock_init(&dev->queued_bufs_lock);
1195 	INIT_LIST_HEAD(&dev->queued_bufs);
1196 	dev->dev = &intf->dev;
1197 	dev->udev = interface_to_usbdev(intf);
1198 	dev->f_adc = bands[0].rangelow;
1199 	dev->pixelformat = formats[0].pixelformat;
1200 	dev->buffersize = formats[0].buffersize;
1201 	dev->num_formats = NUM_FORMATS;
1202 	if (!msi2500_emulated_fmt)
1203 		dev->num_formats -= 2;
1204 
1205 	/* Init videobuf2 queue structure */
1206 	dev->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1207 	dev->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1208 	dev->vb_queue.drv_priv = dev;
1209 	dev->vb_queue.buf_struct_size = sizeof(struct msi2500_frame_buf);
1210 	dev->vb_queue.ops = &msi2500_vb2_ops;
1211 	dev->vb_queue.mem_ops = &vb2_vmalloc_memops;
1212 	dev->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1213 	ret = vb2_queue_init(&dev->vb_queue);
1214 	if (ret) {
1215 		dev_err(dev->dev, "Could not initialize vb2 queue\n");
1216 		goto err_free_mem;
1217 	}
1218 
1219 	/* Init video_device structure */
1220 	dev->vdev = msi2500_template;
1221 	dev->vdev.queue = &dev->vb_queue;
1222 	dev->vdev.queue->lock = &dev->vb_queue_lock;
1223 	video_set_drvdata(&dev->vdev, dev);
1224 
1225 	/* Register the v4l2_device structure */
1226 	dev->v4l2_dev.release = msi2500_video_release;
1227 	ret = v4l2_device_register(&intf->dev, &dev->v4l2_dev);
1228 	if (ret) {
1229 		dev_err(dev->dev, "Failed to register v4l2-device (%d)\n", ret);
1230 		goto err_free_mem;
1231 	}
1232 
1233 	/* SPI master adapter */
1234 	master = spi_alloc_master(dev->dev, 0);
1235 	if (master == NULL) {
1236 		ret = -ENOMEM;
1237 		goto err_unregister_v4l2_dev;
1238 	}
1239 
1240 	dev->master = master;
1241 	master->bus_num = 0;
1242 	master->num_chipselect = 1;
1243 	master->transfer_one_message = msi2500_transfer_one_message;
1244 	spi_master_set_devdata(master, dev);
1245 	ret = spi_register_master(master);
1246 	if (ret) {
1247 		spi_master_put(master);
1248 		goto err_unregister_v4l2_dev;
1249 	}
1250 
1251 	/* load v4l2 subdevice */
1252 	sd = v4l2_spi_new_subdev(&dev->v4l2_dev, master, &board_info);
1253 	dev->v4l2_subdev = sd;
1254 	if (sd == NULL) {
1255 		dev_err(dev->dev, "cannot get v4l2 subdevice\n");
1256 		ret = -ENODEV;
1257 		goto err_unregister_master;
1258 	}
1259 
1260 	/* Register controls */
1261 	v4l2_ctrl_handler_init(&dev->hdl, 0);
1262 	if (dev->hdl.error) {
1263 		ret = dev->hdl.error;
1264 		dev_err(dev->dev, "Could not initialize controls\n");
1265 		goto err_free_controls;
1266 	}
1267 
1268 	/* currently all controls are from subdev */
1269 	v4l2_ctrl_add_handler(&dev->hdl, sd->ctrl_handler, NULL, true);
1270 
1271 	dev->v4l2_dev.ctrl_handler = &dev->hdl;
1272 	dev->vdev.v4l2_dev = &dev->v4l2_dev;
1273 	dev->vdev.lock = &dev->v4l2_lock;
1274 	dev->vdev.device_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_STREAMING |
1275 				V4L2_CAP_READWRITE | V4L2_CAP_TUNER;
1276 
1277 	ret = video_register_device(&dev->vdev, VFL_TYPE_SDR, -1);
1278 	if (ret) {
1279 		dev_err(dev->dev,
1280 			"Failed to register as video device (%d)\n", ret);
1281 		goto err_unregister_v4l2_dev;
1282 	}
1283 	dev_info(dev->dev, "Registered as %s\n",
1284 		 video_device_node_name(&dev->vdev));
1285 	dev_notice(dev->dev,
1286 		   "SDR API is still slightly experimental and functionality changes may follow\n");
1287 	return 0;
1288 err_free_controls:
1289 	v4l2_ctrl_handler_free(&dev->hdl);
1290 err_unregister_master:
1291 	spi_unregister_master(dev->master);
1292 err_unregister_v4l2_dev:
1293 	v4l2_device_unregister(&dev->v4l2_dev);
1294 err_free_mem:
1295 	kfree(dev);
1296 err:
1297 	return ret;
1298 }
1299 
1300 /* USB device ID list */
1301 static const struct usb_device_id msi2500_id_table[] = {
1302 	{USB_DEVICE(0x1df7, 0x2500)}, /* Mirics MSi3101 SDR Dongle */
1303 	{USB_DEVICE(0x2040, 0xd300)}, /* Hauppauge WinTV 133559 LF */
1304 	{}
1305 };
1306 MODULE_DEVICE_TABLE(usb, msi2500_id_table);
1307 
1308 /* USB subsystem interface */
1309 static struct usb_driver msi2500_driver = {
1310 	.name                     = KBUILD_MODNAME,
1311 	.probe                    = msi2500_probe,
1312 	.disconnect               = msi2500_disconnect,
1313 	.id_table                 = msi2500_id_table,
1314 };
1315 
1316 module_usb_driver(msi2500_driver);
1317 
1318 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1319 MODULE_DESCRIPTION("Mirics MSi3101 SDR Dongle");
1320 MODULE_LICENSE("GPL");
1321