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