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