Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / drivers / media / usb / airspy / airspy.c
1 /*
2  * AirSpy SDR driver
3  *
4  * Copyright (C) 2014 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
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/usb.h>
20 #include <media/v4l2-device.h>
21 #include <media/v4l2-ioctl.h>
22 #include <media/v4l2-ctrls.h>
23 #include <media/v4l2-event.h>
24 #include <media/videobuf2-vmalloc.h>
25
26 /* AirSpy USB API commands (from AirSpy Library) */
27 enum {
28         CMD_INVALID                       = 0x00,
29         CMD_RECEIVER_MODE                 = 0x01,
30         CMD_SI5351C_WRITE                 = 0x02,
31         CMD_SI5351C_READ                  = 0x03,
32         CMD_R820T_WRITE                   = 0x04,
33         CMD_R820T_READ                    = 0x05,
34         CMD_SPIFLASH_ERASE                = 0x06,
35         CMD_SPIFLASH_WRITE                = 0x07,
36         CMD_SPIFLASH_READ                 = 0x08,
37         CMD_BOARD_ID_READ                 = 0x09,
38         CMD_VERSION_STRING_READ           = 0x0a,
39         CMD_BOARD_PARTID_SERIALNO_READ    = 0x0b,
40         CMD_SET_SAMPLE_RATE               = 0x0c,
41         CMD_SET_FREQ                      = 0x0d,
42         CMD_SET_LNA_GAIN                  = 0x0e,
43         CMD_SET_MIXER_GAIN                = 0x0f,
44         CMD_SET_VGA_GAIN                  = 0x10,
45         CMD_SET_LNA_AGC                   = 0x11,
46         CMD_SET_MIXER_AGC                 = 0x12,
47         CMD_SET_PACKING                   = 0x13,
48 };
49
50 /*
51  *       bEndpointAddress     0x81  EP 1 IN
52  *         Transfer Type            Bulk
53  *       wMaxPacketSize     0x0200  1x 512 bytes
54  */
55 #define MAX_BULK_BUFS            (6)
56 #define BULK_BUFFER_SIZE         (128 * 512)
57
58 static const struct v4l2_frequency_band bands[] = {
59         {
60                 .tuner = 0,
61                 .type = V4L2_TUNER_ADC,
62                 .index = 0,
63                 .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
64                 .rangelow   = 20000000,
65                 .rangehigh  = 20000000,
66         },
67 };
68
69 static const struct v4l2_frequency_band bands_rf[] = {
70         {
71                 .tuner = 1,
72                 .type = V4L2_TUNER_RF,
73                 .index = 0,
74                 .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
75                 .rangelow   =   24000000,
76                 .rangehigh  = 1750000000,
77         },
78 };
79
80 /* stream formats */
81 struct airspy_format {
82         char    *name;
83         u32     pixelformat;
84         u32     buffersize;
85 };
86
87 /* format descriptions for capture and preview */
88 static struct airspy_format formats[] = {
89         {
90                 .name           = "Real U12LE",
91                 .pixelformat    = V4L2_SDR_FMT_RU12LE,
92                 .buffersize     = BULK_BUFFER_SIZE,
93         },
94 };
95
96 static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
97
98 /* intermediate buffers with raw data from the USB device */
99 struct airspy_frame_buf {
100         struct vb2_buffer vb;   /* common v4l buffer stuff -- must be first */
101         struct list_head list;
102 };
103
104 struct airspy {
105 #define POWER_ON           (1 << 1)
106 #define URB_BUF            (1 << 2)
107 #define USB_STATE_URB_BUF  (1 << 3)
108         unsigned long flags;
109
110         struct device *dev;
111         struct usb_device *udev;
112         struct video_device vdev;
113         struct v4l2_device v4l2_dev;
114
115         /* videobuf2 queue and queued buffers list */
116         struct vb2_queue vb_queue;
117         struct list_head queued_bufs;
118         spinlock_t queued_bufs_lock; /* Protects queued_bufs */
119         unsigned sequence;           /* Buffer sequence counter */
120         unsigned int vb_full;        /* vb is full and packets dropped */
121
122         /* Note if taking both locks v4l2_lock must always be locked first! */
123         struct mutex v4l2_lock;      /* Protects everything else */
124         struct mutex vb_queue_lock;  /* Protects vb_queue and capt_file */
125
126         struct urb     *urb_list[MAX_BULK_BUFS];
127         int            buf_num;
128         unsigned long  buf_size;
129         u8             *buf_list[MAX_BULK_BUFS];
130         dma_addr_t     dma_addr[MAX_BULK_BUFS];
131         int            urbs_initialized;
132         int            urbs_submitted;
133
134         /* USB control message buffer */
135         #define BUF_SIZE 24
136         u8 buf[BUF_SIZE];
137
138         /* Current configuration */
139         unsigned int f_adc;
140         unsigned int f_rf;
141         u32 pixelformat;
142         u32 buffersize;
143
144         /* Controls */
145         struct v4l2_ctrl_handler hdl;
146         struct v4l2_ctrl *lna_gain_auto;
147         struct v4l2_ctrl *lna_gain;
148         struct v4l2_ctrl *mixer_gain_auto;
149         struct v4l2_ctrl *mixer_gain;
150         struct v4l2_ctrl *if_gain;
151
152         /* Sample rate calc */
153         unsigned long jiffies_next;
154         unsigned int sample;
155         unsigned int sample_measured;
156 };
157
158 #define airspy_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
159         char *_direction; \
160         if (_t & USB_DIR_IN) \
161                 _direction = "<<<"; \
162         else \
163                 _direction = ">>>"; \
164         dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
165                         _t, _r, _v & 0xff, _v >> 8, _i & 0xff, _i >> 8, \
166                         _l & 0xff, _l >> 8, _direction, _l, _b); \
167 }
168
169 /* execute firmware command */
170 static int airspy_ctrl_msg(struct airspy *s, u8 request, u16 value, u16 index,
171                 u8 *data, u16 size)
172 {
173         int ret;
174         unsigned int pipe;
175         u8 requesttype;
176
177         switch (request) {
178         case CMD_RECEIVER_MODE:
179         case CMD_SET_FREQ:
180                 pipe = usb_sndctrlpipe(s->udev, 0);
181                 requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
182                 break;
183         case CMD_BOARD_ID_READ:
184         case CMD_VERSION_STRING_READ:
185         case CMD_BOARD_PARTID_SERIALNO_READ:
186         case CMD_SET_LNA_GAIN:
187         case CMD_SET_MIXER_GAIN:
188         case CMD_SET_VGA_GAIN:
189         case CMD_SET_LNA_AGC:
190         case CMD_SET_MIXER_AGC:
191                 pipe = usb_rcvctrlpipe(s->udev, 0);
192                 requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
193                 break;
194         default:
195                 dev_err(s->dev, "Unknown command %02x\n", request);
196                 ret = -EINVAL;
197                 goto err;
198         }
199
200         /* write request */
201         if (!(requesttype & USB_DIR_IN))
202                 memcpy(s->buf, data, size);
203
204         ret = usb_control_msg(s->udev, pipe, request, requesttype, value,
205                         index, s->buf, size, 1000);
206         airspy_dbg_usb_control_msg(s->dev, request, requesttype, value,
207                         index, s->buf, size);
208         if (ret < 0) {
209                 dev_err(s->dev, "usb_control_msg() failed %d request %02x\n",
210                                 ret, request);
211                 goto err;
212         }
213
214         /* read request */
215         if (requesttype & USB_DIR_IN)
216                 memcpy(data, s->buf, size);
217
218         return 0;
219 err:
220         return ret;
221 }
222
223 /* Private functions */
224 static struct airspy_frame_buf *airspy_get_next_fill_buf(struct airspy *s)
225 {
226         unsigned long flags;
227         struct airspy_frame_buf *buf = NULL;
228
229         spin_lock_irqsave(&s->queued_bufs_lock, flags);
230         if (list_empty(&s->queued_bufs))
231                 goto leave;
232
233         buf = list_entry(s->queued_bufs.next,
234                         struct airspy_frame_buf, list);
235         list_del(&buf->list);
236 leave:
237         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
238         return buf;
239 }
240
241 static unsigned int airspy_convert_stream(struct airspy *s,
242                 void *dst, void *src, unsigned int src_len)
243 {
244         unsigned int dst_len;
245
246         if (s->pixelformat == V4L2_SDR_FMT_RU12LE) {
247                 memcpy(dst, src, src_len);
248                 dst_len = src_len;
249         } else {
250                 dst_len = 0;
251         }
252
253         /* calculate sample rate and output it in 10 seconds intervals */
254         if (unlikely(time_is_before_jiffies(s->jiffies_next))) {
255                 #define MSECS 10000UL
256                 unsigned int msecs = jiffies_to_msecs(jiffies -
257                                 s->jiffies_next + msecs_to_jiffies(MSECS));
258                 unsigned int samples = s->sample - s->sample_measured;
259
260                 s->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
261                 s->sample_measured = s->sample;
262                 dev_dbg(s->dev, "slen=%u samples=%u msecs=%u sample rate=%lu\n",
263                                 src_len, samples, msecs,
264                                 samples * 1000UL / msecs);
265         }
266
267         /* total number of samples */
268         s->sample += src_len / 2;
269
270         return dst_len;
271 }
272
273 /*
274  * This gets called for the bulk stream pipe. This is done in interrupt
275  * time, so it has to be fast, not crash, and not stall. Neat.
276  */
277 static void airspy_urb_complete(struct urb *urb)
278 {
279         struct airspy *s = urb->context;
280         struct airspy_frame_buf *fbuf;
281
282         dev_dbg_ratelimited(s->dev, "status=%d length=%d/%d errors=%d\n",
283                         urb->status, urb->actual_length,
284                         urb->transfer_buffer_length, urb->error_count);
285
286         switch (urb->status) {
287         case 0:             /* success */
288         case -ETIMEDOUT:    /* NAK */
289                 break;
290         case -ECONNRESET:   /* kill */
291         case -ENOENT:
292         case -ESHUTDOWN:
293                 return;
294         default:            /* error */
295                 dev_err_ratelimited(s->dev, "URB failed %d\n", urb->status);
296                 break;
297         }
298
299         if (likely(urb->actual_length > 0)) {
300                 void *ptr;
301                 unsigned int len;
302                 /* get free framebuffer */
303                 fbuf = airspy_get_next_fill_buf(s);
304                 if (unlikely(fbuf == NULL)) {
305                         s->vb_full++;
306                         dev_notice_ratelimited(s->dev,
307                                         "videobuf is full, %d packets dropped\n",
308                                         s->vb_full);
309                         goto skip;
310                 }
311
312                 /* fill framebuffer */
313                 ptr = vb2_plane_vaddr(&fbuf->vb, 0);
314                 len = airspy_convert_stream(s, ptr, urb->transfer_buffer,
315                                 urb->actual_length);
316                 vb2_set_plane_payload(&fbuf->vb, 0, len);
317                 v4l2_get_timestamp(&fbuf->vb.v4l2_buf.timestamp);
318                 fbuf->vb.v4l2_buf.sequence = s->sequence++;
319                 vb2_buffer_done(&fbuf->vb, VB2_BUF_STATE_DONE);
320         }
321 skip:
322         usb_submit_urb(urb, GFP_ATOMIC);
323 }
324
325 static int airspy_kill_urbs(struct airspy *s)
326 {
327         int i;
328
329         for (i = s->urbs_submitted - 1; i >= 0; i--) {
330                 dev_dbg(s->dev, "kill urb=%d\n", i);
331                 /* stop the URB */
332                 usb_kill_urb(s->urb_list[i]);
333         }
334         s->urbs_submitted = 0;
335
336         return 0;
337 }
338
339 static int airspy_submit_urbs(struct airspy *s)
340 {
341         int i, ret;
342
343         for (i = 0; i < s->urbs_initialized; i++) {
344                 dev_dbg(s->dev, "submit urb=%d\n", i);
345                 ret = usb_submit_urb(s->urb_list[i], GFP_ATOMIC);
346                 if (ret) {
347                         dev_err(s->dev, "Could not submit URB no. %d - get them all back\n",
348                                         i);
349                         airspy_kill_urbs(s);
350                         return ret;
351                 }
352                 s->urbs_submitted++;
353         }
354
355         return 0;
356 }
357
358 static int airspy_free_stream_bufs(struct airspy *s)
359 {
360         if (s->flags & USB_STATE_URB_BUF) {
361                 while (s->buf_num) {
362                         s->buf_num--;
363                         dev_dbg(s->dev, "free buf=%d\n", s->buf_num);
364                         usb_free_coherent(s->udev, s->buf_size,
365                                           s->buf_list[s->buf_num],
366                                           s->dma_addr[s->buf_num]);
367                 }
368         }
369         s->flags &= ~USB_STATE_URB_BUF;
370
371         return 0;
372 }
373
374 static int airspy_alloc_stream_bufs(struct airspy *s)
375 {
376         s->buf_num = 0;
377         s->buf_size = BULK_BUFFER_SIZE;
378
379         dev_dbg(s->dev, "all in all I will use %u bytes for streaming\n",
380                         MAX_BULK_BUFS * BULK_BUFFER_SIZE);
381
382         for (s->buf_num = 0; s->buf_num < MAX_BULK_BUFS; s->buf_num++) {
383                 s->buf_list[s->buf_num] = usb_alloc_coherent(s->udev,
384                                 BULK_BUFFER_SIZE, GFP_ATOMIC,
385                                 &s->dma_addr[s->buf_num]);
386                 if (!s->buf_list[s->buf_num]) {
387                         dev_dbg(s->dev, "alloc buf=%d failed\n", s->buf_num);
388                         airspy_free_stream_bufs(s);
389                         return -ENOMEM;
390                 }
391
392                 dev_dbg(s->dev, "alloc buf=%d %p (dma %llu)\n", s->buf_num,
393                                 s->buf_list[s->buf_num],
394                                 (long long)s->dma_addr[s->buf_num]);
395                 s->flags |= USB_STATE_URB_BUF;
396         }
397
398         return 0;
399 }
400
401 static int airspy_free_urbs(struct airspy *s)
402 {
403         int i;
404
405         airspy_kill_urbs(s);
406
407         for (i = s->urbs_initialized - 1; i >= 0; i--) {
408                 if (s->urb_list[i]) {
409                         dev_dbg(s->dev, "free urb=%d\n", i);
410                         /* free the URBs */
411                         usb_free_urb(s->urb_list[i]);
412                 }
413         }
414         s->urbs_initialized = 0;
415
416         return 0;
417 }
418
419 static int airspy_alloc_urbs(struct airspy *s)
420 {
421         int i, j;
422
423         /* allocate the URBs */
424         for (i = 0; i < MAX_BULK_BUFS; i++) {
425                 dev_dbg(s->dev, "alloc urb=%d\n", i);
426                 s->urb_list[i] = usb_alloc_urb(0, GFP_ATOMIC);
427                 if (!s->urb_list[i]) {
428                         dev_dbg(s->dev, "failed\n");
429                         for (j = 0; j < i; j++)
430                                 usb_free_urb(s->urb_list[j]);
431                         return -ENOMEM;
432                 }
433                 usb_fill_bulk_urb(s->urb_list[i],
434                                 s->udev,
435                                 usb_rcvbulkpipe(s->udev, 0x81),
436                                 s->buf_list[i],
437                                 BULK_BUFFER_SIZE,
438                                 airspy_urb_complete, s);
439
440                 s->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
441                 s->urb_list[i]->transfer_dma = s->dma_addr[i];
442                 s->urbs_initialized++;
443         }
444
445         return 0;
446 }
447
448 /* Must be called with vb_queue_lock hold */
449 static void airspy_cleanup_queued_bufs(struct airspy *s)
450 {
451         unsigned long flags;
452
453         dev_dbg(s->dev, "\n");
454
455         spin_lock_irqsave(&s->queued_bufs_lock, flags);
456         while (!list_empty(&s->queued_bufs)) {
457                 struct airspy_frame_buf *buf;
458
459                 buf = list_entry(s->queued_bufs.next,
460                                 struct airspy_frame_buf, list);
461                 list_del(&buf->list);
462                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
463         }
464         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
465 }
466
467 /* The user yanked out the cable... */
468 static void airspy_disconnect(struct usb_interface *intf)
469 {
470         struct v4l2_device *v = usb_get_intfdata(intf);
471         struct airspy *s = container_of(v, struct airspy, v4l2_dev);
472
473         dev_dbg(s->dev, "\n");
474
475         mutex_lock(&s->vb_queue_lock);
476         mutex_lock(&s->v4l2_lock);
477         /* No need to keep the urbs around after disconnection */
478         s->udev = NULL;
479         v4l2_device_disconnect(&s->v4l2_dev);
480         video_unregister_device(&s->vdev);
481         mutex_unlock(&s->v4l2_lock);
482         mutex_unlock(&s->vb_queue_lock);
483
484         v4l2_device_put(&s->v4l2_dev);
485 }
486
487 /* Videobuf2 operations */
488 static int airspy_queue_setup(struct vb2_queue *vq,
489                 const struct v4l2_format *fmt, unsigned int *nbuffers,
490                 unsigned int *nplanes, unsigned int sizes[], void *alloc_ctxs[])
491 {
492         struct airspy *s = vb2_get_drv_priv(vq);
493
494         dev_dbg(s->dev, "nbuffers=%d\n", *nbuffers);
495
496         /* Need at least 8 buffers */
497         if (vq->num_buffers + *nbuffers < 8)
498                 *nbuffers = 8 - vq->num_buffers;
499         *nplanes = 1;
500         sizes[0] = PAGE_ALIGN(s->buffersize);
501
502         dev_dbg(s->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
503         return 0;
504 }
505
506 static void airspy_buf_queue(struct vb2_buffer *vb)
507 {
508         struct airspy *s = vb2_get_drv_priv(vb->vb2_queue);
509         struct airspy_frame_buf *buf =
510                         container_of(vb, struct airspy_frame_buf, vb);
511         unsigned long flags;
512
513         /* Check the device has not disconnected between prep and queuing */
514         if (unlikely(!s->udev)) {
515                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
516                 return;
517         }
518
519         spin_lock_irqsave(&s->queued_bufs_lock, flags);
520         list_add_tail(&buf->list, &s->queued_bufs);
521         spin_unlock_irqrestore(&s->queued_bufs_lock, flags);
522 }
523
524 static int airspy_start_streaming(struct vb2_queue *vq, unsigned int count)
525 {
526         struct airspy *s = vb2_get_drv_priv(vq);
527         int ret;
528
529         dev_dbg(s->dev, "\n");
530
531         if (!s->udev)
532                 return -ENODEV;
533
534         mutex_lock(&s->v4l2_lock);
535
536         s->sequence = 0;
537
538         set_bit(POWER_ON, &s->flags);
539
540         ret = airspy_alloc_stream_bufs(s);
541         if (ret)
542                 goto err_clear_bit;
543
544         ret = airspy_alloc_urbs(s);
545         if (ret)
546                 goto err_free_stream_bufs;
547
548         ret = airspy_submit_urbs(s);
549         if (ret)
550                 goto err_free_urbs;
551
552         /* start hardware streaming */
553         ret = airspy_ctrl_msg(s, CMD_RECEIVER_MODE, 1, 0, NULL, 0);
554         if (ret)
555                 goto err_kill_urbs;
556
557         goto exit_mutex_unlock;
558
559 err_kill_urbs:
560         airspy_kill_urbs(s);
561 err_free_urbs:
562         airspy_free_urbs(s);
563 err_free_stream_bufs:
564         airspy_free_stream_bufs(s);
565 err_clear_bit:
566         clear_bit(POWER_ON, &s->flags);
567
568         /* return all queued buffers to vb2 */
569         {
570                 struct airspy_frame_buf *buf, *tmp;
571
572                 list_for_each_entry_safe(buf, tmp, &s->queued_bufs, list) {
573                         list_del(&buf->list);
574                         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_QUEUED);
575                 }
576         }
577
578 exit_mutex_unlock:
579         mutex_unlock(&s->v4l2_lock);
580
581         return ret;
582 }
583
584 static void airspy_stop_streaming(struct vb2_queue *vq)
585 {
586         struct airspy *s = vb2_get_drv_priv(vq);
587
588         dev_dbg(s->dev, "\n");
589
590         mutex_lock(&s->v4l2_lock);
591
592         /* stop hardware streaming */
593         airspy_ctrl_msg(s, CMD_RECEIVER_MODE, 0, 0, NULL, 0);
594
595         airspy_kill_urbs(s);
596         airspy_free_urbs(s);
597         airspy_free_stream_bufs(s);
598
599         airspy_cleanup_queued_bufs(s);
600
601         clear_bit(POWER_ON, &s->flags);
602
603         mutex_unlock(&s->v4l2_lock);
604 }
605
606 static struct vb2_ops airspy_vb2_ops = {
607         .queue_setup            = airspy_queue_setup,
608         .buf_queue              = airspy_buf_queue,
609         .start_streaming        = airspy_start_streaming,
610         .stop_streaming         = airspy_stop_streaming,
611         .wait_prepare           = vb2_ops_wait_prepare,
612         .wait_finish            = vb2_ops_wait_finish,
613 };
614
615 static int airspy_querycap(struct file *file, void *fh,
616                 struct v4l2_capability *cap)
617 {
618         struct airspy *s = video_drvdata(file);
619
620         strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
621         strlcpy(cap->card, s->vdev.name, sizeof(cap->card));
622         usb_make_path(s->udev, cap->bus_info, sizeof(cap->bus_info));
623         cap->device_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_STREAMING |
624                         V4L2_CAP_READWRITE | V4L2_CAP_TUNER;
625         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
626
627         return 0;
628 }
629
630 static int airspy_enum_fmt_sdr_cap(struct file *file, void *priv,
631                 struct v4l2_fmtdesc *f)
632 {
633         if (f->index >= NUM_FORMATS)
634                 return -EINVAL;
635
636         strlcpy(f->description, formats[f->index].name, sizeof(f->description));
637         f->pixelformat = formats[f->index].pixelformat;
638
639         return 0;
640 }
641
642 static int airspy_g_fmt_sdr_cap(struct file *file, void *priv,
643                 struct v4l2_format *f)
644 {
645         struct airspy *s = video_drvdata(file);
646
647         f->fmt.sdr.pixelformat = s->pixelformat;
648         f->fmt.sdr.buffersize = s->buffersize;
649         memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
650
651         return 0;
652 }
653
654 static int airspy_s_fmt_sdr_cap(struct file *file, void *priv,
655                 struct v4l2_format *f)
656 {
657         struct airspy *s = video_drvdata(file);
658         struct vb2_queue *q = &s->vb_queue;
659         int i;
660
661         if (vb2_is_busy(q))
662                 return -EBUSY;
663
664         memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
665         for (i = 0; i < NUM_FORMATS; i++) {
666                 if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
667                         s->pixelformat = formats[i].pixelformat;
668                         s->buffersize = formats[i].buffersize;
669                         f->fmt.sdr.buffersize = formats[i].buffersize;
670                         return 0;
671                 }
672         }
673
674         s->pixelformat = formats[0].pixelformat;
675         s->buffersize = formats[0].buffersize;
676         f->fmt.sdr.pixelformat = formats[0].pixelformat;
677         f->fmt.sdr.buffersize = formats[0].buffersize;
678
679         return 0;
680 }
681
682 static int airspy_try_fmt_sdr_cap(struct file *file, void *priv,
683                 struct v4l2_format *f)
684 {
685         int i;
686
687         memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
688         for (i = 0; i < NUM_FORMATS; i++) {
689                 if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
690                         f->fmt.sdr.buffersize = formats[i].buffersize;
691                         return 0;
692                 }
693         }
694
695         f->fmt.sdr.pixelformat = formats[0].pixelformat;
696         f->fmt.sdr.buffersize = formats[0].buffersize;
697
698         return 0;
699 }
700
701 static int airspy_s_tuner(struct file *file, void *priv,
702                 const struct v4l2_tuner *v)
703 {
704         int ret;
705
706         if (v->index == 0)
707                 ret = 0;
708         else if (v->index == 1)
709                 ret = 0;
710         else
711                 ret = -EINVAL;
712
713         return ret;
714 }
715
716 static int airspy_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
717 {
718         int ret;
719
720         if (v->index == 0) {
721                 strlcpy(v->name, "AirSpy ADC", sizeof(v->name));
722                 v->type = V4L2_TUNER_ADC;
723                 v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
724                 v->rangelow  = bands[0].rangelow;
725                 v->rangehigh = bands[0].rangehigh;
726                 ret = 0;
727         } else if (v->index == 1) {
728                 strlcpy(v->name, "AirSpy RF", sizeof(v->name));
729                 v->type = V4L2_TUNER_RF;
730                 v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
731                 v->rangelow  = bands_rf[0].rangelow;
732                 v->rangehigh = bands_rf[0].rangehigh;
733                 ret = 0;
734         } else {
735                 ret = -EINVAL;
736         }
737
738         return ret;
739 }
740
741 static int airspy_g_frequency(struct file *file, void *priv,
742                 struct v4l2_frequency *f)
743 {
744         struct airspy *s = video_drvdata(file);
745         int ret;
746
747         if (f->tuner == 0) {
748                 f->type = V4L2_TUNER_ADC;
749                 f->frequency = s->f_adc;
750                 dev_dbg(s->dev, "ADC frequency=%u Hz\n", s->f_adc);
751                 ret = 0;
752         } else if (f->tuner == 1) {
753                 f->type = V4L2_TUNER_RF;
754                 f->frequency = s->f_rf;
755                 dev_dbg(s->dev, "RF frequency=%u Hz\n", s->f_rf);
756                 ret = 0;
757         } else {
758                 ret = -EINVAL;
759         }
760
761         return ret;
762 }
763
764 static int airspy_s_frequency(struct file *file, void *priv,
765                 const struct v4l2_frequency *f)
766 {
767         struct airspy *s = video_drvdata(file);
768         int ret;
769         u8 buf[4];
770
771         if (f->tuner == 0) {
772                 s->f_adc = clamp_t(unsigned int, f->frequency,
773                                 bands[0].rangelow,
774                                 bands[0].rangehigh);
775                 dev_dbg(s->dev, "ADC frequency=%u Hz\n", s->f_adc);
776                 ret = 0;
777         } else if (f->tuner == 1) {
778                 s->f_rf = clamp_t(unsigned int, f->frequency,
779                                 bands_rf[0].rangelow,
780                                 bands_rf[0].rangehigh);
781                 dev_dbg(s->dev, "RF frequency=%u Hz\n", s->f_rf);
782                 buf[0] = (s->f_rf >>  0) & 0xff;
783                 buf[1] = (s->f_rf >>  8) & 0xff;
784                 buf[2] = (s->f_rf >> 16) & 0xff;
785                 buf[3] = (s->f_rf >> 24) & 0xff;
786                 ret = airspy_ctrl_msg(s, CMD_SET_FREQ, 0, 0, buf, 4);
787         } else {
788                 ret = -EINVAL;
789         }
790
791         return ret;
792 }
793
794 static int airspy_enum_freq_bands(struct file *file, void *priv,
795                 struct v4l2_frequency_band *band)
796 {
797         int ret;
798
799         if (band->tuner == 0) {
800                 if (band->index >= ARRAY_SIZE(bands)) {
801                         ret = -EINVAL;
802                 } else {
803                         *band = bands[band->index];
804                         ret = 0;
805                 }
806         } else if (band->tuner == 1) {
807                 if (band->index >= ARRAY_SIZE(bands_rf)) {
808                         ret = -EINVAL;
809                 } else {
810                         *band = bands_rf[band->index];
811                         ret = 0;
812                 }
813         } else {
814                 ret = -EINVAL;
815         }
816
817         return ret;
818 }
819
820 static const struct v4l2_ioctl_ops airspy_ioctl_ops = {
821         .vidioc_querycap          = airspy_querycap,
822
823         .vidioc_enum_fmt_sdr_cap  = airspy_enum_fmt_sdr_cap,
824         .vidioc_g_fmt_sdr_cap     = airspy_g_fmt_sdr_cap,
825         .vidioc_s_fmt_sdr_cap     = airspy_s_fmt_sdr_cap,
826         .vidioc_try_fmt_sdr_cap   = airspy_try_fmt_sdr_cap,
827
828         .vidioc_reqbufs           = vb2_ioctl_reqbufs,
829         .vidioc_create_bufs       = vb2_ioctl_create_bufs,
830         .vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
831         .vidioc_querybuf          = vb2_ioctl_querybuf,
832         .vidioc_qbuf              = vb2_ioctl_qbuf,
833         .vidioc_dqbuf             = vb2_ioctl_dqbuf,
834
835         .vidioc_streamon          = vb2_ioctl_streamon,
836         .vidioc_streamoff         = vb2_ioctl_streamoff,
837
838         .vidioc_g_tuner           = airspy_g_tuner,
839         .vidioc_s_tuner           = airspy_s_tuner,
840
841         .vidioc_g_frequency       = airspy_g_frequency,
842         .vidioc_s_frequency       = airspy_s_frequency,
843         .vidioc_enum_freq_bands   = airspy_enum_freq_bands,
844
845         .vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
846         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
847         .vidioc_log_status        = v4l2_ctrl_log_status,
848 };
849
850 static const struct v4l2_file_operations airspy_fops = {
851         .owner                    = THIS_MODULE,
852         .open                     = v4l2_fh_open,
853         .release                  = vb2_fop_release,
854         .read                     = vb2_fop_read,
855         .poll                     = vb2_fop_poll,
856         .mmap                     = vb2_fop_mmap,
857         .unlocked_ioctl           = video_ioctl2,
858 };
859
860 static struct video_device airspy_template = {
861         .name                     = "AirSpy SDR",
862         .release                  = video_device_release_empty,
863         .fops                     = &airspy_fops,
864         .ioctl_ops                = &airspy_ioctl_ops,
865 };
866
867 static void airspy_video_release(struct v4l2_device *v)
868 {
869         struct airspy *s = container_of(v, struct airspy, v4l2_dev);
870
871         v4l2_ctrl_handler_free(&s->hdl);
872         v4l2_device_unregister(&s->v4l2_dev);
873         kfree(s);
874 }
875
876 static int airspy_set_lna_gain(struct airspy *s)
877 {
878         int ret;
879         u8 u8tmp;
880
881         dev_dbg(s->dev, "lna auto=%d->%d val=%d->%d\n",
882                         s->lna_gain_auto->cur.val, s->lna_gain_auto->val,
883                         s->lna_gain->cur.val, s->lna_gain->val);
884
885         ret = airspy_ctrl_msg(s, CMD_SET_LNA_AGC, 0, s->lna_gain_auto->val,
886                         &u8tmp, 1);
887         if (ret)
888                 goto err;
889
890         if (s->lna_gain_auto->val == false) {
891                 ret = airspy_ctrl_msg(s, CMD_SET_LNA_GAIN, 0, s->lna_gain->val,
892                                 &u8tmp, 1);
893                 if (ret)
894                         goto err;
895         }
896 err:
897         if (ret)
898                 dev_dbg(s->dev, "failed=%d\n", ret);
899
900         return ret;
901 }
902
903 static int airspy_set_mixer_gain(struct airspy *s)
904 {
905         int ret;
906         u8 u8tmp;
907
908         dev_dbg(s->dev, "mixer auto=%d->%d val=%d->%d\n",
909                         s->mixer_gain_auto->cur.val, s->mixer_gain_auto->val,
910                         s->mixer_gain->cur.val, s->mixer_gain->val);
911
912         ret = airspy_ctrl_msg(s, CMD_SET_MIXER_AGC, 0, s->mixer_gain_auto->val,
913                         &u8tmp, 1);
914         if (ret)
915                 goto err;
916
917         if (s->mixer_gain_auto->val == false) {
918                 ret = airspy_ctrl_msg(s, CMD_SET_MIXER_GAIN, 0,
919                                 s->mixer_gain->val, &u8tmp, 1);
920                 if (ret)
921                         goto err;
922         }
923 err:
924         if (ret)
925                 dev_dbg(s->dev, "failed=%d\n", ret);
926
927         return ret;
928 }
929
930 static int airspy_set_if_gain(struct airspy *s)
931 {
932         int ret;
933         u8 u8tmp;
934
935         dev_dbg(s->dev, "val=%d->%d\n", s->if_gain->cur.val, s->if_gain->val);
936
937         ret = airspy_ctrl_msg(s, CMD_SET_VGA_GAIN, 0, s->if_gain->val,
938                         &u8tmp, 1);
939         if (ret)
940                 goto err;
941 err:
942         if (ret)
943                 dev_dbg(s->dev, "failed=%d\n", ret);
944
945         return ret;
946 }
947
948 static int airspy_s_ctrl(struct v4l2_ctrl *ctrl)
949 {
950         struct airspy *s = container_of(ctrl->handler, struct airspy, hdl);
951         int ret;
952
953         switch (ctrl->id) {
954         case  V4L2_CID_RF_TUNER_LNA_GAIN_AUTO:
955         case  V4L2_CID_RF_TUNER_LNA_GAIN:
956                 ret = airspy_set_lna_gain(s);
957                 break;
958         case  V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO:
959         case  V4L2_CID_RF_TUNER_MIXER_GAIN:
960                 ret = airspy_set_mixer_gain(s);
961                 break;
962         case  V4L2_CID_RF_TUNER_IF_GAIN:
963                 ret = airspy_set_if_gain(s);
964                 break;
965         default:
966                 dev_dbg(s->dev, "unknown ctrl: id=%d name=%s\n",
967                                 ctrl->id, ctrl->name);
968                 ret = -EINVAL;
969         }
970
971         return ret;
972 }
973
974 static const struct v4l2_ctrl_ops airspy_ctrl_ops = {
975         .s_ctrl = airspy_s_ctrl,
976 };
977
978 static int airspy_probe(struct usb_interface *intf,
979                 const struct usb_device_id *id)
980 {
981         struct airspy *s;
982         int ret;
983         u8 u8tmp, buf[BUF_SIZE];
984
985         s = kzalloc(sizeof(struct airspy), GFP_KERNEL);
986         if (s == NULL) {
987                 dev_err(&intf->dev, "Could not allocate memory for state\n");
988                 return -ENOMEM;
989         }
990
991         mutex_init(&s->v4l2_lock);
992         mutex_init(&s->vb_queue_lock);
993         spin_lock_init(&s->queued_bufs_lock);
994         INIT_LIST_HEAD(&s->queued_bufs);
995         s->dev = &intf->dev;
996         s->udev = interface_to_usbdev(intf);
997         s->f_adc = bands[0].rangelow;
998         s->f_rf = bands_rf[0].rangelow;
999         s->pixelformat = formats[0].pixelformat;
1000         s->buffersize = formats[0].buffersize;
1001
1002         /* Detect device */
1003         ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
1004         if (ret == 0)
1005                 ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0,
1006                                 buf, BUF_SIZE);
1007         if (ret) {
1008                 dev_err(s->dev, "Could not detect board\n");
1009                 goto err_free_mem;
1010         }
1011
1012         buf[BUF_SIZE - 1] = '\0';
1013
1014         dev_info(s->dev, "Board ID: %02x\n", u8tmp);
1015         dev_info(s->dev, "Firmware version: %s\n", buf);
1016
1017         /* Init videobuf2 queue structure */
1018         s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1019         s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
1020         s->vb_queue.drv_priv = s;
1021         s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf);
1022         s->vb_queue.ops = &airspy_vb2_ops;
1023         s->vb_queue.mem_ops = &vb2_vmalloc_memops;
1024         s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1025         ret = vb2_queue_init(&s->vb_queue);
1026         if (ret) {
1027                 dev_err(s->dev, "Could not initialize vb2 queue\n");
1028                 goto err_free_mem;
1029         }
1030
1031         /* Init video_device structure */
1032         s->vdev = airspy_template;
1033         s->vdev.queue = &s->vb_queue;
1034         s->vdev.queue->lock = &s->vb_queue_lock;
1035         video_set_drvdata(&s->vdev, s);
1036
1037         /* Register the v4l2_device structure */
1038         s->v4l2_dev.release = airspy_video_release;
1039         ret = v4l2_device_register(&intf->dev, &s->v4l2_dev);
1040         if (ret) {
1041                 dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret);
1042                 goto err_free_mem;
1043         }
1044
1045         /* Register controls */
1046         v4l2_ctrl_handler_init(&s->hdl, 5);
1047         s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
1048                         V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0);
1049         s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
1050                         V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8);
1051         v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false);
1052         s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
1053                         V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0);
1054         s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
1055                         V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8);
1056         v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false);
1057         s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops,
1058                         V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0);
1059         if (s->hdl.error) {
1060                 ret = s->hdl.error;
1061                 dev_err(s->dev, "Could not initialize controls\n");
1062                 goto err_free_controls;
1063         }
1064
1065         v4l2_ctrl_handler_setup(&s->hdl);
1066
1067         s->v4l2_dev.ctrl_handler = &s->hdl;
1068         s->vdev.v4l2_dev = &s->v4l2_dev;
1069         s->vdev.lock = &s->v4l2_lock;
1070
1071         ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1);
1072         if (ret) {
1073                 dev_err(s->dev, "Failed to register as video device (%d)\n",
1074                                 ret);
1075                 goto err_unregister_v4l2_dev;
1076         }
1077         dev_info(s->dev, "Registered as %s\n",
1078                         video_device_node_name(&s->vdev));
1079         dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
1080         return 0;
1081
1082 err_free_controls:
1083         v4l2_ctrl_handler_free(&s->hdl);
1084 err_unregister_v4l2_dev:
1085         v4l2_device_unregister(&s->v4l2_dev);
1086 err_free_mem:
1087         kfree(s);
1088         return ret;
1089 }
1090
1091 /* USB device ID list */
1092 static struct usb_device_id airspy_id_table[] = {
1093         { USB_DEVICE(0x1d50, 0x60a1) }, /* AirSpy */
1094         { }
1095 };
1096 MODULE_DEVICE_TABLE(usb, airspy_id_table);
1097
1098 /* USB subsystem interface */
1099 static struct usb_driver airspy_driver = {
1100         .name                     = KBUILD_MODNAME,
1101         .probe                    = airspy_probe,
1102         .disconnect               = airspy_disconnect,
1103         .id_table                 = airspy_id_table,
1104 };
1105
1106 module_usb_driver(airspy_driver);
1107
1108 MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1109 MODULE_DESCRIPTION("AirSpy SDR");
1110 MODULE_LICENSE("GPL");