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