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