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