[media] msi3101: add 2040:d300 Hauppauge WinTV 133559 LF
[linux-2.6-block.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
21 #include <linux/kernel.h>
22 #include <linux/module.h>
23 #include <linux/init.h>
24 #include <linux/slab.h>
25 #include <linux/input.h>
26 #include <linux/videodev2.h>
27 #include <media/v4l2-device.h>
28 #include <media/v4l2-ioctl.h>
29 #include <media/v4l2-ctrls.h>
30 #include <media/v4l2-event.h>
31 #include <linux/usb.h>
32 #include <linux/mutex.h>
33 #include <media/videobuf2-vmalloc.h>
34
35 struct msi3101_gain {
36         u8 tot:7;
37         u8 baseband:6;
38         bool lna:1;
39         bool mixer:1;
40 };
41
42 /* 60 – 120 MHz band, lna 24dB, mixer 19dB */
43 static const struct msi3101_gain msi3101_gain_lut_120[] = {
44         {  0,  0,  0,  0},
45         {  1,  1,  0,  0},
46         {  2,  2,  0,  0},
47         {  3,  3,  0,  0},
48         {  4,  4,  0,  0},
49         {  5,  5,  0,  0},
50         {  6,  6,  0,  0},
51         {  7,  7,  0,  0},
52         {  8,  8,  0,  0},
53         {  9,  9,  0,  0},
54         { 10, 10,  0,  0},
55         { 11, 11,  0,  0},
56         { 12, 12,  0,  0},
57         { 13, 13,  0,  0},
58         { 14, 14,  0,  0},
59         { 15, 15,  0,  0},
60         { 16, 16,  0,  0},
61         { 17, 17,  0,  0},
62         { 18, 18,  0,  0},
63         { 19, 19,  0,  0},
64         { 20, 20,  0,  0},
65         { 21, 21,  0,  0},
66         { 22, 22,  0,  0},
67         { 23, 23,  0,  0},
68         { 24, 24,  0,  0},
69         { 25, 25,  0,  0},
70         { 26, 26,  0,  0},
71         { 27, 27,  0,  0},
72         { 28, 28,  0,  0},
73         { 29,  5,  1,  0},
74         { 30,  6,  1,  0},
75         { 31,  7,  1,  0},
76         { 32,  8,  1,  0},
77         { 33,  9,  1,  0},
78         { 34, 10,  1,  0},
79         { 35, 11,  1,  0},
80         { 36, 12,  1,  0},
81         { 37, 13,  1,  0},
82         { 38, 14,  1,  0},
83         { 39, 15,  1,  0},
84         { 40, 16,  1,  0},
85         { 41, 17,  1,  0},
86         { 42, 18,  1,  0},
87         { 43, 19,  1,  0},
88         { 44, 20,  1,  0},
89         { 45, 21,  1,  0},
90         { 46, 22,  1,  0},
91         { 47, 23,  1,  0},
92         { 48, 24,  1,  0},
93         { 49, 25,  1,  0},
94         { 50, 26,  1,  0},
95         { 51, 27,  1,  0},
96         { 52, 28,  1,  0},
97         { 53, 29,  1,  0},
98         { 54, 30,  1,  0},
99         { 55, 31,  1,  0},
100         { 56, 32,  1,  0},
101         { 57, 33,  1,  0},
102         { 58, 34,  1,  0},
103         { 59, 35,  1,  0},
104         { 60, 36,  1,  0},
105         { 61, 37,  1,  0},
106         { 62, 38,  1,  0},
107         { 63, 39,  1,  0},
108         { 64, 40,  1,  0},
109         { 65, 41,  1,  0},
110         { 66, 42,  1,  0},
111         { 67, 43,  1,  0},
112         { 68, 44,  1,  0},
113         { 69, 45,  1,  0},
114         { 70, 46,  1,  0},
115         { 71, 47,  1,  0},
116         { 72, 48,  1,  0},
117         { 73, 49,  1,  0},
118         { 74, 50,  1,  0},
119         { 75, 51,  1,  0},
120         { 76, 52,  1,  0},
121         { 77, 53,  1,  0},
122         { 78, 54,  1,  0},
123         { 79, 55,  1,  0},
124         { 80, 56,  1,  0},
125         { 81, 57,  1,  0},
126         { 82, 58,  1,  0},
127         { 83, 40,  1,  1},
128         { 84, 41,  1,  1},
129         { 85, 42,  1,  1},
130         { 86, 43,  1,  1},
131         { 87, 44,  1,  1},
132         { 88, 45,  1,  1},
133         { 89, 46,  1,  1},
134         { 90, 47,  1,  1},
135         { 91, 48,  1,  1},
136         { 92, 49,  1,  1},
137         { 93, 50,  1,  1},
138         { 94, 51,  1,  1},
139         { 95, 52,  1,  1},
140         { 96, 53,  1,  1},
141         { 97, 54,  1,  1},
142         { 98, 55,  1,  1},
143         { 99, 56,  1,  1},
144         {100, 57,  1,  1},
145         {101, 58,  1,  1},
146         {102, 59,  1,  1},
147 };
148
149 /* 120 – 245 MHz band, lna 24dB, mixer 19dB */
150 static const struct msi3101_gain msi3101_gain_lut_245[] = {
151         {  0,  0,  0,  0},
152         {  1,  1,  0,  0},
153         {  2,  2,  0,  0},
154         {  3,  3,  0,  0},
155         {  4,  4,  0,  0},
156         {  5,  5,  0,  0},
157         {  6,  6,  0,  0},
158         {  7,  7,  0,  0},
159         {  8,  8,  0,  0},
160         {  9,  9,  0,  0},
161         { 10, 10,  0,  0},
162         { 11, 11,  0,  0},
163         { 12, 12,  0,  0},
164         { 13, 13,  0,  0},
165         { 14, 14,  0,  0},
166         { 15, 15,  0,  0},
167         { 16, 16,  0,  0},
168         { 17, 17,  0,  0},
169         { 18, 18,  0,  0},
170         { 19, 19,  0,  0},
171         { 20, 20,  0,  0},
172         { 21, 21,  0,  0},
173         { 22, 22,  0,  0},
174         { 23, 23,  0,  0},
175         { 24, 24,  0,  0},
176         { 25, 25,  0,  0},
177         { 26, 26,  0,  0},
178         { 27, 27,  0,  0},
179         { 28, 28,  0,  0},
180         { 29,  5,  1,  0},
181         { 30,  6,  1,  0},
182         { 31,  7,  1,  0},
183         { 32,  8,  1,  0},
184         { 33,  9,  1,  0},
185         { 34, 10,  1,  0},
186         { 35, 11,  1,  0},
187         { 36, 12,  1,  0},
188         { 37, 13,  1,  0},
189         { 38, 14,  1,  0},
190         { 39, 15,  1,  0},
191         { 40, 16,  1,  0},
192         { 41, 17,  1,  0},
193         { 42, 18,  1,  0},
194         { 43, 19,  1,  0},
195         { 44, 20,  1,  0},
196         { 45, 21,  1,  0},
197         { 46, 22,  1,  0},
198         { 47, 23,  1,  0},
199         { 48, 24,  1,  0},
200         { 49, 25,  1,  0},
201         { 50, 26,  1,  0},
202         { 51, 27,  1,  0},
203         { 52, 28,  1,  0},
204         { 53, 29,  1,  0},
205         { 54, 30,  1,  0},
206         { 55, 31,  1,  0},
207         { 56, 32,  1,  0},
208         { 57, 33,  1,  0},
209         { 58, 34,  1,  0},
210         { 59, 35,  1,  0},
211         { 60, 36,  1,  0},
212         { 61, 37,  1,  0},
213         { 62, 38,  1,  0},
214         { 63, 39,  1,  0},
215         { 64, 40,  1,  0},
216         { 65, 41,  1,  0},
217         { 66, 42,  1,  0},
218         { 67, 43,  1,  0},
219         { 68, 44,  1,  0},
220         { 69, 45,  1,  0},
221         { 70, 46,  1,  0},
222         { 71, 47,  1,  0},
223         { 72, 48,  1,  0},
224         { 73, 49,  1,  0},
225         { 74, 50,  1,  0},
226         { 75, 51,  1,  0},
227         { 76, 52,  1,  0},
228         { 77, 53,  1,  0},
229         { 78, 54,  1,  0},
230         { 79, 55,  1,  0},
231         { 80, 56,  1,  0},
232         { 81, 57,  1,  0},
233         { 82, 58,  1,  0},
234         { 83, 40,  1,  1},
235         { 84, 41,  1,  1},
236         { 85, 42,  1,  1},
237         { 86, 43,  1,  1},
238         { 87, 44,  1,  1},
239         { 88, 45,  1,  1},
240         { 89, 46,  1,  1},
241         { 90, 47,  1,  1},
242         { 91, 48,  1,  1},
243         { 92, 49,  1,  1},
244         { 93, 50,  1,  1},
245         { 94, 51,  1,  1},
246         { 95, 52,  1,  1},
247         { 96, 53,  1,  1},
248         { 97, 54,  1,  1},
249         { 98, 55,  1,  1},
250         { 99, 56,  1,  1},
251         {100, 57,  1,  1},
252         {101, 58,  1,  1},
253         {102, 59,  1,  1},
254 };
255
256 /* 420 – 1000 MHz band, lna 7dB, mixer 19dB */
257 static const struct msi3101_gain msi3101_gain_lut_1000[] = {
258         {  0,  0, 0,  0},
259         {  1,  1, 0,  0},
260         {  2,  2, 0,  0},
261         {  3,  3, 0,  0},
262         {  4,  4, 0,  0},
263         {  5,  5, 0,  0},
264         {  6,  6, 0,  0},
265         {  7,  7, 0,  0},
266         {  8,  8, 0,  0},
267         {  9,  9, 0,  0},
268         { 10, 10, 0,  0},
269         { 11, 11, 0,  0},
270         { 12,  5, 1,  0},
271         { 13,  6, 1,  0},
272         { 14,  7, 1,  0},
273         { 15,  8, 1,  0},
274         { 16,  9, 1,  0},
275         { 17, 10, 1,  0},
276         { 18, 11, 1,  0},
277         { 19, 12, 1,  0},
278         { 20, 13, 1,  0},
279         { 21, 14, 1,  0},
280         { 22, 15, 1,  0},
281         { 23, 16, 1,  0},
282         { 24, 17, 1,  0},
283         { 25, 18, 1,  0},
284         { 26, 19, 1,  0},
285         { 27, 20, 1,  0},
286         { 28, 21, 1,  0},
287         { 29, 22, 1,  0},
288         { 30, 23, 1,  0},
289         { 31, 24, 1,  0},
290         { 32, 25, 1,  0},
291         { 33, 26, 1,  0},
292         { 34, 27, 1,  0},
293         { 35, 28, 1,  0},
294         { 36, 29, 1,  0},
295         { 37, 30, 1,  0},
296         { 38, 31, 1,  0},
297         { 39, 32, 1,  0},
298         { 40, 33, 1,  0},
299         { 41, 34, 1,  0},
300         { 42, 35, 1,  0},
301         { 43, 36, 1,  0},
302         { 44, 37, 1,  0},
303         { 45, 38, 1,  0},
304         { 46, 39, 1,  0},
305         { 47, 40, 1,  0},
306         { 48, 41, 1,  0},
307         { 49, 42, 1,  0},
308         { 50, 43, 1,  0},
309         { 51, 44, 1,  0},
310         { 52, 45, 1,  0},
311         { 53, 46, 1,  0},
312         { 54, 47, 1,  0},
313         { 55, 48, 1,  0},
314         { 56, 49, 1,  0},
315         { 57, 50, 1,  0},
316         { 58, 51, 1,  0},
317         { 59, 52, 1,  0},
318         { 60, 53, 1,  0},
319         { 61, 54, 1,  0},
320         { 62, 55, 1,  0},
321         { 63, 56, 1,  0},
322         { 64, 57, 1,  0},
323         { 65, 58, 1,  0},
324         { 66, 40, 1,  1},
325         { 67, 41, 1,  1},
326         { 68, 42, 1,  1},
327         { 69, 43, 1,  1},
328         { 70, 44, 1,  1},
329         { 71, 45, 1,  1},
330         { 72, 46, 1,  1},
331         { 73, 47, 1,  1},
332         { 74, 48, 1,  1},
333         { 75, 49, 1,  1},
334         { 76, 50, 1,  1},
335         { 77, 51, 1,  1},
336         { 78, 52, 1,  1},
337         { 79, 53, 1,  1},
338         { 80, 54, 1,  1},
339         { 81, 55, 1,  1},
340         { 82, 56, 1,  1},
341         { 83, 57, 1,  1},
342         { 84, 58, 1,  1},
343         { 85, 59, 1,  1},
344 };
345
346 /*
347  *   iConfiguration          0
348  *     bInterfaceNumber        0
349  *     bAlternateSetting       1
350  *     bNumEndpoints           1
351  *       bEndpointAddress     0x81  EP 1 IN
352  *       bmAttributes            1
353  *         Transfer Type            Isochronous
354  *       wMaxPacketSize     0x1400  3x 1024 bytes
355  *       bInterval               1
356  */
357 #define MAX_ISO_BUFS            (8)
358 #define ISO_FRAMES_PER_DESC     (8)
359 #define ISO_MAX_FRAME_SIZE      (3 * 1024)
360 #define ISO_BUFFER_SIZE         (ISO_FRAMES_PER_DESC * ISO_MAX_FRAME_SIZE)
361
362 #define MAX_ISOC_ERRORS         20
363
364 #define MSI3101_CID_SAMPLING_MODE         ((V4L2_CID_USER_BASE | 0xf000) + 0)
365 #define MSI3101_CID_SAMPLING_RATE         ((V4L2_CID_USER_BASE | 0xf000) + 1)
366 #define MSI3101_CID_SAMPLING_RESOLUTION   ((V4L2_CID_USER_BASE | 0xf000) + 2)
367 #define MSI3101_CID_TUNER_RF              ((V4L2_CID_USER_BASE | 0xf000) + 10)
368 #define MSI3101_CID_TUNER_BW              ((V4L2_CID_USER_BASE | 0xf000) + 11)
369 #define MSI3101_CID_TUNER_IF              ((V4L2_CID_USER_BASE | 0xf000) + 12)
370 #define MSI3101_CID_TUNER_GAIN            ((V4L2_CID_USER_BASE | 0xf000) + 13)
371
372 /* intermediate buffers with raw data from the USB device */
373 struct msi3101_frame_buf {
374         struct vb2_buffer vb;   /* common v4l buffer stuff -- must be first */
375         struct list_head list;
376         void *data;             /* raw data from USB device */
377         int filled;             /* number of bytes filled to *data */
378 };
379
380 struct msi3101_state {
381         struct video_device vdev;
382         struct v4l2_device v4l2_dev;
383
384         /* videobuf2 queue and queued buffers list */
385         struct vb2_queue vb_queue;
386         struct list_head queued_bufs;
387         spinlock_t queued_bufs_lock; /* Protects queued_bufs */
388
389         /* Note if taking both locks v4l2_lock must always be locked first! */
390         struct mutex v4l2_lock;      /* Protects everything else */
391         struct mutex vb_queue_lock;  /* Protects vb_queue and capt_file */
392
393         /* Pointer to our usb_device, will be NULL after unplug */
394         struct usb_device *udev; /* Both mutexes most be hold when setting! */
395
396         unsigned int isoc_errors; /* number of contiguous ISOC errors */
397         unsigned int vb_full; /* vb is full and packets dropped */
398
399         struct urb *urbs[MAX_ISO_BUFS];
400
401         /* Controls */
402         struct v4l2_ctrl_handler ctrl_handler;
403         struct v4l2_ctrl *ctrl_sampling_rate;
404         struct v4l2_ctrl *ctrl_tuner_rf;
405         struct v4l2_ctrl *ctrl_tuner_bw;
406         struct v4l2_ctrl *ctrl_tuner_if;
407         struct v4l2_ctrl *ctrl_tuner_gain;
408
409         u32 next_sample; /* for track lost packets */
410         u32 sample; /* for sample rate calc */
411         unsigned long jiffies;
412         unsigned int sample_ctrl_bit[4];
413 };
414
415 /* Private functions */
416 static struct msi3101_frame_buf *msi3101_get_next_fill_buf(
417                 struct msi3101_state *s)
418 {
419         unsigned long flags = 0;
420         struct msi3101_frame_buf *buf = NULL;
421
422         spin_lock_irqsave(&s->queued_bufs_lock, flags);
423         if (list_empty(&s->queued_bufs))
424                 goto leave;
425
426         buf = list_entry(s->queued_bufs.next, struct msi3101_frame_buf, list);
427         list_del(&buf->list);
428 leave:
429         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
430         return buf;
431 }
432
433 /*
434  * +===========================================================================
435  * |   00-1024 | USB packet
436  * +===========================================================================
437  * |   00-  03 | sequence number of first sample in that USB packet
438  * +---------------------------------------------------------------------------
439  * |   04-  15 | garbage
440  * +---------------------------------------------------------------------------
441  * |   16- 175 | samples
442  * +---------------------------------------------------------------------------
443  * |  176- 179 | control bits for previous samples
444  * +---------------------------------------------------------------------------
445  * |  180- 339 | samples
446  * +---------------------------------------------------------------------------
447  * |  340- 343 | control bits for previous samples
448  * +---------------------------------------------------------------------------
449  * |  344- 503 | samples
450  * +---------------------------------------------------------------------------
451  * |  504- 507 | control bits for previous samples
452  * +---------------------------------------------------------------------------
453  * |  508- 667 | samples
454  * +---------------------------------------------------------------------------
455  * |  668- 671 | control bits for previous samples
456  * +---------------------------------------------------------------------------
457  * |  672- 831 | samples
458  * +---------------------------------------------------------------------------
459  * |  832- 835 | control bits for previous samples
460  * +---------------------------------------------------------------------------
461  * |  836- 995 | samples
462  * +---------------------------------------------------------------------------
463  * |  996- 999 | control bits for previous samples
464  * +---------------------------------------------------------------------------
465  * | 1000-1024 | garbage
466  * +---------------------------------------------------------------------------
467  *
468  * Bytes 4 - 7 could have some meaning?
469  *
470  * Control bits for previous samples is 32-bit field, containing 16 x 2-bit
471  * numbers. This results one 2-bit number for 8 samples. It is likely used for
472  * for bit shifting sample by given bits, increasing actual sampling resolution.
473  * Number 2 (0b10) was never seen.
474  *
475  * 6 * 16 * 2 * 4 = 768 samples. 768 * 4 = 3072 bytes
476  */
477
478 /*
479  * Converts signed 10-bit integer into 32-bit IEEE floating point
480  * representation.
481  * Will be exact from 0 to 2^24.  Above that, we round towards zero
482  * as the fractional bits will not fit in a float.  (It would be better to
483  * round towards even as the fpu does, but that is slower.)
484  */
485 #define I2F_FRAC_BITS  23
486 #define I2F_MASK ((1 << I2F_FRAC_BITS) - 1)
487 static u32 msi3101_convert_sample(struct msi3101_state *s, u16 x, int shift)
488 {
489         u32 msb, exponent, fraction, sign;
490         s->sample_ctrl_bit[shift]++;
491
492         /* Zero is special */
493         if (!x)
494                 return 0;
495
496         /* Convert 10-bit two's complement to 13-bit */
497         if (x & (1 << 9)) {
498                 x |= ~0U << 10; /* set all the rest bits to one */
499                 x <<= shift;
500                 x = -x;
501                 x &= 0xfff; /* result is 12 bit ... + sign */
502                 sign = 1 << 31;
503         } else {
504                 x <<= shift;
505                 sign = 0 << 31;
506         }
507
508         /* Get location of the most significant bit */
509         msb = __fls(x);
510
511         /*
512          * Use a rotate instead of a shift because that works both leftwards
513          * and rightwards due to the mod(32) behaviour.  This means we don't
514          * need to check to see if we are above 2^24 or not.
515          */
516         fraction = ror32(x, (msb - I2F_FRAC_BITS) & 0x1f) & I2F_MASK;
517         exponent = (127 + msb) << I2F_FRAC_BITS;
518
519         return (fraction + exponent) | sign;
520 }
521
522 #define MSI3101_CONVERT_IN_URB_HANDLER
523 #define MSI3101_EXTENSIVE_DEBUG
524 static int msi3101_convert_stream(struct msi3101_state *s, u32 *dst,
525                 const u8 *src, unsigned int src_len)
526 {
527         int i, j, k, l, i_max, dst_len = 0;
528         u16 sample[4];
529         u32 bits;
530 #ifdef MSI3101_EXTENSIVE_DEBUG
531         u32 sample_num[3];
532 #endif
533         /* There could be 1-3 1024 bytes URB frames */
534         i_max = src_len / 1024;
535         for (i = 0; i < i_max; i++) {
536 #ifdef MSI3101_EXTENSIVE_DEBUG
537                 sample_num[i] = src[3] << 24 | src[2] << 16 | src[1] << 8 | src[0] << 0;
538                 if (i == 0 && s->next_sample != sample_num[0]) {
539                         dev_dbg(&s->udev->dev,
540                                         "%d samples lost, %d %08x:%08x\n",
541                                         sample_num[0] - s->next_sample,
542                                         src_len, s->next_sample, sample_num[0]);
543                 }
544 #endif
545                 src += 16;
546                 for (j = 0; j < 6; j++) {
547                         bits = src[160 + 3] << 24 | src[160 + 2] << 16 | src[160 + 1] << 8 | src[160 + 0] << 0;
548                         for (k = 0; k < 16; k++) {
549                                 for (l = 0; l < 10; l += 5) {
550                                         sample[0] = (src[l + 0] & 0xff) >> 0 | (src[l + 1] & 0x03) << 8;
551                                         sample[1] = (src[l + 1] & 0xfc) >> 2 | (src[l + 2] & 0x0f) << 6;
552                                         sample[2] = (src[l + 2] & 0xf0) >> 4 | (src[l + 3] & 0x3f) << 4;
553                                         sample[3] = (src[l + 3] & 0xc0) >> 6 | (src[l + 4] & 0xff) << 2;
554
555                                         *dst++ = msi3101_convert_sample(s, sample[0], (bits >> (2 * k)) & 0x3);
556                                         *dst++ = msi3101_convert_sample(s, sample[1], (bits >> (2 * k)) & 0x3);
557                                         *dst++ = msi3101_convert_sample(s, sample[2], (bits >> (2 * k)) & 0x3);
558                                         *dst++ = msi3101_convert_sample(s, sample[3], (bits >> (2 * k)) & 0x3);
559
560                                         /* 4 x 32bit float samples */
561                                         dst_len += 4 * 4;
562                                 }
563                                 src += 10;
564                         }
565 #ifdef MSI3101_EXTENSIVE_DEBUG
566                         dev_dbg_ratelimited(&s->udev->dev,
567                                         "sample control bits %08x\n", bits);
568 #endif
569                         src += 4;
570                 }
571                 src += 24;
572         }
573
574 #ifdef MSI3101_EXTENSIVE_DEBUG
575         /* calculate samping rate and output it in 10 seconds intervals */
576         if ((s->jiffies + msecs_to_jiffies(10000)) <= jiffies) {
577                 unsigned long jiffies_now = jiffies;
578                 unsigned long msecs = jiffies_to_msecs(jiffies_now) - jiffies_to_msecs(s->jiffies);
579                 unsigned int samples = sample_num[i_max - 1] - s->sample;
580                 s->jiffies = jiffies_now;
581                 s->sample = sample_num[i_max - 1];
582                 dev_dbg(&s->udev->dev,
583                                 "slen=%d samples=%u msecs=%lu sampling rate=%lu bits=%d.%d.%d.%d\n",
584                                 src_len, samples, msecs,
585                                 samples * 1000UL / msecs,
586                                 s->sample_ctrl_bit[0], s->sample_ctrl_bit[1],
587                                 s->sample_ctrl_bit[2], s->sample_ctrl_bit[3]);
588         }
589
590         /* next sample (sample = sample + i * 384) */
591         s->next_sample = sample_num[i_max - 1] + 384;
592 #endif
593         return dst_len;
594 }
595
596 /*
597  * This gets called for the Isochronous pipe (stream). This is done in interrupt
598  * time, so it has to be fast, not crash, and not stall. Neat.
599  */
600 static void msi3101_isoc_handler(struct urb *urb)
601 {
602         struct msi3101_state *s = (struct msi3101_state *)urb->context;
603         int i, flen, fstatus;
604         unsigned char *iso_buf = NULL;
605         struct msi3101_frame_buf *fbuf;
606
607         if (urb->status == -ENOENT || urb->status == -ECONNRESET ||
608                         urb->status == -ESHUTDOWN) {
609                 dev_dbg(&s->udev->dev, "URB (%p) unlinked %ssynchronuously\n",
610                                 urb, urb->status == -ENOENT ? "" : "a");
611                 return;
612         }
613
614         if (urb->status != 0) {
615                 dev_dbg(&s->udev->dev,
616                                 "msi3101_isoc_handler() called with status %d\n",
617                                 urb->status);
618                 /* Give up after a number of contiguous errors */
619                 if (++s->isoc_errors > MAX_ISOC_ERRORS)
620                         dev_dbg(&s->udev->dev,
621                                         "Too many ISOC errors, bailing out\n");
622                 goto handler_end;
623         } else {
624                 /* Reset ISOC error counter. We did get here, after all. */
625                 s->isoc_errors = 0;
626         }
627
628         /* Compact data */
629         for (i = 0; i < urb->number_of_packets; i++) {
630                 /* Check frame error */
631                 fstatus = urb->iso_frame_desc[i].status;
632                 if (fstatus) {
633                         dev_dbg(&s->udev->dev,
634                                         "frame=%d/%d has error %d skipping\n",
635                                         i, urb->number_of_packets, fstatus);
636                         goto skip;
637                 }
638
639                 /* Check if that frame contains data */
640                 flen = urb->iso_frame_desc[i].actual_length;
641                 if (flen == 0)
642                         goto skip;
643
644                 iso_buf = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
645
646                 /* Get free framebuffer */
647                 fbuf = msi3101_get_next_fill_buf(s);
648                 if (fbuf == NULL) {
649                         s->vb_full++;
650                         dev_dbg_ratelimited(&s->udev->dev,
651                                         "videobuf is full, %d packets dropped\n",
652                                         s->vb_full);
653                         goto skip;
654                 }
655
656                 /* fill framebuffer */
657 #ifdef MSI3101_CONVERT_IN_URB_HANDLER
658                 vb2_set_plane_payload(&fbuf->vb, 0,
659                                 msi3101_convert_stream(s,
660                                 vb2_plane_vaddr(&fbuf->vb, 0), iso_buf, flen));
661 #else
662                 memcpy(fbuf->data, iso_buf, flen);
663                 fbuf->filled = flen;
664 #endif
665                 vb2_buffer_done(&fbuf->vb, VB2_BUF_STATE_DONE);
666 skip:
667                 ;
668         }
669
670 handler_end:
671         i = usb_submit_urb(urb, GFP_ATOMIC);
672         if (i != 0)
673                 dev_dbg(&s->udev->dev,
674                                 "Error (%d) re-submitting urb in msi3101_isoc_handler\n",
675                                 i);
676 }
677
678 static void msi3101_iso_stop(struct msi3101_state *s)
679 {
680         int i;
681         dev_dbg(&s->udev->dev, "%s:\n", __func__);
682
683         /* Unlinking ISOC buffers one by one */
684         for (i = 0; i < MAX_ISO_BUFS; i++) {
685                 if (s->urbs[i]) {
686                         dev_dbg(&s->udev->dev, "Unlinking URB %p\n",
687                                         s->urbs[i]);
688                         usb_kill_urb(s->urbs[i]);
689                 }
690         }
691 }
692
693 static void msi3101_iso_free(struct msi3101_state *s)
694 {
695         int i;
696         dev_dbg(&s->udev->dev, "%s:\n", __func__);
697
698         /* Freeing ISOC buffers one by one */
699         for (i = 0; i < MAX_ISO_BUFS; i++) {
700                 if (s->urbs[i]) {
701                         dev_dbg(&s->udev->dev, "Freeing URB\n");
702                         if (s->urbs[i]->transfer_buffer) {
703                                 usb_free_coherent(s->udev,
704                                         s->urbs[i]->transfer_buffer_length,
705                                         s->urbs[i]->transfer_buffer,
706                                         s->urbs[i]->transfer_dma);
707                         }
708                         usb_free_urb(s->urbs[i]);
709                         s->urbs[i] = NULL;
710                 }
711         }
712 }
713
714 /* Both v4l2_lock and vb_queue_lock should be locked when calling this */
715 static void msi3101_isoc_cleanup(struct msi3101_state *s)
716 {
717         dev_dbg(&s->udev->dev, "%s:\n", __func__);
718
719         msi3101_iso_stop(s);
720         msi3101_iso_free(s);
721 }
722
723 /* Both v4l2_lock and vb_queue_lock should be locked when calling this */
724 static int msi3101_isoc_init(struct msi3101_state *s)
725 {
726         struct usb_device *udev;
727         struct urb *urb;
728         int i, j, ret;
729         dev_dbg(&s->udev->dev, "%s:\n", __func__);
730
731         s->isoc_errors = 0;
732         udev = s->udev;
733
734         ret = usb_set_interface(s->udev, 0, 1);
735         if (ret < 0)
736                 return ret;
737
738         /* Allocate and init Isochronuous urbs */
739         for (i = 0; i < MAX_ISO_BUFS; i++) {
740                 urb = usb_alloc_urb(ISO_FRAMES_PER_DESC, GFP_KERNEL);
741                 if (urb == NULL) {
742                         dev_err(&s->udev->dev,
743                                         "Failed to allocate urb %d\n", i);
744                         msi3101_isoc_cleanup(s);
745                         return -ENOMEM;
746                 }
747                 s->urbs[i] = urb;
748                 dev_dbg(&s->udev->dev, "Allocated URB at 0x%p\n", urb);
749
750                 urb->interval = 1;
751                 urb->dev = udev;
752                 urb->pipe = usb_rcvisocpipe(udev, 0x81);
753                 urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
754                 urb->transfer_buffer = usb_alloc_coherent(udev, ISO_BUFFER_SIZE,
755                                 GFP_KERNEL, &urb->transfer_dma);
756                 if (urb->transfer_buffer == NULL) {
757                         dev_err(&s->udev->dev,
758                                         "Failed to allocate urb buffer %d\n",
759                                         i);
760                         msi3101_isoc_cleanup(s);
761                         return -ENOMEM;
762                 }
763                 urb->transfer_buffer_length = ISO_BUFFER_SIZE;
764                 urb->complete = msi3101_isoc_handler;
765                 urb->context = s;
766                 urb->start_frame = 0;
767                 urb->number_of_packets = ISO_FRAMES_PER_DESC;
768                 for (j = 0; j < ISO_FRAMES_PER_DESC; j++) {
769                         urb->iso_frame_desc[j].offset = j * ISO_MAX_FRAME_SIZE;
770                         urb->iso_frame_desc[j].length = ISO_MAX_FRAME_SIZE;
771                 }
772         }
773
774         /* link */
775         for (i = 0; i < MAX_ISO_BUFS; i++) {
776                 ret = usb_submit_urb(s->urbs[i], GFP_KERNEL);
777                 if (ret) {
778                         dev_err(&s->udev->dev,
779                                         "isoc_init() submit_urb %d failed with error %d\n",
780                                         i, ret);
781                         msi3101_isoc_cleanup(s);
782                         return ret;
783                 }
784                 dev_dbg(&s->udev->dev, "URB 0x%p submitted.\n", s->urbs[i]);
785         }
786
787         /* All is done... */
788         return 0;
789 }
790
791 /* Must be called with vb_queue_lock hold */
792 static void msi3101_cleanup_queued_bufs(struct msi3101_state *s)
793 {
794         unsigned long flags = 0;
795         dev_dbg(&s->udev->dev, "%s:\n", __func__);
796
797         spin_lock_irqsave(&s->queued_bufs_lock, flags);
798         while (!list_empty(&s->queued_bufs)) {
799                 struct msi3101_frame_buf *buf;
800
801                 buf = list_entry(s->queued_bufs.next, struct msi3101_frame_buf,
802                                  list);
803                 list_del(&buf->list);
804                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
805         }
806         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
807 }
808
809 /* The user yanked out the cable... */
810 static void msi3101_disconnect(struct usb_interface *intf)
811 {
812         struct v4l2_device *v = usb_get_intfdata(intf);
813         struct msi3101_state *s =
814                         container_of(v, struct msi3101_state, v4l2_dev);
815         dev_dbg(&s->udev->dev, "%s:\n", __func__);
816
817         mutex_lock(&s->vb_queue_lock);
818         mutex_lock(&s->v4l2_lock);
819         /* No need to keep the urbs around after disconnection */
820         s->udev = NULL;
821
822         v4l2_device_disconnect(&s->v4l2_dev);
823         video_unregister_device(&s->vdev);
824         mutex_unlock(&s->v4l2_lock);
825         mutex_unlock(&s->vb_queue_lock);
826
827         v4l2_device_put(&s->v4l2_dev);
828 }
829
830 static int msi3101_querycap(struct file *file, void *fh,
831                 struct v4l2_capability *cap)
832 {
833         struct msi3101_state *s = video_drvdata(file);
834         dev_dbg(&s->udev->dev, "%s:\n", __func__);
835
836         strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
837         strlcpy(cap->card, s->vdev.name, sizeof(cap->card));
838         usb_make_path(s->udev, cap->bus_info, sizeof(cap->bus_info));
839         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
840                         V4L2_CAP_READWRITE;
841         cap->device_caps = V4L2_CAP_TUNER;
842         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
843         return 0;
844 }
845
846
847 /* Videobuf2 operations */
848 static int msi3101_queue_setup(struct vb2_queue *vq,
849                 const struct v4l2_format *fmt, unsigned int *nbuffers,
850                 unsigned int *nplanes, unsigned int sizes[], void *alloc_ctxs[])
851 {
852         struct msi3101_state *s = vb2_get_drv_priv(vq);
853         dev_dbg(&s->udev->dev, "%s: *nbuffers=%d\n", __func__, *nbuffers);
854
855         /* Absolute min and max number of buffers available for mmap() */
856         *nbuffers = 32;
857         *nplanes = 1;
858         sizes[0] = PAGE_ALIGN(3 * 3072); /* 3 * 768 * 4 */
859         dev_dbg(&s->udev->dev, "%s: nbuffers=%d sizes[0]=%d\n",
860                         __func__, *nbuffers, sizes[0]);
861         return 0;
862 }
863
864 static int msi3101_buf_init(struct vb2_buffer *vb)
865 {
866         struct msi3101_state *s = vb2_get_drv_priv(vb->vb2_queue);
867         struct msi3101_frame_buf *fbuf =
868                         container_of(vb, struct msi3101_frame_buf, vb);
869         dev_dbg(&s->udev->dev, "%s:\n", __func__);
870
871         fbuf->data = vzalloc(ISO_MAX_FRAME_SIZE);
872         if (fbuf->data == NULL)
873                 return -ENOMEM;
874
875         return 0;
876 }
877
878 static int msi3101_buf_prepare(struct vb2_buffer *vb)
879 {
880         struct msi3101_state *s = vb2_get_drv_priv(vb->vb2_queue);
881
882         /* Don't allow queing new buffers after device disconnection */
883         if (!s->udev)
884                 return -ENODEV;
885
886         return 0;
887 }
888
889 #ifdef MSI3101_CONVERT_IN_URB_HANDLER
890 static int msi3101_buf_finish(struct vb2_buffer *vb)
891 {
892         return 0;
893 }
894 #else
895 static int msi3101_buf_finish(struct vb2_buffer *vb)
896 {
897         struct msi3101_state *s = vb2_get_drv_priv(vb->vb2_queue);
898         struct msi3101_frame_buf *fbuf =
899                         container_of(vb, struct msi3101_frame_buf, vb);
900         int ret;
901         u32 *dst = vb2_plane_vaddr(&fbuf->vb, 0);
902         ret = msi3101_convert_stream(s, dst, fbuf->data, fbuf->filled);
903         vb2_set_plane_payload(&fbuf->vb, 0, ret);
904         return 0;
905 }
906 #endif
907
908 static void msi3101_buf_cleanup(struct vb2_buffer *vb)
909 {
910         struct msi3101_state *s = vb2_get_drv_priv(vb->vb2_queue);
911         struct msi3101_frame_buf *buf =
912                         container_of(vb, struct msi3101_frame_buf, vb);
913         dev_dbg(&s->udev->dev, "%s:\n", __func__);
914
915         vfree(buf->data);
916 }
917 static void msi3101_buf_queue(struct vb2_buffer *vb)
918 {
919         struct msi3101_state *s = vb2_get_drv_priv(vb->vb2_queue);
920         struct msi3101_frame_buf *buf =
921                         container_of(vb, struct msi3101_frame_buf, vb);
922         unsigned long flags = 0;
923
924         /* Check the device has not disconnected between prep and queuing */
925         if (!s->udev) {
926                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
927                 return;
928         }
929
930         spin_lock_irqsave(&s->queued_bufs_lock, flags);
931         list_add_tail(&buf->list, &s->queued_bufs);
932         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
933 }
934
935 #define CMD_WREG               0x41
936 #define CMD_START_STREAMING    0x43
937 #define CMD_STOP_STREAMING     0x45
938 #define CMD_READ_UNKNOW        0x48
939
940 #define msi3101_dbg_usb_control_msg(udev, r, t, v, _i, b, l) { \
941         char *direction; \
942         if (t == (USB_TYPE_VENDOR | USB_DIR_OUT)) \
943                 direction = ">>>"; \
944         else \
945                 direction = "<<<"; \
946         dev_dbg(&udev->dev, "%s: %02x %02x %02x %02x %02x %02x %02x %02x " \
947                         "%s %*ph\n",  __func__, t, r, v & 0xff, v >> 8, \
948                         _i & 0xff, _i >> 8, l & 0xff, l >> 8, direction, l, b); \
949 }
950
951 static int msi3101_ctrl_msg(struct msi3101_state *s, u8 cmd, u32 data)
952 {
953         int ret;
954         u8 request = cmd;
955         u8 requesttype = USB_DIR_OUT | USB_TYPE_VENDOR;
956         u16 value = (data >> 0) & 0xffff;
957         u16 index = (data >> 16) & 0xffff;
958
959         msi3101_dbg_usb_control_msg(s->udev,
960                         request, requesttype, value, index, NULL, 0);
961
962         ret = usb_control_msg(s->udev, usb_sndctrlpipe(s->udev, 0),
963                         request, requesttype, value, index, NULL, 0, 2000);
964
965         if (ret)
966                 dev_err(&s->udev->dev, "%s: failed %d, cmd %02x, data %04x\n",
967                                 __func__, ret, cmd, data);
968
969         return ret;
970 };
971
972 static int msi3101_tuner_write(struct msi3101_state *s, u32 data)
973 {
974         return msi3101_ctrl_msg(s, CMD_WREG, data << 8 | 0x09);
975 };
976
977 #define F_REF 24000000
978 #define DIV_R_IN 2
979 static int msi3101_set_usb_adc(struct msi3101_state *s)
980 {
981         int ret, div_n, div_m, div_r_out, f_sr, f_vco;
982         u32 reg4, reg3;
983         /*
984          * Synthesizer config is just a educated guess...
985          *
986          * [7:0]   0x03, register address
987          * [8]     1, always
988          * [9]     ?
989          * [12:10] output divider
990          * [13]    0 ?
991          * [14]    0 ?
992          * [15]    increase sr by max fract
993          * [16:19] N
994          * [23:20] ?
995          * [24:31] 0x01
996          *
997          * output divider
998          * val   div
999          *   0     - (invalid)
1000          *   1     4
1001          *   2     6
1002          *   3     8
1003          *   4    10
1004          *   5    12
1005          *   6    14
1006          *   7    16
1007          *
1008          * VCO 202000000 - 720000000++
1009          */
1010
1011         f_sr = s->ctrl_sampling_rate->val64;
1012         reg3 = 0x01c00303;
1013
1014         for (div_r_out = 4; div_r_out < 16; div_r_out += 2) {
1015                 f_vco = f_sr * div_r_out * 12;
1016                 dev_dbg(&s->udev->dev, "%s: div_r_out=%d f_vco=%d\n",
1017                                 __func__, div_r_out, f_vco);
1018                 if (f_vco >= 202000000)
1019                         break;
1020         }
1021
1022         div_n = f_vco / (F_REF * DIV_R_IN);
1023         div_m = f_vco % (F_REF * DIV_R_IN);
1024
1025         reg3 |= div_n << 16;
1026         reg3 |= (div_r_out / 2 - 1) << 10;
1027         reg4 = 0x0ffffful * div_m / F_REF;
1028
1029         if (reg4 >= 0x0ffffful) {
1030                 dev_dbg(&s->udev->dev,
1031                                 "%s: extending fractional part value %08x\n",
1032                                 __func__, reg4);
1033                 reg4 -= 0x0ffffful;
1034                 reg3 |= 1 << 15;
1035         }
1036
1037         reg4 = (reg4 << 8) | 0x04;
1038
1039         dev_dbg(&s->udev->dev,
1040                         "%s: f_sr=%d f_vco=%d div_n=%d div_m=%d div_r_out=%d reg4=%08x\n",
1041                         __func__, f_sr, f_vco, div_n, div_m, div_r_out, reg4);
1042
1043         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x00608008);
1044         if (ret)
1045                 goto err;
1046
1047         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x00000c05);
1048         if (ret)
1049                 goto err;
1050
1051         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x00020000);
1052         if (ret)
1053                 goto err;
1054
1055         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x00480102);
1056         if (ret)
1057                 goto err;
1058
1059         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x00f38008);
1060         if (ret)
1061                 goto err;
1062
1063         ret = msi3101_ctrl_msg(s, CMD_WREG, 0x0000a507);
1064         if (ret)
1065                 goto err;
1066
1067         ret = msi3101_ctrl_msg(s, CMD_WREG, reg4);
1068         if (ret)
1069                 goto err;
1070
1071         ret = msi3101_ctrl_msg(s, CMD_WREG, reg3);
1072         if (ret)
1073                 goto err;
1074 err:
1075         return ret;
1076 };
1077
1078 static int msi3101_set_tuner(struct msi3101_state *s)
1079 {
1080         int i, ret, len;
1081         u32 reg, synthstep, thresh, n, frac;
1082         u64 fsynth;
1083         u8 mode, lo_div;
1084         const struct msi3101_gain *gain_lut;
1085         static const struct {
1086                 u32 rf;
1087                 u8 mode;
1088                 u8 lo_div;
1089         } band_lut[] = {
1090                 { 30000000, 0x01, 16}, /* AM_MODE1 */
1091                 {108000000, 0x02, 32}, /* VHF_MODE */
1092                 {240000000, 0x04, 16}, /* B3_MODE */
1093                 {960000000, 0x08,  4}, /* B45_MODE */
1094                 {167500000, 0x10,  2}, /* BL_MODE */
1095         };
1096         static const struct {
1097                 u32 freq;
1098                 u8 val;
1099         } if_freq_lut[] = {
1100                 {      0, 0x03}, /* Zero IF */
1101                 { 450000, 0x02}, /* 450 kHz IF */
1102                 {1620000, 0x01}, /* 1.62 MHz IF */
1103                 {2048000, 0x00}, /* 2.048 MHz IF */
1104         };
1105         static const struct {
1106                 u32 freq;
1107                 u8 val;
1108         } bandwidth_lut[] = {
1109                 { 200000, 0x00}, /* 200 kHz */
1110                 { 300000, 0x01}, /* 300 kHz */
1111                 { 600000, 0x02}, /* 600 kHz */
1112                 {1536000, 0x03}, /* 1.536 MHz */
1113                 {5000000, 0x04}, /* 5 MHz */
1114                 {6000000, 0x05}, /* 6 MHz */
1115                 {7000000, 0x06}, /* 7 MHz */
1116                 {8000000, 0x07}, /* 8 MHz */
1117         };
1118
1119         unsigned int rf_freq = s->ctrl_tuner_rf->val64;
1120
1121         /*
1122          * bandwidth (Hz)
1123          * 200000, 300000, 600000, 1536000, 5000000, 6000000, 7000000, 8000000
1124          */
1125         int bandwidth = s->ctrl_tuner_bw->val;
1126
1127         /*
1128          * intermediate frequency (Hz)
1129          * 0, 450000, 1620000, 2048000
1130          */
1131         int if_freq = s->ctrl_tuner_if->val;
1132
1133         /*
1134          * gain reduction (dB)
1135          * 0 - 102 below 420 MHz
1136          * 0 - 85 above 420 MHz
1137          */
1138         int gain = s->ctrl_tuner_gain->val;
1139
1140         dev_dbg(&s->udev->dev,
1141                         "%s: rf_freq=%d bandwidth=%d if_freq=%d gain=%d\n",
1142                         __func__, rf_freq, bandwidth, if_freq, gain);
1143
1144         ret = -EINVAL;
1145
1146         for (i = 0; i < ARRAY_SIZE(band_lut); i++) {
1147                 if (rf_freq <= band_lut[i].rf) {
1148                         mode = band_lut[i].mode;
1149                         lo_div = band_lut[i].lo_div;
1150                         break;
1151                 }
1152         }
1153
1154         if (i == ARRAY_SIZE(band_lut))
1155                 goto err;
1156
1157         for (i = 0; i < ARRAY_SIZE(if_freq_lut); i++) {
1158                 if (if_freq == if_freq_lut[i].freq) {
1159                         if_freq = if_freq_lut[i].val;
1160                         break;
1161                 }
1162         }
1163
1164         if (i == ARRAY_SIZE(if_freq_lut))
1165                 goto err;
1166
1167         for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
1168                 if (bandwidth == bandwidth_lut[i].freq) {
1169                         bandwidth = bandwidth_lut[i].val;
1170                         break;
1171                 }
1172         }
1173
1174         if (i == ARRAY_SIZE(bandwidth_lut))
1175                 goto err;
1176
1177         #define FSTEP 10000
1178         #define FREF1 24000000
1179         fsynth = (rf_freq + 0) * lo_div;
1180         synthstep = FSTEP * lo_div;
1181         thresh = (FREF1 * 4) / synthstep;
1182         n = fsynth / (FREF1 * 4);
1183         frac = thresh * (fsynth % (FREF1 * 4)) / (FREF1 * 4);
1184
1185         if (thresh > 4095 || n > 63 || frac > 4095) {
1186                 dev_dbg(&s->udev->dev,
1187                                 "%s: synth setup failed rf=%d thresh=%d n=%d frac=%d\n",
1188                                 __func__, rf_freq, thresh, n, frac);
1189                 ret = -EINVAL;
1190                 goto err;
1191         }
1192
1193         ret = msi3101_tuner_write(s, 0x00000e);
1194         ret = msi3101_tuner_write(s, 0x000003);
1195
1196         reg = 0 << 0;
1197         reg |= mode << 4;
1198         reg |= 1 << 10;
1199         reg |= if_freq << 12;
1200         reg |= bandwidth << 14;
1201         reg |= 0x02 << 17;
1202         reg |= 0x00 << 20;
1203         ret = msi3101_tuner_write(s, reg);
1204         if (ret)
1205                 goto err;
1206
1207         reg = 5 << 0;
1208         reg |= thresh << 4;
1209         reg |= 1 << 19;
1210         reg |= 1 << 21;
1211         ret = msi3101_tuner_write(s, reg);
1212         if (ret)
1213                 goto err;
1214
1215         reg = 2 << 0;
1216         reg |= frac << 4;
1217         reg |= n << 16;
1218         ret = msi3101_tuner_write(s, reg);
1219         if (ret)
1220                 goto err;
1221
1222         if (rf_freq < 120000000) {
1223                 gain_lut = msi3101_gain_lut_120;
1224                 len = ARRAY_SIZE(msi3101_gain_lut_120);
1225         } else if (rf_freq < 245000000) {
1226                 gain_lut = msi3101_gain_lut_245;
1227                 len = ARRAY_SIZE(msi3101_gain_lut_120);
1228         } else {
1229                 gain_lut = msi3101_gain_lut_1000;
1230                 len = ARRAY_SIZE(msi3101_gain_lut_1000);
1231         }
1232
1233         for (i = 0; i < len; i++) {
1234                 if (gain_lut[i].tot >= gain)
1235                         break;
1236         }
1237
1238         if (i == len)
1239                 goto err;
1240
1241         dev_dbg(&s->udev->dev,
1242                         "%s: gain tot=%d baseband=%d lna=%d mixer=%d\n",
1243                         __func__, gain_lut[i].tot, gain_lut[i].baseband,
1244                         gain_lut[i].lna, gain_lut[i].mixer);
1245
1246         reg = 1 << 0;
1247         reg |= gain_lut[i].baseband << 4;
1248         reg |= 0 << 10;
1249         reg |= gain_lut[i].mixer << 12;
1250         reg |= gain_lut[i].lna << 13;
1251         reg |= 4 << 14;
1252         reg |= 0 << 17;
1253         ret = msi3101_tuner_write(s, reg);
1254         if (ret)
1255                 goto err;
1256
1257         reg = 6 << 0;
1258         reg |= 63 << 4;
1259         reg |= 4095 << 10;
1260         ret = msi3101_tuner_write(s, reg);
1261         if (ret)
1262                 goto err;
1263
1264         return 0;
1265 err:
1266         dev_dbg(&s->udev->dev, "%s: failed %d\n", __func__, ret);
1267         return ret;
1268 };
1269
1270 static int msi3101_start_streaming(struct vb2_queue *vq, unsigned int count)
1271 {
1272         struct msi3101_state *s = vb2_get_drv_priv(vq);
1273         int ret;
1274         dev_dbg(&s->udev->dev, "%s:\n", __func__);
1275
1276         if (!s->udev)
1277                 return -ENODEV;
1278
1279         if (mutex_lock_interruptible(&s->v4l2_lock))
1280                 return -ERESTARTSYS;
1281
1282         ret = msi3101_set_usb_adc(s);
1283
1284         ret = msi3101_isoc_init(s);
1285         if (ret)
1286                 msi3101_cleanup_queued_bufs(s);
1287
1288         ret = msi3101_ctrl_msg(s, CMD_START_STREAMING, 0);
1289
1290         mutex_unlock(&s->v4l2_lock);
1291
1292         return ret;
1293 }
1294
1295 static int msi3101_stop_streaming(struct vb2_queue *vq)
1296 {
1297         struct msi3101_state *s = vb2_get_drv_priv(vq);
1298         dev_dbg(&s->udev->dev, "%s:\n", __func__);
1299
1300         if (mutex_lock_interruptible(&s->v4l2_lock))
1301                 return -ERESTARTSYS;
1302
1303         if (s->udev)
1304                 msi3101_isoc_cleanup(s);
1305
1306         msi3101_cleanup_queued_bufs(s);
1307
1308         /* according to tests, at least 700us delay is required  */
1309         msleep(20);
1310         msi3101_ctrl_msg(s, CMD_STOP_STREAMING, 0);
1311
1312         mutex_unlock(&s->v4l2_lock);
1313
1314         return 0;
1315 }
1316
1317 static struct vb2_ops msi3101_vb2_ops = {
1318         .queue_setup            = msi3101_queue_setup,
1319         .buf_init               = msi3101_buf_init,
1320         .buf_prepare            = msi3101_buf_prepare,
1321         .buf_finish             = msi3101_buf_finish,
1322         .buf_cleanup            = msi3101_buf_cleanup,
1323         .buf_queue              = msi3101_buf_queue,
1324         .start_streaming        = msi3101_start_streaming,
1325         .stop_streaming         = msi3101_stop_streaming,
1326         .wait_prepare           = vb2_ops_wait_prepare,
1327         .wait_finish            = vb2_ops_wait_finish,
1328 };
1329
1330 static int msi3101_enum_input(struct file *file, void *fh, struct v4l2_input *i)
1331 {
1332         if (i->index != 0)
1333                 return -EINVAL;
1334
1335         strlcpy(i->name, "SDR data", sizeof(i->name));
1336         i->type = V4L2_INPUT_TYPE_CAMERA;
1337
1338         return 0;
1339 }
1340
1341 static int msi3101_g_input(struct file *file, void *fh, unsigned int *i)
1342 {
1343         *i = 0;
1344
1345         return 0;
1346 }
1347
1348 static int msi3101_s_input(struct file *file, void *fh, unsigned int i)
1349 {
1350         return i ? -EINVAL : 0;
1351 }
1352
1353 static int vidioc_s_tuner(struct file *file, void *priv,
1354                 const struct v4l2_tuner *v)
1355 {
1356         struct msi3101_state *s = video_drvdata(file);
1357         dev_dbg(&s->udev->dev, "%s:\n", __func__);
1358
1359         return 0;
1360 }
1361
1362 static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
1363 {
1364         struct msi3101_state *s = video_drvdata(file);
1365         dev_dbg(&s->udev->dev, "%s:\n", __func__);
1366
1367         strcpy(v->name, "SDR RX");
1368         v->capability = V4L2_TUNER_CAP_LOW;
1369
1370         return 0;
1371 }
1372
1373 static int vidioc_s_frequency(struct file *file, void *priv,
1374                 const struct v4l2_frequency *f)
1375 {
1376         struct msi3101_state *s = video_drvdata(file);
1377         dev_dbg(&s->udev->dev, "%s: frequency=%u Hz (%d)\n",
1378                         __func__, f->frequency * 625U / 10U, f->frequency);
1379
1380         return v4l2_ctrl_s_ctrl_int64(s->ctrl_tuner_rf,
1381                         f->frequency * 625U / 10U);
1382 }
1383
1384 const struct v4l2_ioctl_ops msi3101_ioctl_ops = {
1385         .vidioc_querycap          = msi3101_querycap,
1386
1387         .vidioc_enum_input        = msi3101_enum_input,
1388         .vidioc_g_input           = msi3101_g_input,
1389         .vidioc_s_input           = msi3101_s_input,
1390
1391         .vidioc_reqbufs           = vb2_ioctl_reqbufs,
1392         .vidioc_create_bufs       = vb2_ioctl_create_bufs,
1393         .vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1394         .vidioc_querybuf          = vb2_ioctl_querybuf,
1395         .vidioc_qbuf              = vb2_ioctl_qbuf,
1396         .vidioc_dqbuf             = vb2_ioctl_dqbuf,
1397
1398         .vidioc_streamon          = vb2_ioctl_streamon,
1399         .vidioc_streamoff         = vb2_ioctl_streamoff,
1400
1401         .vidioc_g_tuner           = vidioc_g_tuner,
1402         .vidioc_s_tuner           = vidioc_s_tuner,
1403         .vidioc_s_frequency       = vidioc_s_frequency,
1404
1405         .vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1406         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1407         .vidioc_log_status        = v4l2_ctrl_log_status,
1408 };
1409
1410 static const struct v4l2_file_operations msi3101_fops = {
1411         .owner                    = THIS_MODULE,
1412         .open                     = v4l2_fh_open,
1413         .release                  = vb2_fop_release,
1414         .read                     = vb2_fop_read,
1415         .poll                     = vb2_fop_poll,
1416         .mmap                     = vb2_fop_mmap,
1417         .unlocked_ioctl           = video_ioctl2,
1418 };
1419
1420 static struct video_device msi3101_template = {
1421         .name                     = "Mirics MSi3101 SDR Dongle",
1422         .release                  = video_device_release_empty,
1423         .fops                     = &msi3101_fops,
1424         .ioctl_ops                = &msi3101_ioctl_ops,
1425 };
1426
1427 static int msi3101_s_ctrl(struct v4l2_ctrl *ctrl)
1428 {
1429         struct msi3101_state *s =
1430                         container_of(ctrl->handler, struct msi3101_state,
1431                                         ctrl_handler);
1432         int ret;
1433         dev_dbg(&s->udev->dev,
1434                         "%s: id=%d name=%s val=%d min=%d max=%d step=%d\n",
1435                         __func__, ctrl->id, ctrl->name, ctrl->val,
1436                         ctrl->minimum, ctrl->maximum, ctrl->step);
1437
1438         switch (ctrl->id) {
1439         case MSI3101_CID_SAMPLING_MODE:
1440         case MSI3101_CID_SAMPLING_RATE:
1441         case MSI3101_CID_SAMPLING_RESOLUTION:
1442                 ret = 0;
1443                 break;
1444         case MSI3101_CID_TUNER_RF:
1445         case MSI3101_CID_TUNER_BW:
1446         case MSI3101_CID_TUNER_IF:
1447         case MSI3101_CID_TUNER_GAIN:
1448                 ret = msi3101_set_tuner(s);
1449                 break;
1450         default:
1451                 ret = -EINVAL;
1452         }
1453
1454         return ret;
1455 }
1456
1457 static const struct v4l2_ctrl_ops msi3101_ctrl_ops = {
1458         .s_ctrl = msi3101_s_ctrl,
1459 };
1460
1461 static void msi3101_video_release(struct v4l2_device *v)
1462 {
1463         struct msi3101_state *s =
1464                         container_of(v, struct msi3101_state, v4l2_dev);
1465
1466         v4l2_ctrl_handler_free(&s->ctrl_handler);
1467         v4l2_device_unregister(&s->v4l2_dev);
1468         kfree(s);
1469 }
1470
1471 static int msi3101_probe(struct usb_interface *intf,
1472                 const struct usb_device_id *id)
1473 {
1474         struct usb_device *udev = interface_to_usbdev(intf);
1475         struct msi3101_state *s = NULL;
1476         int ret;
1477         static const char * const ctrl_sampling_mode_qmenu_strings[] = {
1478                 "Quadrature Sampling",
1479                 NULL,
1480         };
1481         static const struct v4l2_ctrl_config ctrl_sampling_mode = {
1482                 .ops    = &msi3101_ctrl_ops,
1483                 .id     = MSI3101_CID_SAMPLING_MODE,
1484                 .type   = V4L2_CTRL_TYPE_MENU,
1485                 .flags  = V4L2_CTRL_FLAG_INACTIVE,
1486                 .name   = "Sampling Mode",
1487                 .qmenu  = ctrl_sampling_mode_qmenu_strings,
1488         };
1489         static const struct v4l2_ctrl_config ctrl_sampling_rate = {
1490                 .ops    = &msi3101_ctrl_ops,
1491                 .id     = MSI3101_CID_SAMPLING_RATE,
1492                 .type   = V4L2_CTRL_TYPE_INTEGER64,
1493                 .name   = "Sampling Rate",
1494                 .min    = 500000,
1495                 .max    = 12000000,
1496                 .def    = 2048000,
1497                 .step   = 1,
1498         };
1499         static const struct v4l2_ctrl_config ctrl_sampling_resolution = {
1500                 .ops    = &msi3101_ctrl_ops,
1501                 .id     = MSI3101_CID_SAMPLING_RESOLUTION,
1502                 .type   = V4L2_CTRL_TYPE_INTEGER,
1503                 .flags  = V4L2_CTRL_FLAG_INACTIVE,
1504                 .name   = "Sampling Resolution",
1505                 .min    = 10,
1506                 .max    = 10,
1507                 .def    = 10,
1508                 .step   = 1,
1509         };
1510         static const struct v4l2_ctrl_config ctrl_tuner_rf = {
1511                 .ops    = &msi3101_ctrl_ops,
1512                 .id     = MSI3101_CID_TUNER_RF,
1513                 .type   = V4L2_CTRL_TYPE_INTEGER64,
1514                 .name   = "Tuner RF",
1515                 .min    = 40000000,
1516                 .max    = 2000000000,
1517                 .def    = 100000000,
1518                 .step   = 1,
1519         };
1520         static const struct v4l2_ctrl_config ctrl_tuner_bw = {
1521                 .ops    = &msi3101_ctrl_ops,
1522                 .id     = MSI3101_CID_TUNER_BW,
1523                 .type   = V4L2_CTRL_TYPE_INTEGER,
1524                 .name   = "Tuner BW",
1525                 .min    = 200000,
1526                 .max    = 8000000,
1527                 .def    = 600000,
1528                 .step   = 1,
1529         };
1530         static const struct v4l2_ctrl_config ctrl_tuner_if = {
1531                 .ops    = &msi3101_ctrl_ops,
1532                 .id     = MSI3101_CID_TUNER_IF,
1533                 .type   = V4L2_CTRL_TYPE_INTEGER,
1534                 .flags  = V4L2_CTRL_FLAG_INACTIVE,
1535                 .name   = "Tuner IF",
1536                 .min    = 0,
1537                 .max    = 2048000,
1538                 .def    = 0,
1539                 .step   = 1,
1540         };
1541         static const struct v4l2_ctrl_config ctrl_tuner_gain = {
1542                 .ops    = &msi3101_ctrl_ops,
1543                 .id     = MSI3101_CID_TUNER_GAIN,
1544                 .type   = V4L2_CTRL_TYPE_INTEGER,
1545                 .name   = "Tuner Gain",
1546                 .min    = 0,
1547                 .max    = 102,
1548                 .def    = 0,
1549                 .step   = 1,
1550         };
1551
1552         s = kzalloc(sizeof(struct msi3101_state), GFP_KERNEL);
1553         if (s == NULL) {
1554                 pr_err("Could not allocate memory for msi3101_state\n");
1555                 return -ENOMEM;
1556         }
1557
1558         mutex_init(&s->v4l2_lock);
1559         mutex_init(&s->vb_queue_lock);
1560         spin_lock_init(&s->queued_bufs_lock);
1561         INIT_LIST_HEAD(&s->queued_bufs);
1562
1563         s->udev = udev;
1564
1565         /* Init videobuf2 queue structure */
1566         s->vb_queue.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1567         s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1568         s->vb_queue.drv_priv = s;
1569         s->vb_queue.buf_struct_size = sizeof(struct msi3101_frame_buf);
1570         s->vb_queue.ops = &msi3101_vb2_ops;
1571         s->vb_queue.mem_ops = &vb2_vmalloc_memops;
1572         s->vb_queue.timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1573         ret = vb2_queue_init(&s->vb_queue);
1574         if (ret < 0) {
1575                 dev_err(&s->udev->dev, "Could not initialize vb2 queue\n");
1576                 goto err_free_mem;
1577         }
1578
1579         /* Init video_device structure */
1580         s->vdev = msi3101_template;
1581         s->vdev.queue = &s->vb_queue;
1582         s->vdev.queue->lock = &s->vb_queue_lock;
1583         set_bit(V4L2_FL_USE_FH_PRIO, &s->vdev.flags);
1584         video_set_drvdata(&s->vdev, s);
1585
1586         /* Register controls */
1587         v4l2_ctrl_handler_init(&s->ctrl_handler, 7);
1588         v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_sampling_mode, NULL);
1589         s->ctrl_sampling_rate = v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_sampling_rate, NULL);
1590         v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_sampling_resolution, NULL);
1591         s->ctrl_tuner_rf = v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_tuner_rf, NULL);
1592         s->ctrl_tuner_bw = v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_tuner_bw, NULL);
1593         s->ctrl_tuner_if = v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_tuner_if, NULL);
1594         s->ctrl_tuner_gain = v4l2_ctrl_new_custom(&s->ctrl_handler, &ctrl_tuner_gain, NULL);
1595         if (s->ctrl_handler.error) {
1596                 ret = s->ctrl_handler.error;
1597                 dev_err(&s->udev->dev, "Could not initialize controls\n");
1598                 goto err_free_controls;
1599         }
1600
1601         /* Register the v4l2_device structure */
1602         s->v4l2_dev.release = msi3101_video_release;
1603         ret = v4l2_device_register(&intf->dev, &s->v4l2_dev);
1604         if (ret) {
1605                 dev_err(&s->udev->dev,
1606                                 "Failed to register v4l2-device (%d)\n", ret);
1607                 goto err_free_controls;
1608         }
1609
1610         s->v4l2_dev.ctrl_handler = &s->ctrl_handler;
1611         s->vdev.v4l2_dev = &s->v4l2_dev;
1612         s->vdev.lock = &s->v4l2_lock;
1613
1614         ret = video_register_device(&s->vdev, VFL_TYPE_GRABBER, -1);
1615         if (ret < 0) {
1616                 dev_err(&s->udev->dev,
1617                                 "Failed to register as video device (%d)\n",
1618                                 ret);
1619                 goto err_unregister_v4l2_dev;
1620         }
1621         dev_info(&s->udev->dev, "Registered as %s\n",
1622                         video_device_node_name(&s->vdev));
1623
1624         return 0;
1625
1626 err_unregister_v4l2_dev:
1627         v4l2_device_unregister(&s->v4l2_dev);
1628 err_free_controls:
1629         v4l2_ctrl_handler_free(&s->ctrl_handler);
1630 err_free_mem:
1631         kfree(s);
1632         return ret;
1633 }
1634
1635 /* USB device ID list */
1636 static struct usb_device_id msi3101_id_table[] = {
1637         { USB_DEVICE(0x1df7, 0x2500) },
1638         { USB_DEVICE(0x2040, 0xd300) }, /* Hauppauge WinTV 133559 LF */
1639         { }
1640 };
1641 MODULE_DEVICE_TABLE(usb, msi3101_id_table);
1642
1643 /* USB subsystem interface */
1644 static struct usb_driver msi3101_driver = {
1645         .name                     = KBUILD_MODNAME,
1646         .probe                    = msi3101_probe,
1647         .disconnect               = msi3101_disconnect,
1648         .id_table                 = msi3101_id_table,
1649 };
1650
1651 module_usb_driver(msi3101_driver);
1652
1653 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1654 MODULE_DESCRIPTION("Mirics MSi3101 SDR Dongle");
1655 MODULE_LICENSE("GPL");