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