Linux Audio

Check our new training course

Loading...
v6.13.7
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * HackRF driver
   4 *
   5 * Copyright (C) 2014 Antti Palosaari <crope@iki.fi>
   6 */
   7
   8#include <linux/module.h>
   9#include <linux/slab.h>
  10#include <linux/usb.h>
  11#include <media/v4l2-device.h>
  12#include <media/v4l2-ioctl.h>
  13#include <media/v4l2-ctrls.h>
  14#include <media/v4l2-event.h>
  15#include <media/videobuf2-v4l2.h>
  16#include <media/videobuf2-vmalloc.h>
  17
  18/*
  19 * Used Avago MGA-81563 RF amplifier could be destroyed pretty easily with too
  20 * strong signal or transmitting to bad antenna.
  21 * Set RF gain control to 'grabbed' state by default for sure.
  22 */
  23static bool hackrf_enable_rf_gain_ctrl;
  24module_param_named(enable_rf_gain_ctrl, hackrf_enable_rf_gain_ctrl, bool, 0644);
  25MODULE_PARM_DESC(enable_rf_gain_ctrl, "enable RX/TX RF amplifier control (warn: could damage amplifier)");
  26
  27/* HackRF USB API commands (from HackRF Library) */
  28enum {
  29	CMD_SET_TRANSCEIVER_MODE           = 0x01,
  30	CMD_SAMPLE_RATE_SET                = 0x06,
  31	CMD_BASEBAND_FILTER_BANDWIDTH_SET  = 0x07,
  32	CMD_BOARD_ID_READ                  = 0x0e,
  33	CMD_VERSION_STRING_READ            = 0x0f,
  34	CMD_SET_FREQ                       = 0x10,
  35	CMD_AMP_ENABLE                     = 0x11,
  36	CMD_SET_LNA_GAIN                   = 0x13,
  37	CMD_SET_VGA_GAIN                   = 0x14,
  38	CMD_SET_TXVGA_GAIN                 = 0x15,
  39};
  40
  41/*
  42 *       bEndpointAddress     0x81  EP 1 IN
  43 *         Transfer Type            Bulk
  44 *       wMaxPacketSize     0x0200  1x 512 bytes
  45 */
  46#define MAX_BULK_BUFS            (6)
  47#define BULK_BUFFER_SIZE         (128 * 512)
  48
  49static const struct v4l2_frequency_band bands_adc_dac[] = {
  50	{
  51		.tuner = 0,
  52		.type = V4L2_TUNER_SDR,
  53		.index = 0,
  54		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
  55		.rangelow   =   200000,
  56		.rangehigh  = 24000000,
  57	},
  58};
  59
  60static const struct v4l2_frequency_band bands_rx_tx[] = {
  61	{
  62		.tuner = 1,
  63		.type = V4L2_TUNER_RF,
  64		.index = 0,
  65		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
  66		.rangelow   =          1,
  67		.rangehigh  = 4294967294LL, /* max u32, hw goes over 7GHz */
  68	},
  69};
  70
  71/* stream formats */
  72struct hackrf_format {
  73	u32	pixelformat;
  74	u32	buffersize;
  75};
  76
  77/* format descriptions for capture and preview */
  78static struct hackrf_format formats[] = {
  79	{
  80		.pixelformat	= V4L2_SDR_FMT_CS8,
  81		.buffersize	= BULK_BUFFER_SIZE,
  82	},
  83};
  84
  85static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
  86
  87/* intermediate buffers with raw data from the USB device */
  88struct hackrf_buffer {
  89	struct vb2_v4l2_buffer vb;
  90	struct list_head list;
  91};
  92
  93struct hackrf_dev {
  94#define USB_STATE_URB_BUF                1 /* XXX: set manually */
  95#define RX_ON                            4
  96#define TX_ON                            5
  97#define RX_ADC_FREQUENCY                11
  98#define TX_DAC_FREQUENCY                12
  99#define RX_BANDWIDTH                    13
 100#define TX_BANDWIDTH                    14
 101#define RX_RF_FREQUENCY                 15
 102#define TX_RF_FREQUENCY                 16
 103#define RX_RF_GAIN                      17
 104#define TX_RF_GAIN                      18
 105#define RX_IF_GAIN                      19
 106#define RX_LNA_GAIN                     20
 107#define TX_LNA_GAIN                     21
 108	unsigned long flags;
 109
 110	struct usb_interface *intf;
 111	struct device *dev;
 112	struct usb_device *udev;
 113	struct video_device rx_vdev;
 114	struct video_device tx_vdev;
 115	struct v4l2_device v4l2_dev;
 116
 117	/* videobuf2 queue and queued buffers list */
 118	struct vb2_queue rx_vb2_queue;
 119	struct vb2_queue tx_vb2_queue;
 120	struct list_head rx_buffer_list;
 121	struct list_head tx_buffer_list;
 122	spinlock_t buffer_list_lock; /* Protects buffer_list */
 123	unsigned int sequence;	     /* Buffer sequence counter */
 124	unsigned int vb_full;        /* vb is full and packets dropped */
 125	unsigned int vb_empty;       /* vb is empty and packets dropped */
 126
 127	/* Note if taking both locks v4l2_lock must always be locked first! */
 128	struct mutex v4l2_lock;      /* Protects everything else */
 129	struct mutex vb_queue_lock;  /* Protects vb_queue */
 130
 131	struct urb     *urb_list[MAX_BULK_BUFS];
 132	int            buf_num;
 133	unsigned long  buf_size;
 134	u8             *buf_list[MAX_BULK_BUFS];
 135	dma_addr_t     dma_addr[MAX_BULK_BUFS];
 136	int            urbs_initialized;
 137	int            urbs_submitted;
 138
 139	/* USB control message buffer */
 140	#define BUF_SIZE 24
 141	u8 buf[BUF_SIZE];
 142
 143	/* Current configuration */
 144	unsigned int f_adc;
 145	unsigned int f_dac;
 146	unsigned int f_rx;
 147	unsigned int f_tx;
 148	u32 pixelformat;
 149	u32 buffersize;
 150
 151	/* Controls */
 152	struct v4l2_ctrl_handler rx_ctrl_handler;
 153	struct v4l2_ctrl *rx_bandwidth_auto;
 154	struct v4l2_ctrl *rx_bandwidth;
 155	struct v4l2_ctrl *rx_rf_gain;
 156	struct v4l2_ctrl *rx_lna_gain;
 157	struct v4l2_ctrl *rx_if_gain;
 158	struct v4l2_ctrl_handler tx_ctrl_handler;
 159	struct v4l2_ctrl *tx_bandwidth_auto;
 160	struct v4l2_ctrl *tx_bandwidth;
 161	struct v4l2_ctrl *tx_rf_gain;
 162	struct v4l2_ctrl *tx_lna_gain;
 163
 164	/* Sample rate calc */
 165	unsigned long jiffies_next;
 166	unsigned int sample;
 167	unsigned int sample_measured;
 168};
 169
 170#define hackrf_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
 171	char *_direction; \
 172	if (_t & USB_DIR_IN) \
 173		_direction = "<<<"; \
 174	else \
 175		_direction = ">>>"; \
 176	dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
 177			_t, _r, _v & 0xff, _v >> 8, _i & 0xff, \
 178			_i >> 8, _l & 0xff, _l >> 8, _direction, _l, _b); \
 179}
 180
 181/* execute firmware command */
 182static int hackrf_ctrl_msg(struct hackrf_dev *dev, u8 request, u16 value,
 183		u16 index, u8 *data, u16 size)
 184{
 185	int ret;
 186	unsigned int pipe;
 187	u8 requesttype;
 188
 189	switch (request) {
 190	case CMD_SET_TRANSCEIVER_MODE:
 191	case CMD_SET_FREQ:
 192	case CMD_AMP_ENABLE:
 193	case CMD_SAMPLE_RATE_SET:
 194	case CMD_BASEBAND_FILTER_BANDWIDTH_SET:
 195		pipe = usb_sndctrlpipe(dev->udev, 0);
 196		requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
 197		break;
 198	case CMD_BOARD_ID_READ:
 199	case CMD_VERSION_STRING_READ:
 200	case CMD_SET_LNA_GAIN:
 201	case CMD_SET_VGA_GAIN:
 202	case CMD_SET_TXVGA_GAIN:
 203		pipe = usb_rcvctrlpipe(dev->udev, 0);
 204		requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
 205		break;
 206	default:
 207		dev_err(dev->dev, "Unknown command %02x\n", request);
 208		ret = -EINVAL;
 209		goto err;
 210	}
 211
 212	/* write request */
 213	if (!(requesttype & USB_DIR_IN))
 214		memcpy(dev->buf, data, size);
 215
 216	ret = usb_control_msg(dev->udev, pipe, request, requesttype, value,
 217			index, dev->buf, size, 1000);
 218	hackrf_dbg_usb_control_msg(dev->dev, request, requesttype, value,
 219			index, dev->buf, size);
 220	if (ret < 0) {
 221		dev_err(dev->dev, "usb_control_msg() failed %d request %02x\n",
 222				ret, request);
 223		goto err;
 224	}
 225
 226	/* read request */
 227	if (requesttype & USB_DIR_IN)
 228		memcpy(data, dev->buf, size);
 229
 230	return 0;
 231err:
 232	return ret;
 233}
 234
 235static int hackrf_set_params(struct hackrf_dev *dev)
 236{
 237	struct usb_interface *intf = dev->intf;
 238	int ret, i;
 239	u8 buf[8], u8tmp;
 240	unsigned int uitmp, uitmp1, uitmp2;
 241	const bool rx = test_bit(RX_ON, &dev->flags);
 242	const bool tx = test_bit(TX_ON, &dev->flags);
 243	static const struct {
 244		u32 freq;
 245	} bandwidth_lut[] = {
 246		{ 1750000}, /*  1.75 MHz */
 247		{ 2500000}, /*  2.5  MHz */
 248		{ 3500000}, /*  3.5  MHz */
 249		{ 5000000}, /*  5    MHz */
 250		{ 5500000}, /*  5.5  MHz */
 251		{ 6000000}, /*  6    MHz */
 252		{ 7000000}, /*  7    MHz */
 253		{ 8000000}, /*  8    MHz */
 254		{ 9000000}, /*  9    MHz */
 255		{10000000}, /* 10    MHz */
 256		{12000000}, /* 12    MHz */
 257		{14000000}, /* 14    MHz */
 258		{15000000}, /* 15    MHz */
 259		{20000000}, /* 20    MHz */
 260		{24000000}, /* 24    MHz */
 261		{28000000}, /* 28    MHz */
 262	};
 263
 264	if (!rx && !tx) {
 265		dev_dbg(&intf->dev, "device is sleeping\n");
 266		return 0;
 267	}
 268
 269	/* ADC / DAC frequency */
 270	if (rx && test_and_clear_bit(RX_ADC_FREQUENCY, &dev->flags)) {
 271		dev_dbg(&intf->dev, "RX ADC frequency=%u Hz\n", dev->f_adc);
 272		uitmp1 = dev->f_adc;
 273		uitmp2 = 1;
 274		set_bit(TX_DAC_FREQUENCY, &dev->flags);
 275	} else if (tx && test_and_clear_bit(TX_DAC_FREQUENCY, &dev->flags)) {
 276		dev_dbg(&intf->dev, "TX DAC frequency=%u Hz\n", dev->f_dac);
 277		uitmp1 = dev->f_dac;
 278		uitmp2 = 1;
 279		set_bit(RX_ADC_FREQUENCY, &dev->flags);
 280	} else {
 281		uitmp1 = uitmp2 = 0;
 282	}
 283	if (uitmp1 || uitmp2) {
 284		buf[0] = (uitmp1 >>  0) & 0xff;
 285		buf[1] = (uitmp1 >>  8) & 0xff;
 286		buf[2] = (uitmp1 >> 16) & 0xff;
 287		buf[3] = (uitmp1 >> 24) & 0xff;
 288		buf[4] = (uitmp2 >>  0) & 0xff;
 289		buf[5] = (uitmp2 >>  8) & 0xff;
 290		buf[6] = (uitmp2 >> 16) & 0xff;
 291		buf[7] = (uitmp2 >> 24) & 0xff;
 292		ret = hackrf_ctrl_msg(dev, CMD_SAMPLE_RATE_SET, 0, 0, buf, 8);
 293		if (ret)
 294			goto err;
 295	}
 296
 297	/* bandwidth */
 298	if (rx && test_and_clear_bit(RX_BANDWIDTH, &dev->flags)) {
 299		if (dev->rx_bandwidth_auto->val == true)
 300			uitmp = dev->f_adc;
 301		else
 302			uitmp = dev->rx_bandwidth->val;
 303
 304		for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
 305			if (uitmp <= bandwidth_lut[i].freq) {
 306				uitmp = bandwidth_lut[i].freq;
 307				break;
 308			}
 309		}
 310		dev->rx_bandwidth->val = uitmp;
 311		dev->rx_bandwidth->cur.val = uitmp;
 312		dev_dbg(&intf->dev, "RX bandwidth selected=%u\n", uitmp);
 313		set_bit(TX_BANDWIDTH, &dev->flags);
 314	} else if (tx && test_and_clear_bit(TX_BANDWIDTH, &dev->flags)) {
 315		if (dev->tx_bandwidth_auto->val == true)
 316			uitmp = dev->f_dac;
 317		else
 318			uitmp = dev->tx_bandwidth->val;
 319
 320		for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
 321			if (uitmp <= bandwidth_lut[i].freq) {
 322				uitmp = bandwidth_lut[i].freq;
 323				break;
 324			}
 325		}
 326		dev->tx_bandwidth->val = uitmp;
 327		dev->tx_bandwidth->cur.val = uitmp;
 328		dev_dbg(&intf->dev, "TX bandwidth selected=%u\n", uitmp);
 329		set_bit(RX_BANDWIDTH, &dev->flags);
 330	} else {
 331		uitmp = 0;
 332	}
 333	if (uitmp) {
 334		uitmp1 = uitmp2 = 0;
 335		uitmp1 |= ((uitmp >>  0) & 0xff) << 0;
 336		uitmp1 |= ((uitmp >>  8) & 0xff) << 8;
 337		uitmp2 |= ((uitmp >> 16) & 0xff) << 0;
 338		uitmp2 |= ((uitmp >> 24) & 0xff) << 8;
 339		ret = hackrf_ctrl_msg(dev, CMD_BASEBAND_FILTER_BANDWIDTH_SET,
 340				      uitmp1, uitmp2, NULL, 0);
 341		if (ret)
 342			goto err;
 343	}
 344
 345	/* RX / TX RF frequency */
 346	if (rx && test_and_clear_bit(RX_RF_FREQUENCY, &dev->flags)) {
 347		dev_dbg(&intf->dev, "RX RF frequency=%u Hz\n", dev->f_rx);
 348		uitmp1 = dev->f_rx / 1000000;
 349		uitmp2 = dev->f_rx % 1000000;
 350		set_bit(TX_RF_FREQUENCY, &dev->flags);
 351	} else if (tx && test_and_clear_bit(TX_RF_FREQUENCY, &dev->flags)) {
 352		dev_dbg(&intf->dev, "TX RF frequency=%u Hz\n", dev->f_tx);
 353		uitmp1 = dev->f_tx / 1000000;
 354		uitmp2 = dev->f_tx % 1000000;
 355		set_bit(RX_RF_FREQUENCY, &dev->flags);
 356	} else {
 357		uitmp1 = uitmp2 = 0;
 358	}
 359	if (uitmp1 || uitmp2) {
 360		buf[0] = (uitmp1 >>  0) & 0xff;
 361		buf[1] = (uitmp1 >>  8) & 0xff;
 362		buf[2] = (uitmp1 >> 16) & 0xff;
 363		buf[3] = (uitmp1 >> 24) & 0xff;
 364		buf[4] = (uitmp2 >>  0) & 0xff;
 365		buf[5] = (uitmp2 >>  8) & 0xff;
 366		buf[6] = (uitmp2 >> 16) & 0xff;
 367		buf[7] = (uitmp2 >> 24) & 0xff;
 368		ret = hackrf_ctrl_msg(dev, CMD_SET_FREQ, 0, 0, buf, 8);
 369		if (ret)
 370			goto err;
 371	}
 372
 373	/* RX RF gain */
 374	if (rx && test_and_clear_bit(RX_RF_GAIN, &dev->flags)) {
 375		dev_dbg(&intf->dev, "RX RF gain val=%d->%d\n",
 376			dev->rx_rf_gain->cur.val, dev->rx_rf_gain->val);
 377
 378		u8tmp = (dev->rx_rf_gain->val) ? 1 : 0;
 379		ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
 380		if (ret)
 381			goto err;
 382		set_bit(TX_RF_GAIN, &dev->flags);
 383	}
 384
 385	/* TX RF gain */
 386	if (tx && test_and_clear_bit(TX_RF_GAIN, &dev->flags)) {
 387		dev_dbg(&intf->dev, "TX RF gain val=%d->%d\n",
 388			dev->tx_rf_gain->cur.val, dev->tx_rf_gain->val);
 389
 390		u8tmp = (dev->tx_rf_gain->val) ? 1 : 0;
 391		ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
 392		if (ret)
 393			goto err;
 394		set_bit(RX_RF_GAIN, &dev->flags);
 395	}
 396
 397	/* RX LNA gain */
 398	if (rx && test_and_clear_bit(RX_LNA_GAIN, &dev->flags)) {
 399		dev_dbg(dev->dev, "RX LNA gain val=%d->%d\n",
 400			dev->rx_lna_gain->cur.val, dev->rx_lna_gain->val);
 401
 402		ret = hackrf_ctrl_msg(dev, CMD_SET_LNA_GAIN, 0,
 403				      dev->rx_lna_gain->val, &u8tmp, 1);
 404		if (ret)
 405			goto err;
 406	}
 407
 408	/* RX IF gain */
 409	if (rx && test_and_clear_bit(RX_IF_GAIN, &dev->flags)) {
 410		dev_dbg(&intf->dev, "IF gain val=%d->%d\n",
 411			dev->rx_if_gain->cur.val, dev->rx_if_gain->val);
 412
 413		ret = hackrf_ctrl_msg(dev, CMD_SET_VGA_GAIN, 0,
 414				      dev->rx_if_gain->val, &u8tmp, 1);
 415		if (ret)
 416			goto err;
 417	}
 418
 419	/* TX LNA gain */
 420	if (tx && test_and_clear_bit(TX_LNA_GAIN, &dev->flags)) {
 421		dev_dbg(&intf->dev, "TX LNA gain val=%d->%d\n",
 422			dev->tx_lna_gain->cur.val, dev->tx_lna_gain->val);
 423
 424		ret = hackrf_ctrl_msg(dev, CMD_SET_TXVGA_GAIN, 0,
 425				      dev->tx_lna_gain->val, &u8tmp, 1);
 426		if (ret)
 427			goto err;
 428	}
 429
 430	return 0;
 431err:
 432	dev_dbg(&intf->dev, "failed=%d\n", ret);
 433	return ret;
 434}
 435
 436/* Private functions */
 437static struct hackrf_buffer *hackrf_get_next_buffer(struct hackrf_dev *dev,
 438						    struct list_head *buffer_list)
 439{
 440	unsigned long flags;
 441	struct hackrf_buffer *buffer = NULL;
 442
 443	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 444	if (list_empty(buffer_list))
 445		goto leave;
 446
 447	buffer = list_entry(buffer_list->next, struct hackrf_buffer, list);
 448	list_del(&buffer->list);
 449leave:
 450	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 451	return buffer;
 452}
 453
 454static void hackrf_copy_stream(struct hackrf_dev *dev, void *dst, void *src,
 455			       unsigned int src_len)
 456{
 457	memcpy(dst, src, src_len);
 458
 459	/* calculate sample rate and output it in 10 seconds intervals */
 460	if (unlikely(time_is_before_jiffies(dev->jiffies_next))) {
 461		#define MSECS 10000UL
 462		unsigned int msecs = jiffies_to_msecs(jiffies -
 463				dev->jiffies_next + msecs_to_jiffies(MSECS));
 464		unsigned int samples = dev->sample - dev->sample_measured;
 465
 466		dev->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
 467		dev->sample_measured = dev->sample;
 468		dev_dbg(dev->dev, "slen=%u samples=%u msecs=%u sample rate=%lu\n",
 469				src_len, samples, msecs,
 470				samples * 1000UL / msecs);
 471	}
 472
 473	/* total number of samples */
 474	dev->sample += src_len / 2;
 475}
 476
 477/*
 478 * This gets called for the bulk stream pipe. This is done in interrupt
 479 * time, so it has to be fast, not crash, and not stall. Neat.
 480 */
 481static void hackrf_urb_complete_in(struct urb *urb)
 482{
 483	struct hackrf_dev *dev = urb->context;
 484	struct usb_interface *intf = dev->intf;
 485	struct hackrf_buffer *buffer;
 486	unsigned int len;
 487
 488	dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
 489			    urb->actual_length, urb->transfer_buffer_length);
 490
 491	switch (urb->status) {
 492	case 0:             /* success */
 493	case -ETIMEDOUT:    /* NAK */
 494		break;
 495	case -ECONNRESET:   /* kill */
 496	case -ENOENT:
 497	case -ESHUTDOWN:
 498		return;
 499	default:            /* error */
 500		dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
 501		goto exit_usb_submit_urb;
 502	}
 503
 504	/* get buffer to write */
 505	buffer = hackrf_get_next_buffer(dev, &dev->rx_buffer_list);
 506	if (unlikely(buffer == NULL)) {
 507		dev->vb_full++;
 508		dev_notice_ratelimited(&intf->dev,
 509				       "buffer is full - %u packets dropped\n",
 510				       dev->vb_full);
 511		goto exit_usb_submit_urb;
 512	}
 513
 514	len = min_t(unsigned long, vb2_plane_size(&buffer->vb.vb2_buf, 0),
 515		    urb->actual_length);
 516	hackrf_copy_stream(dev, vb2_plane_vaddr(&buffer->vb.vb2_buf, 0),
 517		    urb->transfer_buffer, len);
 518	vb2_set_plane_payload(&buffer->vb.vb2_buf, 0, len);
 519	buffer->vb.sequence = dev->sequence++;
 520	buffer->vb.vb2_buf.timestamp = ktime_get_ns();
 521	vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
 522exit_usb_submit_urb:
 523	usb_submit_urb(urb, GFP_ATOMIC);
 524}
 525
 526static void hackrf_urb_complete_out(struct urb *urb)
 527{
 528	struct hackrf_dev *dev = urb->context;
 529	struct usb_interface *intf = dev->intf;
 530	struct hackrf_buffer *buffer;
 531	unsigned int len;
 532
 533	dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
 534			    urb->actual_length, urb->transfer_buffer_length);
 535
 536	switch (urb->status) {
 537	case 0:             /* success */
 538	case -ETIMEDOUT:    /* NAK */
 539		break;
 540	case -ECONNRESET:   /* kill */
 541	case -ENOENT:
 542	case -ESHUTDOWN:
 543		return;
 544	default:            /* error */
 545		dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
 546	}
 547
 548	/* get buffer to read */
 549	buffer = hackrf_get_next_buffer(dev, &dev->tx_buffer_list);
 550	if (unlikely(buffer == NULL)) {
 551		dev->vb_empty++;
 552		dev_notice_ratelimited(&intf->dev,
 553				       "buffer is empty - %u packets dropped\n",
 554				       dev->vb_empty);
 555		urb->actual_length = 0;
 556		goto exit_usb_submit_urb;
 557	}
 558
 559	len = min_t(unsigned long, urb->transfer_buffer_length,
 560		    vb2_get_plane_payload(&buffer->vb.vb2_buf, 0));
 561	hackrf_copy_stream(dev, urb->transfer_buffer,
 562			   vb2_plane_vaddr(&buffer->vb.vb2_buf, 0), len);
 563	urb->actual_length = len;
 564	buffer->vb.sequence = dev->sequence++;
 565	buffer->vb.vb2_buf.timestamp = ktime_get_ns();
 566	vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
 567exit_usb_submit_urb:
 568	usb_submit_urb(urb, GFP_ATOMIC);
 569}
 570
 571static int hackrf_kill_urbs(struct hackrf_dev *dev)
 572{
 573	int i;
 574
 575	for (i = dev->urbs_submitted - 1; i >= 0; i--) {
 576		dev_dbg(dev->dev, "kill urb=%d\n", i);
 577		/* stop the URB */
 578		usb_kill_urb(dev->urb_list[i]);
 579	}
 580	dev->urbs_submitted = 0;
 581
 582	return 0;
 583}
 584
 585static int hackrf_submit_urbs(struct hackrf_dev *dev)
 586{
 587	int i, ret;
 588
 589	for (i = 0; i < dev->urbs_initialized; i++) {
 590		dev_dbg(dev->dev, "submit urb=%d\n", i);
 591		ret = usb_submit_urb(dev->urb_list[i], GFP_KERNEL);
 592		if (ret) {
 593			dev_err(dev->dev, "Could not submit URB no. %d - get them all back\n",
 594					i);
 595			hackrf_kill_urbs(dev);
 596			return ret;
 597		}
 598		dev->urbs_submitted++;
 599	}
 600
 601	return 0;
 602}
 603
 604static int hackrf_free_stream_bufs(struct hackrf_dev *dev)
 605{
 606	if (dev->flags & USB_STATE_URB_BUF) {
 607		while (dev->buf_num) {
 608			dev->buf_num--;
 609			dev_dbg(dev->dev, "free buf=%d\n", dev->buf_num);
 610			usb_free_coherent(dev->udev, dev->buf_size,
 611					  dev->buf_list[dev->buf_num],
 612					  dev->dma_addr[dev->buf_num]);
 613		}
 614	}
 615	dev->flags &= ~USB_STATE_URB_BUF;
 616
 617	return 0;
 618}
 619
 620static int hackrf_alloc_stream_bufs(struct hackrf_dev *dev)
 621{
 622	dev->buf_num = 0;
 623	dev->buf_size = BULK_BUFFER_SIZE;
 624
 625	dev_dbg(dev->dev, "all in all I will use %u bytes for streaming\n",
 626			MAX_BULK_BUFS * BULK_BUFFER_SIZE);
 627
 628	for (dev->buf_num = 0; dev->buf_num < MAX_BULK_BUFS; dev->buf_num++) {
 629		dev->buf_list[dev->buf_num] = usb_alloc_coherent(dev->udev,
 630				BULK_BUFFER_SIZE, GFP_KERNEL,
 631				&dev->dma_addr[dev->buf_num]);
 632		if (!dev->buf_list[dev->buf_num]) {
 633			dev_dbg(dev->dev, "alloc buf=%d failed\n",
 634					dev->buf_num);
 635			hackrf_free_stream_bufs(dev);
 636			return -ENOMEM;
 637		}
 638
 639		dev_dbg(dev->dev, "alloc buf=%d %p (dma %llu)\n", dev->buf_num,
 640				dev->buf_list[dev->buf_num],
 641				(long long)dev->dma_addr[dev->buf_num]);
 642		dev->flags |= USB_STATE_URB_BUF;
 643	}
 644
 645	return 0;
 646}
 647
 648static int hackrf_free_urbs(struct hackrf_dev *dev)
 649{
 650	int i;
 651
 652	hackrf_kill_urbs(dev);
 653
 654	for (i = dev->urbs_initialized - 1; i >= 0; i--) {
 655		if (dev->urb_list[i]) {
 656			dev_dbg(dev->dev, "free urb=%d\n", i);
 657			/* free the URBs */
 658			usb_free_urb(dev->urb_list[i]);
 659		}
 660	}
 661	dev->urbs_initialized = 0;
 662
 663	return 0;
 664}
 665
 666static int hackrf_alloc_urbs(struct hackrf_dev *dev, bool rcv)
 667{
 668	int i, j;
 669	unsigned int pipe;
 670	usb_complete_t complete;
 671
 672	if (rcv) {
 673		pipe = usb_rcvbulkpipe(dev->udev, 0x81);
 674		complete = &hackrf_urb_complete_in;
 675	} else {
 676		pipe = usb_sndbulkpipe(dev->udev, 0x02);
 677		complete = &hackrf_urb_complete_out;
 678	}
 679
 680	/* allocate the URBs */
 681	for (i = 0; i < MAX_BULK_BUFS; i++) {
 682		dev_dbg(dev->dev, "alloc urb=%d\n", i);
 683		dev->urb_list[i] = usb_alloc_urb(0, GFP_KERNEL);
 684		if (!dev->urb_list[i]) {
 685			for (j = 0; j < i; j++)
 686				usb_free_urb(dev->urb_list[j]);
 687			return -ENOMEM;
 688		}
 689		usb_fill_bulk_urb(dev->urb_list[i],
 690				dev->udev,
 691				pipe,
 692				dev->buf_list[i],
 693				BULK_BUFFER_SIZE,
 694				complete, dev);
 695
 696		dev->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
 697		dev->urb_list[i]->transfer_dma = dev->dma_addr[i];
 698		dev->urbs_initialized++;
 699	}
 700
 701	return 0;
 702}
 703
 704/* The user yanked out the cable... */
 705static void hackrf_disconnect(struct usb_interface *intf)
 706{
 707	struct v4l2_device *v = usb_get_intfdata(intf);
 708	struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
 709
 710	dev_dbg(dev->dev, "\n");
 711
 712	mutex_lock(&dev->vb_queue_lock);
 713	mutex_lock(&dev->v4l2_lock);
 714	/* No need to keep the urbs around after disconnection */
 715	dev->udev = NULL;
 716	v4l2_device_disconnect(&dev->v4l2_dev);
 717	video_unregister_device(&dev->tx_vdev);
 718	video_unregister_device(&dev->rx_vdev);
 719	mutex_unlock(&dev->v4l2_lock);
 720	mutex_unlock(&dev->vb_queue_lock);
 721
 722	v4l2_device_put(&dev->v4l2_dev);
 723}
 724
 725/* Videobuf2 operations */
 726static void hackrf_return_all_buffers(struct vb2_queue *vq,
 727				      enum vb2_buffer_state state)
 728{
 729	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 730	struct usb_interface *intf = dev->intf;
 731	struct hackrf_buffer *buffer, *node;
 732	struct list_head *buffer_list;
 733	unsigned long flags;
 734
 735	dev_dbg(&intf->dev, "\n");
 736
 737	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 738		buffer_list = &dev->rx_buffer_list;
 739	else
 740		buffer_list = &dev->tx_buffer_list;
 741
 742	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 743	list_for_each_entry_safe(buffer, node, buffer_list, list) {
 744		dev_dbg(&intf->dev, "list_for_each_entry_safe\n");
 745		vb2_buffer_done(&buffer->vb.vb2_buf, state);
 746		list_del(&buffer->list);
 747	}
 748	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 749}
 750
 751static int hackrf_queue_setup(struct vb2_queue *vq,
 752		unsigned int *nbuffers,
 753		unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[])
 754{
 755	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 756	unsigned int q_num_bufs = vb2_get_num_buffers(vq);
 757
 758	dev_dbg(dev->dev, "nbuffers=%d\n", *nbuffers);
 759
 760	/* Need at least 8 buffers */
 761	if (q_num_bufs + *nbuffers < 8)
 762		*nbuffers = 8 - q_num_bufs;
 763	*nplanes = 1;
 764	sizes[0] = PAGE_ALIGN(dev->buffersize);
 765
 766	dev_dbg(dev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
 767	return 0;
 768}
 769
 770static void hackrf_buf_queue(struct vb2_buffer *vb)
 771{
 772	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
 773	struct vb2_queue *vq = vb->vb2_queue;
 774	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 775	struct hackrf_buffer *buffer = container_of(vbuf, struct hackrf_buffer, vb);
 776	struct list_head *buffer_list;
 777	unsigned long flags;
 778
 779	dev_dbg_ratelimited(&dev->intf->dev, "\n");
 780
 781	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 782		buffer_list = &dev->rx_buffer_list;
 783	else
 784		buffer_list = &dev->tx_buffer_list;
 785
 786	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 787	list_add_tail(&buffer->list, buffer_list);
 788	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 789}
 790
 791static int hackrf_start_streaming(struct vb2_queue *vq, unsigned int count)
 792{
 793	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 794	struct usb_interface *intf = dev->intf;
 795	int ret;
 796	unsigned int mode;
 797
 798	dev_dbg(&intf->dev, "count=%i\n", count);
 799
 800	mutex_lock(&dev->v4l2_lock);
 801
 802	/* Allow only RX or TX, not both same time */
 803	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE) {
 804		if (test_bit(TX_ON, &dev->flags)) {
 805			ret = -EBUSY;
 806			goto err_hackrf_return_all_buffers;
 807		}
 808
 809		mode = 1;
 810		set_bit(RX_ON, &dev->flags);
 811	} else {
 812		if (test_bit(RX_ON, &dev->flags)) {
 813			ret = -EBUSY;
 814			goto err_hackrf_return_all_buffers;
 815		}
 816
 817		mode = 2;
 818		set_bit(TX_ON, &dev->flags);
 819	}
 820
 821	dev->sequence = 0;
 822
 823	ret = hackrf_alloc_stream_bufs(dev);
 824	if (ret)
 825		goto err;
 826
 827	ret = hackrf_alloc_urbs(dev, (mode == 1));
 828	if (ret)
 829		goto err;
 830
 831	ret = hackrf_submit_urbs(dev);
 832	if (ret)
 833		goto err;
 834
 835	ret = hackrf_set_params(dev);
 836	if (ret)
 837		goto err;
 838
 839	/* start hardware streaming */
 840	ret = hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, mode, 0, NULL, 0);
 841	if (ret)
 842		goto err;
 843
 844	mutex_unlock(&dev->v4l2_lock);
 845
 846	return 0;
 847err:
 848	hackrf_kill_urbs(dev);
 849	hackrf_free_urbs(dev);
 850	hackrf_free_stream_bufs(dev);
 851	clear_bit(RX_ON, &dev->flags);
 852	clear_bit(TX_ON, &dev->flags);
 853err_hackrf_return_all_buffers:
 854	hackrf_return_all_buffers(vq, VB2_BUF_STATE_QUEUED);
 855	mutex_unlock(&dev->v4l2_lock);
 856	dev_dbg(&intf->dev, "failed=%d\n", ret);
 857	return ret;
 858}
 859
 860static void hackrf_stop_streaming(struct vb2_queue *vq)
 861{
 862	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 863	struct usb_interface *intf = dev->intf;
 864
 865	dev_dbg(&intf->dev, "\n");
 866
 867	mutex_lock(&dev->v4l2_lock);
 868
 869	/* stop hardware streaming */
 870	hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, 0, 0, NULL, 0);
 871
 872	hackrf_kill_urbs(dev);
 873	hackrf_free_urbs(dev);
 874	hackrf_free_stream_bufs(dev);
 875
 876	hackrf_return_all_buffers(vq, VB2_BUF_STATE_ERROR);
 877
 878	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 879		clear_bit(RX_ON, &dev->flags);
 880	else
 881		clear_bit(TX_ON, &dev->flags);
 882
 883	mutex_unlock(&dev->v4l2_lock);
 884}
 885
 886static const struct vb2_ops hackrf_vb2_ops = {
 887	.queue_setup            = hackrf_queue_setup,
 888	.buf_queue              = hackrf_buf_queue,
 889	.start_streaming        = hackrf_start_streaming,
 890	.stop_streaming         = hackrf_stop_streaming,
 
 
 891};
 892
 893static int hackrf_querycap(struct file *file, void *fh,
 894		struct v4l2_capability *cap)
 895{
 896	struct hackrf_dev *dev = video_drvdata(file);
 897	struct usb_interface *intf = dev->intf;
 898
 899	dev_dbg(&intf->dev, "\n");
 900
 901	cap->capabilities = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER |
 902			    V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR |
 903			    V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
 904			    V4L2_CAP_DEVICE_CAPS;
 905	strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
 906	strscpy(cap->card, dev->rx_vdev.name, sizeof(cap->card));
 907	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
 908
 909	return 0;
 910}
 911
 912static int hackrf_s_fmt_sdr(struct file *file, void *priv,
 913			    struct v4l2_format *f)
 914{
 915	struct hackrf_dev *dev = video_drvdata(file);
 916	struct video_device *vdev = video_devdata(file);
 917	struct vb2_queue *q;
 918	int i;
 919
 920	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 921			(char *)&f->fmt.sdr.pixelformat);
 922
 923	if (vdev->vfl_dir == VFL_DIR_RX)
 924		q = &dev->rx_vb2_queue;
 925	else
 926		q = &dev->tx_vb2_queue;
 927
 928	if (vb2_is_busy(q))
 929		return -EBUSY;
 930
 
 931	for (i = 0; i < NUM_FORMATS; i++) {
 932		if (f->fmt.sdr.pixelformat == formats[i].pixelformat) {
 933			dev->pixelformat = formats[i].pixelformat;
 934			dev->buffersize = formats[i].buffersize;
 935			f->fmt.sdr.buffersize = formats[i].buffersize;
 936			return 0;
 937		}
 938	}
 939
 940	dev->pixelformat = formats[0].pixelformat;
 941	dev->buffersize = formats[0].buffersize;
 942	f->fmt.sdr.pixelformat = formats[0].pixelformat;
 943	f->fmt.sdr.buffersize = formats[0].buffersize;
 944
 945	return 0;
 946}
 947
 948static int hackrf_g_fmt_sdr(struct file *file, void *priv,
 949			    struct v4l2_format *f)
 950{
 951	struct hackrf_dev *dev = video_drvdata(file);
 952
 953	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 954			(char *)&dev->pixelformat);
 955
 
 956	f->fmt.sdr.pixelformat = dev->pixelformat;
 957	f->fmt.sdr.buffersize = dev->buffersize;
 958
 959	return 0;
 960}
 961
 962static int hackrf_try_fmt_sdr(struct file *file, void *priv,
 963			      struct v4l2_format *f)
 964{
 965	struct hackrf_dev *dev = video_drvdata(file);
 966	int i;
 967
 968	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 969			(char *)&f->fmt.sdr.pixelformat);
 970
 
 971	for (i = 0; i < NUM_FORMATS; i++) {
 972		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
 973			f->fmt.sdr.buffersize = formats[i].buffersize;
 974			return 0;
 975		}
 976	}
 977
 978	f->fmt.sdr.pixelformat = formats[0].pixelformat;
 979	f->fmt.sdr.buffersize = formats[0].buffersize;
 980
 981	return 0;
 982}
 983
 984static int hackrf_enum_fmt_sdr(struct file *file, void *priv,
 985			       struct v4l2_fmtdesc *f)
 986{
 987	struct hackrf_dev *dev = video_drvdata(file);
 988
 989	dev_dbg(dev->dev, "index=%d\n", f->index);
 990
 991	if (f->index >= NUM_FORMATS)
 992		return -EINVAL;
 993
 994	f->pixelformat = formats[f->index].pixelformat;
 995
 996	return 0;
 997}
 998
 999static int hackrf_s_tuner(struct file *file, void *priv,
1000		const struct v4l2_tuner *v)
1001{
1002	struct hackrf_dev *dev = video_drvdata(file);
1003	int ret;
1004
1005	dev_dbg(dev->dev, "index=%d\n", v->index);
1006
1007	if (v->index == 0)
1008		ret = 0;
1009	else if (v->index == 1)
1010		ret = 0;
1011	else
1012		ret = -EINVAL;
1013
1014	return ret;
1015}
1016
1017static int hackrf_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
1018{
1019	struct hackrf_dev *dev = video_drvdata(file);
1020	int ret;
1021
1022	dev_dbg(dev->dev, "index=%d\n", v->index);
1023
1024	if (v->index == 0) {
1025		strscpy(v->name, "HackRF ADC", sizeof(v->name));
1026		v->type = V4L2_TUNER_SDR;
1027		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1028		v->rangelow  = bands_adc_dac[0].rangelow;
1029		v->rangehigh = bands_adc_dac[0].rangehigh;
1030		ret = 0;
1031	} else if (v->index == 1) {
1032		strscpy(v->name, "HackRF RF", sizeof(v->name));
1033		v->type = V4L2_TUNER_RF;
1034		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1035		v->rangelow  = bands_rx_tx[0].rangelow;
1036		v->rangehigh = bands_rx_tx[0].rangehigh;
1037		ret = 0;
1038	} else {
1039		ret = -EINVAL;
1040	}
1041
1042	return ret;
1043}
1044
1045static int hackrf_s_modulator(struct file *file, void *fh,
1046			      const struct v4l2_modulator *a)
1047{
1048	struct hackrf_dev *dev = video_drvdata(file);
1049
1050	dev_dbg(dev->dev, "index=%d\n", a->index);
1051
1052	return a->index > 1 ? -EINVAL : 0;
1053}
1054
1055static int hackrf_g_modulator(struct file *file, void *fh,
1056			      struct v4l2_modulator *a)
1057{
1058	struct hackrf_dev *dev = video_drvdata(file);
1059	int ret;
1060
1061	dev_dbg(dev->dev, "index=%d\n", a->index);
1062
1063	if (a->index == 0) {
1064		strscpy(a->name, "HackRF DAC", sizeof(a->name));
1065		a->type = V4L2_TUNER_SDR;
1066		a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1067		a->rangelow  = bands_adc_dac[0].rangelow;
1068		a->rangehigh = bands_adc_dac[0].rangehigh;
1069		ret = 0;
1070	} else if (a->index == 1) {
1071		strscpy(a->name, "HackRF RF", sizeof(a->name));
1072		a->type = V4L2_TUNER_RF;
1073		a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1074		a->rangelow  = bands_rx_tx[0].rangelow;
1075		a->rangehigh = bands_rx_tx[0].rangehigh;
1076		ret = 0;
1077	} else {
1078		ret = -EINVAL;
1079	}
1080
1081	return ret;
1082}
1083
1084static int hackrf_s_frequency(struct file *file, void *priv,
1085		const struct v4l2_frequency *f)
1086{
1087	struct hackrf_dev *dev = video_drvdata(file);
1088	struct usb_interface *intf = dev->intf;
1089	struct video_device *vdev = video_devdata(file);
1090	int ret;
1091	unsigned int uitmp;
1092
1093	dev_dbg(&intf->dev, "tuner=%d type=%d frequency=%u\n",
1094			f->tuner, f->type, f->frequency);
1095
1096	if (f->tuner == 0) {
1097		uitmp = clamp(f->frequency, bands_adc_dac[0].rangelow,
1098			      bands_adc_dac[0].rangehigh);
1099		if (vdev->vfl_dir == VFL_DIR_RX) {
1100			dev->f_adc = uitmp;
1101			set_bit(RX_ADC_FREQUENCY, &dev->flags);
1102		} else {
1103			dev->f_dac = uitmp;
1104			set_bit(TX_DAC_FREQUENCY, &dev->flags);
1105		}
1106	} else if (f->tuner == 1) {
1107		uitmp = clamp(f->frequency, bands_rx_tx[0].rangelow,
1108			      bands_rx_tx[0].rangehigh);
1109		if (vdev->vfl_dir == VFL_DIR_RX) {
1110			dev->f_rx = uitmp;
1111			set_bit(RX_RF_FREQUENCY, &dev->flags);
1112		} else {
1113			dev->f_tx = uitmp;
1114			set_bit(TX_RF_FREQUENCY, &dev->flags);
1115		}
1116	} else {
1117		ret = -EINVAL;
1118		goto err;
1119	}
1120
1121	ret = hackrf_set_params(dev);
1122	if (ret)
1123		goto err;
1124
1125	return 0;
1126err:
1127	dev_dbg(&intf->dev, "failed=%d\n", ret);
1128	return ret;
1129}
1130
1131static int hackrf_g_frequency(struct file *file, void *priv,
1132		struct v4l2_frequency *f)
1133{
1134	struct hackrf_dev *dev = video_drvdata(file);
1135	struct usb_interface *intf = dev->intf;
1136	struct video_device *vdev = video_devdata(file);
1137	int ret;
1138
1139	dev_dbg(dev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
1140
1141	if (f->tuner == 0) {
1142		f->type = V4L2_TUNER_SDR;
1143		if (vdev->vfl_dir == VFL_DIR_RX)
1144			f->frequency = dev->f_adc;
1145		else
1146			f->frequency = dev->f_dac;
1147	} else if (f->tuner == 1) {
1148		f->type = V4L2_TUNER_RF;
1149		if (vdev->vfl_dir == VFL_DIR_RX)
1150			f->frequency = dev->f_rx;
1151		else
1152			f->frequency = dev->f_tx;
1153	} else {
1154		ret = -EINVAL;
1155		goto err;
1156	}
1157
1158	return 0;
1159err:
1160	dev_dbg(&intf->dev, "failed=%d\n", ret);
1161	return ret;
1162}
1163
1164static int hackrf_enum_freq_bands(struct file *file, void *priv,
1165		struct v4l2_frequency_band *band)
1166{
1167	struct hackrf_dev *dev = video_drvdata(file);
1168	int ret;
1169
1170	dev_dbg(dev->dev, "tuner=%d type=%d index=%d\n",
1171			band->tuner, band->type, band->index);
1172
1173	if (band->tuner == 0) {
1174		if (band->index >= ARRAY_SIZE(bands_adc_dac)) {
1175			ret = -EINVAL;
1176		} else {
1177			*band = bands_adc_dac[band->index];
1178			ret = 0;
1179		}
1180	} else if (band->tuner == 1) {
1181		if (band->index >= ARRAY_SIZE(bands_rx_tx)) {
1182			ret = -EINVAL;
1183		} else {
1184			*band = bands_rx_tx[band->index];
1185			ret = 0;
1186		}
1187	} else {
1188		ret = -EINVAL;
1189	}
1190
1191	return ret;
1192}
1193
1194static const struct v4l2_ioctl_ops hackrf_ioctl_ops = {
1195	.vidioc_querycap          = hackrf_querycap,
1196
1197	.vidioc_s_fmt_sdr_cap     = hackrf_s_fmt_sdr,
1198	.vidioc_g_fmt_sdr_cap     = hackrf_g_fmt_sdr,
1199	.vidioc_enum_fmt_sdr_cap  = hackrf_enum_fmt_sdr,
1200	.vidioc_try_fmt_sdr_cap   = hackrf_try_fmt_sdr,
1201
1202	.vidioc_s_fmt_sdr_out     = hackrf_s_fmt_sdr,
1203	.vidioc_g_fmt_sdr_out     = hackrf_g_fmt_sdr,
1204	.vidioc_enum_fmt_sdr_out  = hackrf_enum_fmt_sdr,
1205	.vidioc_try_fmt_sdr_out   = hackrf_try_fmt_sdr,
1206
1207	.vidioc_reqbufs           = vb2_ioctl_reqbufs,
1208	.vidioc_create_bufs       = vb2_ioctl_create_bufs,
1209	.vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1210	.vidioc_querybuf          = vb2_ioctl_querybuf,
1211	.vidioc_qbuf              = vb2_ioctl_qbuf,
1212	.vidioc_dqbuf             = vb2_ioctl_dqbuf,
1213	.vidioc_expbuf            = vb2_ioctl_expbuf,
1214
1215	.vidioc_streamon          = vb2_ioctl_streamon,
1216	.vidioc_streamoff         = vb2_ioctl_streamoff,
1217
1218	.vidioc_s_tuner           = hackrf_s_tuner,
1219	.vidioc_g_tuner           = hackrf_g_tuner,
1220
1221	.vidioc_s_modulator       = hackrf_s_modulator,
1222	.vidioc_g_modulator       = hackrf_g_modulator,
1223
1224	.vidioc_s_frequency       = hackrf_s_frequency,
1225	.vidioc_g_frequency       = hackrf_g_frequency,
1226	.vidioc_enum_freq_bands   = hackrf_enum_freq_bands,
1227
1228	.vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1229	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1230	.vidioc_log_status        = v4l2_ctrl_log_status,
1231};
1232
1233static const struct v4l2_file_operations hackrf_fops = {
1234	.owner                    = THIS_MODULE,
1235	.open                     = v4l2_fh_open,
1236	.release                  = vb2_fop_release,
1237	.read                     = vb2_fop_read,
1238	.write                    = vb2_fop_write,
1239	.poll                     = vb2_fop_poll,
1240	.mmap                     = vb2_fop_mmap,
1241	.unlocked_ioctl           = video_ioctl2,
1242};
1243
1244static const struct video_device hackrf_template = {
1245	.name                     = "HackRF One",
1246	.release                  = video_device_release_empty,
1247	.fops                     = &hackrf_fops,
1248	.ioctl_ops                = &hackrf_ioctl_ops,
1249};
1250
1251static void hackrf_video_release(struct v4l2_device *v)
1252{
1253	struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
1254
1255	dev_dbg(dev->dev, "\n");
1256
1257	v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
1258	v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
1259	v4l2_device_unregister(&dev->v4l2_dev);
1260	kfree(dev);
1261}
1262
1263static int hackrf_s_ctrl_rx(struct v4l2_ctrl *ctrl)
1264{
1265	struct hackrf_dev *dev = container_of(ctrl->handler,
1266			struct hackrf_dev, rx_ctrl_handler);
1267	struct usb_interface *intf = dev->intf;
1268	int ret;
1269
1270	switch (ctrl->id) {
1271	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1272	case V4L2_CID_RF_TUNER_BANDWIDTH:
1273		set_bit(RX_BANDWIDTH, &dev->flags);
1274		break;
1275	case  V4L2_CID_RF_TUNER_RF_GAIN:
1276		set_bit(RX_RF_GAIN, &dev->flags);
1277		break;
1278	case  V4L2_CID_RF_TUNER_LNA_GAIN:
1279		set_bit(RX_LNA_GAIN, &dev->flags);
1280		break;
1281	case  V4L2_CID_RF_TUNER_IF_GAIN:
1282		set_bit(RX_IF_GAIN, &dev->flags);
1283		break;
1284	default:
1285		dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
1286			ctrl->id, ctrl->name);
1287		ret = -EINVAL;
1288		goto err;
1289	}
1290
1291	ret = hackrf_set_params(dev);
1292	if (ret)
1293		goto err;
1294
1295	return 0;
1296err:
1297	dev_dbg(&intf->dev, "failed=%d\n", ret);
1298	return ret;
1299}
1300
1301static int hackrf_s_ctrl_tx(struct v4l2_ctrl *ctrl)
1302{
1303	struct hackrf_dev *dev = container_of(ctrl->handler,
1304			struct hackrf_dev, tx_ctrl_handler);
1305	struct usb_interface *intf = dev->intf;
1306	int ret;
1307
1308	switch (ctrl->id) {
1309	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1310	case V4L2_CID_RF_TUNER_BANDWIDTH:
1311		set_bit(TX_BANDWIDTH, &dev->flags);
1312		break;
1313	case  V4L2_CID_RF_TUNER_LNA_GAIN:
1314		set_bit(TX_LNA_GAIN, &dev->flags);
1315		break;
1316	case  V4L2_CID_RF_TUNER_RF_GAIN:
1317		set_bit(TX_RF_GAIN, &dev->flags);
1318		break;
1319	default:
1320		dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
1321			ctrl->id, ctrl->name);
1322		ret = -EINVAL;
1323		goto err;
1324	}
1325
1326	ret = hackrf_set_params(dev);
1327	if (ret)
1328		goto err;
1329
1330	return 0;
1331err:
1332	dev_dbg(&intf->dev, "failed=%d\n", ret);
1333	return ret;
1334}
1335
1336static const struct v4l2_ctrl_ops hackrf_ctrl_ops_rx = {
1337	.s_ctrl = hackrf_s_ctrl_rx,
1338};
1339
1340static const struct v4l2_ctrl_ops hackrf_ctrl_ops_tx = {
1341	.s_ctrl = hackrf_s_ctrl_tx,
1342};
1343
1344static int hackrf_probe(struct usb_interface *intf,
1345		const struct usb_device_id *id)
1346{
1347	struct hackrf_dev *dev;
1348	int ret;
1349	u8 u8tmp, buf[BUF_SIZE];
1350
1351	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1352	if (!dev) {
1353		ret = -ENOMEM;
1354		goto err;
1355	}
1356
1357	mutex_init(&dev->v4l2_lock);
1358	mutex_init(&dev->vb_queue_lock);
1359	spin_lock_init(&dev->buffer_list_lock);
1360	INIT_LIST_HEAD(&dev->rx_buffer_list);
1361	INIT_LIST_HEAD(&dev->tx_buffer_list);
1362	dev->intf = intf;
1363	dev->dev = &intf->dev;
1364	dev->udev = interface_to_usbdev(intf);
1365	dev->pixelformat = formats[0].pixelformat;
1366	dev->buffersize = formats[0].buffersize;
1367	dev->f_adc = bands_adc_dac[0].rangelow;
1368	dev->f_dac = bands_adc_dac[0].rangelow;
1369	dev->f_rx = bands_rx_tx[0].rangelow;
1370	dev->f_tx = bands_rx_tx[0].rangelow;
1371	set_bit(RX_ADC_FREQUENCY, &dev->flags);
1372	set_bit(TX_DAC_FREQUENCY, &dev->flags);
1373	set_bit(RX_RF_FREQUENCY, &dev->flags);
1374	set_bit(TX_RF_FREQUENCY, &dev->flags);
1375
1376	/* Detect device */
1377	ret = hackrf_ctrl_msg(dev, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
1378	if (ret == 0)
1379		ret = hackrf_ctrl_msg(dev, CMD_VERSION_STRING_READ, 0, 0,
1380				buf, BUF_SIZE);
1381	if (ret) {
1382		dev_err(dev->dev, "Could not detect board\n");
1383		goto err_kfree;
1384	}
1385
1386	buf[BUF_SIZE - 1] = '\0';
1387	dev_info(dev->dev, "Board ID: %02x\n", u8tmp);
1388	dev_info(dev->dev, "Firmware version: %s\n", buf);
1389
1390	/* Init vb2 queue structure for receiver */
1391	dev->rx_vb2_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1392	dev->rx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1393				     VB2_READ;
1394	dev->rx_vb2_queue.ops = &hackrf_vb2_ops;
1395	dev->rx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1396	dev->rx_vb2_queue.drv_priv = dev;
1397	dev->rx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1398	dev->rx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1399	dev->rx_vb2_queue.lock = &dev->vb_queue_lock;
1400	ret = vb2_queue_init(&dev->rx_vb2_queue);
1401	if (ret) {
1402		dev_err(dev->dev, "Could not initialize rx vb2 queue\n");
1403		goto err_kfree;
1404	}
1405
1406	/* Init vb2 queue structure for transmitter */
1407	dev->tx_vb2_queue.type = V4L2_BUF_TYPE_SDR_OUTPUT;
1408	dev->tx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1409				     VB2_WRITE;
1410	dev->tx_vb2_queue.ops = &hackrf_vb2_ops;
1411	dev->tx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1412	dev->tx_vb2_queue.drv_priv = dev;
1413	dev->tx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1414	dev->tx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1415	dev->tx_vb2_queue.lock = &dev->vb_queue_lock;
1416	ret = vb2_queue_init(&dev->tx_vb2_queue);
1417	if (ret) {
1418		dev_err(dev->dev, "Could not initialize tx vb2 queue\n");
1419		goto err_kfree;
1420	}
1421
1422	/* Register controls for receiver */
1423	v4l2_ctrl_handler_init(&dev->rx_ctrl_handler, 5);
1424	dev->rx_bandwidth_auto = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1425		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1426		0, 1, 0, 1);
1427	dev->rx_bandwidth = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1428		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH,
1429		1750000, 28000000, 50000, 1750000);
1430	v4l2_ctrl_auto_cluster(2, &dev->rx_bandwidth_auto, 0, false);
1431	dev->rx_rf_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1432		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 12, 12, 0);
1433	dev->rx_lna_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1434		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 40, 8, 0);
1435	dev->rx_if_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1436		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_IF_GAIN, 0, 62, 2, 0);
1437	if (dev->rx_ctrl_handler.error) {
1438		ret = dev->rx_ctrl_handler.error;
1439		dev_err(dev->dev, "Could not initialize controls\n");
1440		goto err_v4l2_ctrl_handler_free_rx;
1441	}
1442	v4l2_ctrl_grab(dev->rx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1443	v4l2_ctrl_handler_setup(&dev->rx_ctrl_handler);
1444
1445	/* Register controls for transmitter */
1446	v4l2_ctrl_handler_init(&dev->tx_ctrl_handler, 4);
1447	dev->tx_bandwidth_auto = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1448		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1449		0, 1, 0, 1);
1450	dev->tx_bandwidth = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1451		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH,
1452		1750000, 28000000, 50000, 1750000);
1453	v4l2_ctrl_auto_cluster(2, &dev->tx_bandwidth_auto, 0, false);
1454	dev->tx_lna_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1455		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 47, 1, 0);
1456	dev->tx_rf_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1457		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 15, 15, 0);
1458	if (dev->tx_ctrl_handler.error) {
1459		ret = dev->tx_ctrl_handler.error;
1460		dev_err(dev->dev, "Could not initialize controls\n");
1461		goto err_v4l2_ctrl_handler_free_tx;
1462	}
1463	v4l2_ctrl_grab(dev->tx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1464	v4l2_ctrl_handler_setup(&dev->tx_ctrl_handler);
1465
1466	/* Register the v4l2_device structure */
1467	dev->v4l2_dev.release = hackrf_video_release;
1468	ret = v4l2_device_register(&intf->dev, &dev->v4l2_dev);
1469	if (ret) {
1470		dev_err(dev->dev, "Failed to register v4l2-device (%d)\n", ret);
1471		goto err_v4l2_ctrl_handler_free_tx;
1472	}
1473
1474	/* Init video_device structure for receiver */
1475	dev->rx_vdev = hackrf_template;
1476	dev->rx_vdev.queue = &dev->rx_vb2_queue;
 
1477	dev->rx_vdev.v4l2_dev = &dev->v4l2_dev;
1478	dev->rx_vdev.ctrl_handler = &dev->rx_ctrl_handler;
1479	dev->rx_vdev.lock = &dev->v4l2_lock;
1480	dev->rx_vdev.vfl_dir = VFL_DIR_RX;
1481	dev->rx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1482				   V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER;
1483	video_set_drvdata(&dev->rx_vdev, dev);
1484	ret = video_register_device(&dev->rx_vdev, VFL_TYPE_SDR, -1);
1485	if (ret) {
1486		dev_err(dev->dev,
1487			"Failed to register as video device (%d)\n", ret);
1488		goto err_v4l2_device_unregister;
1489	}
1490	dev_info(dev->dev, "Registered as %s\n",
1491		 video_device_node_name(&dev->rx_vdev));
1492
1493	/* Init video_device structure for transmitter */
1494	dev->tx_vdev = hackrf_template;
1495	dev->tx_vdev.queue = &dev->tx_vb2_queue;
 
1496	dev->tx_vdev.v4l2_dev = &dev->v4l2_dev;
1497	dev->tx_vdev.ctrl_handler = &dev->tx_ctrl_handler;
1498	dev->tx_vdev.lock = &dev->v4l2_lock;
1499	dev->tx_vdev.vfl_dir = VFL_DIR_TX;
1500	dev->tx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1501				   V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR;
1502	video_set_drvdata(&dev->tx_vdev, dev);
1503	ret = video_register_device(&dev->tx_vdev, VFL_TYPE_SDR, -1);
1504	if (ret) {
1505		dev_err(dev->dev,
1506			"Failed to register as video device (%d)\n", ret);
1507		goto err_video_unregister_device_rx;
1508	}
1509	dev_info(dev->dev, "Registered as %s\n",
1510		 video_device_node_name(&dev->tx_vdev));
1511
1512	dev_notice(dev->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
1513	return 0;
1514err_video_unregister_device_rx:
1515	video_unregister_device(&dev->rx_vdev);
1516err_v4l2_device_unregister:
1517	v4l2_device_unregister(&dev->v4l2_dev);
1518err_v4l2_ctrl_handler_free_tx:
1519	v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
1520err_v4l2_ctrl_handler_free_rx:
1521	v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
1522err_kfree:
1523	kfree(dev);
1524err:
1525	dev_dbg(&intf->dev, "failed=%d\n", ret);
1526	return ret;
1527}
1528
1529/* USB device ID list */
1530static const struct usb_device_id hackrf_id_table[] = {
1531	{ USB_DEVICE(0x1d50, 0x6089) }, /* HackRF One */
1532	{ }
1533};
1534MODULE_DEVICE_TABLE(usb, hackrf_id_table);
1535
1536/* USB subsystem interface */
1537static struct usb_driver hackrf_driver = {
1538	.name                     = KBUILD_MODNAME,
1539	.probe                    = hackrf_probe,
1540	.disconnect               = hackrf_disconnect,
1541	.id_table                 = hackrf_id_table,
1542};
1543
1544module_usb_driver(hackrf_driver);
1545
1546MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1547MODULE_DESCRIPTION("HackRF");
1548MODULE_LICENSE("GPL");
v5.4
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * HackRF driver
   4 *
   5 * Copyright (C) 2014 Antti Palosaari <crope@iki.fi>
   6 */
   7
   8#include <linux/module.h>
   9#include <linux/slab.h>
  10#include <linux/usb.h>
  11#include <media/v4l2-device.h>
  12#include <media/v4l2-ioctl.h>
  13#include <media/v4l2-ctrls.h>
  14#include <media/v4l2-event.h>
  15#include <media/videobuf2-v4l2.h>
  16#include <media/videobuf2-vmalloc.h>
  17
  18/*
  19 * Used Avago MGA-81563 RF amplifier could be destroyed pretty easily with too
  20 * strong signal or transmitting to bad antenna.
  21 * Set RF gain control to 'grabbed' state by default for sure.
  22 */
  23static bool hackrf_enable_rf_gain_ctrl;
  24module_param_named(enable_rf_gain_ctrl, hackrf_enable_rf_gain_ctrl, bool, 0644);
  25MODULE_PARM_DESC(enable_rf_gain_ctrl, "enable RX/TX RF amplifier control (warn: could damage amplifier)");
  26
  27/* HackRF USB API commands (from HackRF Library) */
  28enum {
  29	CMD_SET_TRANSCEIVER_MODE           = 0x01,
  30	CMD_SAMPLE_RATE_SET                = 0x06,
  31	CMD_BASEBAND_FILTER_BANDWIDTH_SET  = 0x07,
  32	CMD_BOARD_ID_READ                  = 0x0e,
  33	CMD_VERSION_STRING_READ            = 0x0f,
  34	CMD_SET_FREQ                       = 0x10,
  35	CMD_AMP_ENABLE                     = 0x11,
  36	CMD_SET_LNA_GAIN                   = 0x13,
  37	CMD_SET_VGA_GAIN                   = 0x14,
  38	CMD_SET_TXVGA_GAIN                 = 0x15,
  39};
  40
  41/*
  42 *       bEndpointAddress     0x81  EP 1 IN
  43 *         Transfer Type            Bulk
  44 *       wMaxPacketSize     0x0200  1x 512 bytes
  45 */
  46#define MAX_BULK_BUFS            (6)
  47#define BULK_BUFFER_SIZE         (128 * 512)
  48
  49static const struct v4l2_frequency_band bands_adc_dac[] = {
  50	{
  51		.tuner = 0,
  52		.type = V4L2_TUNER_SDR,
  53		.index = 0,
  54		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
  55		.rangelow   =   200000,
  56		.rangehigh  = 24000000,
  57	},
  58};
  59
  60static const struct v4l2_frequency_band bands_rx_tx[] = {
  61	{
  62		.tuner = 1,
  63		.type = V4L2_TUNER_RF,
  64		.index = 0,
  65		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
  66		.rangelow   =          1,
  67		.rangehigh  = 4294967294LL, /* max u32, hw goes over 7GHz */
  68	},
  69};
  70
  71/* stream formats */
  72struct hackrf_format {
  73	u32	pixelformat;
  74	u32	buffersize;
  75};
  76
  77/* format descriptions for capture and preview */
  78static struct hackrf_format formats[] = {
  79	{
  80		.pixelformat	= V4L2_SDR_FMT_CS8,
  81		.buffersize	= BULK_BUFFER_SIZE,
  82	},
  83};
  84
  85static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
  86
  87/* intermediate buffers with raw data from the USB device */
  88struct hackrf_buffer {
  89	struct vb2_v4l2_buffer vb;
  90	struct list_head list;
  91};
  92
  93struct hackrf_dev {
  94#define USB_STATE_URB_BUF                1 /* XXX: set manually */
  95#define RX_ON                            4
  96#define TX_ON                            5
  97#define RX_ADC_FREQUENCY                11
  98#define TX_DAC_FREQUENCY                12
  99#define RX_BANDWIDTH                    13
 100#define TX_BANDWIDTH                    14
 101#define RX_RF_FREQUENCY                 15
 102#define TX_RF_FREQUENCY                 16
 103#define RX_RF_GAIN                      17
 104#define TX_RF_GAIN                      18
 105#define RX_IF_GAIN                      19
 106#define RX_LNA_GAIN                     20
 107#define TX_LNA_GAIN                     21
 108	unsigned long flags;
 109
 110	struct usb_interface *intf;
 111	struct device *dev;
 112	struct usb_device *udev;
 113	struct video_device rx_vdev;
 114	struct video_device tx_vdev;
 115	struct v4l2_device v4l2_dev;
 116
 117	/* videobuf2 queue and queued buffers list */
 118	struct vb2_queue rx_vb2_queue;
 119	struct vb2_queue tx_vb2_queue;
 120	struct list_head rx_buffer_list;
 121	struct list_head tx_buffer_list;
 122	spinlock_t buffer_list_lock; /* Protects buffer_list */
 123	unsigned int sequence;	     /* Buffer sequence counter */
 124	unsigned int vb_full;        /* vb is full and packets dropped */
 125	unsigned int vb_empty;       /* vb is empty and packets dropped */
 126
 127	/* Note if taking both locks v4l2_lock must always be locked first! */
 128	struct mutex v4l2_lock;      /* Protects everything else */
 129	struct mutex vb_queue_lock;  /* Protects vb_queue */
 130
 131	struct urb     *urb_list[MAX_BULK_BUFS];
 132	int            buf_num;
 133	unsigned long  buf_size;
 134	u8             *buf_list[MAX_BULK_BUFS];
 135	dma_addr_t     dma_addr[MAX_BULK_BUFS];
 136	int            urbs_initialized;
 137	int            urbs_submitted;
 138
 139	/* USB control message buffer */
 140	#define BUF_SIZE 24
 141	u8 buf[BUF_SIZE];
 142
 143	/* Current configuration */
 144	unsigned int f_adc;
 145	unsigned int f_dac;
 146	unsigned int f_rx;
 147	unsigned int f_tx;
 148	u32 pixelformat;
 149	u32 buffersize;
 150
 151	/* Controls */
 152	struct v4l2_ctrl_handler rx_ctrl_handler;
 153	struct v4l2_ctrl *rx_bandwidth_auto;
 154	struct v4l2_ctrl *rx_bandwidth;
 155	struct v4l2_ctrl *rx_rf_gain;
 156	struct v4l2_ctrl *rx_lna_gain;
 157	struct v4l2_ctrl *rx_if_gain;
 158	struct v4l2_ctrl_handler tx_ctrl_handler;
 159	struct v4l2_ctrl *tx_bandwidth_auto;
 160	struct v4l2_ctrl *tx_bandwidth;
 161	struct v4l2_ctrl *tx_rf_gain;
 162	struct v4l2_ctrl *tx_lna_gain;
 163
 164	/* Sample rate calc */
 165	unsigned long jiffies_next;
 166	unsigned int sample;
 167	unsigned int sample_measured;
 168};
 169
 170#define hackrf_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
 171	char *_direction; \
 172	if (_t & USB_DIR_IN) \
 173		_direction = "<<<"; \
 174	else \
 175		_direction = ">>>"; \
 176	dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
 177			_t, _r, _v & 0xff, _v >> 8, _i & 0xff, \
 178			_i >> 8, _l & 0xff, _l >> 8, _direction, _l, _b); \
 179}
 180
 181/* execute firmware command */
 182static int hackrf_ctrl_msg(struct hackrf_dev *dev, u8 request, u16 value,
 183		u16 index, u8 *data, u16 size)
 184{
 185	int ret;
 186	unsigned int pipe;
 187	u8 requesttype;
 188
 189	switch (request) {
 190	case CMD_SET_TRANSCEIVER_MODE:
 191	case CMD_SET_FREQ:
 192	case CMD_AMP_ENABLE:
 193	case CMD_SAMPLE_RATE_SET:
 194	case CMD_BASEBAND_FILTER_BANDWIDTH_SET:
 195		pipe = usb_sndctrlpipe(dev->udev, 0);
 196		requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
 197		break;
 198	case CMD_BOARD_ID_READ:
 199	case CMD_VERSION_STRING_READ:
 200	case CMD_SET_LNA_GAIN:
 201	case CMD_SET_VGA_GAIN:
 202	case CMD_SET_TXVGA_GAIN:
 203		pipe = usb_rcvctrlpipe(dev->udev, 0);
 204		requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
 205		break;
 206	default:
 207		dev_err(dev->dev, "Unknown command %02x\n", request);
 208		ret = -EINVAL;
 209		goto err;
 210	}
 211
 212	/* write request */
 213	if (!(requesttype & USB_DIR_IN))
 214		memcpy(dev->buf, data, size);
 215
 216	ret = usb_control_msg(dev->udev, pipe, request, requesttype, value,
 217			index, dev->buf, size, 1000);
 218	hackrf_dbg_usb_control_msg(dev->dev, request, requesttype, value,
 219			index, dev->buf, size);
 220	if (ret < 0) {
 221		dev_err(dev->dev, "usb_control_msg() failed %d request %02x\n",
 222				ret, request);
 223		goto err;
 224	}
 225
 226	/* read request */
 227	if (requesttype & USB_DIR_IN)
 228		memcpy(data, dev->buf, size);
 229
 230	return 0;
 231err:
 232	return ret;
 233}
 234
 235static int hackrf_set_params(struct hackrf_dev *dev)
 236{
 237	struct usb_interface *intf = dev->intf;
 238	int ret, i;
 239	u8 buf[8], u8tmp;
 240	unsigned int uitmp, uitmp1, uitmp2;
 241	const bool rx = test_bit(RX_ON, &dev->flags);
 242	const bool tx = test_bit(TX_ON, &dev->flags);
 243	static const struct {
 244		u32 freq;
 245	} bandwidth_lut[] = {
 246		{ 1750000}, /*  1.75 MHz */
 247		{ 2500000}, /*  2.5  MHz */
 248		{ 3500000}, /*  3.5  MHz */
 249		{ 5000000}, /*  5    MHz */
 250		{ 5500000}, /*  5.5  MHz */
 251		{ 6000000}, /*  6    MHz */
 252		{ 7000000}, /*  7    MHz */
 253		{ 8000000}, /*  8    MHz */
 254		{ 9000000}, /*  9    MHz */
 255		{10000000}, /* 10    MHz */
 256		{12000000}, /* 12    MHz */
 257		{14000000}, /* 14    MHz */
 258		{15000000}, /* 15    MHz */
 259		{20000000}, /* 20    MHz */
 260		{24000000}, /* 24    MHz */
 261		{28000000}, /* 28    MHz */
 262	};
 263
 264	if (!rx && !tx) {
 265		dev_dbg(&intf->dev, "device is sleeping\n");
 266		return 0;
 267	}
 268
 269	/* ADC / DAC frequency */
 270	if (rx && test_and_clear_bit(RX_ADC_FREQUENCY, &dev->flags)) {
 271		dev_dbg(&intf->dev, "RX ADC frequency=%u Hz\n", dev->f_adc);
 272		uitmp1 = dev->f_adc;
 273		uitmp2 = 1;
 274		set_bit(TX_DAC_FREQUENCY, &dev->flags);
 275	} else if (tx && test_and_clear_bit(TX_DAC_FREQUENCY, &dev->flags)) {
 276		dev_dbg(&intf->dev, "TX DAC frequency=%u Hz\n", dev->f_dac);
 277		uitmp1 = dev->f_dac;
 278		uitmp2 = 1;
 279		set_bit(RX_ADC_FREQUENCY, &dev->flags);
 280	} else {
 281		uitmp1 = uitmp2 = 0;
 282	}
 283	if (uitmp1 || uitmp2) {
 284		buf[0] = (uitmp1 >>  0) & 0xff;
 285		buf[1] = (uitmp1 >>  8) & 0xff;
 286		buf[2] = (uitmp1 >> 16) & 0xff;
 287		buf[3] = (uitmp1 >> 24) & 0xff;
 288		buf[4] = (uitmp2 >>  0) & 0xff;
 289		buf[5] = (uitmp2 >>  8) & 0xff;
 290		buf[6] = (uitmp2 >> 16) & 0xff;
 291		buf[7] = (uitmp2 >> 24) & 0xff;
 292		ret = hackrf_ctrl_msg(dev, CMD_SAMPLE_RATE_SET, 0, 0, buf, 8);
 293		if (ret)
 294			goto err;
 295	}
 296
 297	/* bandwidth */
 298	if (rx && test_and_clear_bit(RX_BANDWIDTH, &dev->flags)) {
 299		if (dev->rx_bandwidth_auto->val == true)
 300			uitmp = dev->f_adc;
 301		else
 302			uitmp = dev->rx_bandwidth->val;
 303
 304		for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
 305			if (uitmp <= bandwidth_lut[i].freq) {
 306				uitmp = bandwidth_lut[i].freq;
 307				break;
 308			}
 309		}
 310		dev->rx_bandwidth->val = uitmp;
 311		dev->rx_bandwidth->cur.val = uitmp;
 312		dev_dbg(&intf->dev, "RX bandwidth selected=%u\n", uitmp);
 313		set_bit(TX_BANDWIDTH, &dev->flags);
 314	} else if (tx && test_and_clear_bit(TX_BANDWIDTH, &dev->flags)) {
 315		if (dev->tx_bandwidth_auto->val == true)
 316			uitmp = dev->f_dac;
 317		else
 318			uitmp = dev->tx_bandwidth->val;
 319
 320		for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
 321			if (uitmp <= bandwidth_lut[i].freq) {
 322				uitmp = bandwidth_lut[i].freq;
 323				break;
 324			}
 325		}
 326		dev->tx_bandwidth->val = uitmp;
 327		dev->tx_bandwidth->cur.val = uitmp;
 328		dev_dbg(&intf->dev, "TX bandwidth selected=%u\n", uitmp);
 329		set_bit(RX_BANDWIDTH, &dev->flags);
 330	} else {
 331		uitmp = 0;
 332	}
 333	if (uitmp) {
 334		uitmp1 = uitmp2 = 0;
 335		uitmp1 |= ((uitmp >>  0) & 0xff) << 0;
 336		uitmp1 |= ((uitmp >>  8) & 0xff) << 8;
 337		uitmp2 |= ((uitmp >> 16) & 0xff) << 0;
 338		uitmp2 |= ((uitmp >> 24) & 0xff) << 8;
 339		ret = hackrf_ctrl_msg(dev, CMD_BASEBAND_FILTER_BANDWIDTH_SET,
 340				      uitmp1, uitmp2, NULL, 0);
 341		if (ret)
 342			goto err;
 343	}
 344
 345	/* RX / TX RF frequency */
 346	if (rx && test_and_clear_bit(RX_RF_FREQUENCY, &dev->flags)) {
 347		dev_dbg(&intf->dev, "RX RF frequency=%u Hz\n", dev->f_rx);
 348		uitmp1 = dev->f_rx / 1000000;
 349		uitmp2 = dev->f_rx % 1000000;
 350		set_bit(TX_RF_FREQUENCY, &dev->flags);
 351	} else if (tx && test_and_clear_bit(TX_RF_FREQUENCY, &dev->flags)) {
 352		dev_dbg(&intf->dev, "TX RF frequency=%u Hz\n", dev->f_tx);
 353		uitmp1 = dev->f_tx / 1000000;
 354		uitmp2 = dev->f_tx % 1000000;
 355		set_bit(RX_RF_FREQUENCY, &dev->flags);
 356	} else {
 357		uitmp1 = uitmp2 = 0;
 358	}
 359	if (uitmp1 || uitmp2) {
 360		buf[0] = (uitmp1 >>  0) & 0xff;
 361		buf[1] = (uitmp1 >>  8) & 0xff;
 362		buf[2] = (uitmp1 >> 16) & 0xff;
 363		buf[3] = (uitmp1 >> 24) & 0xff;
 364		buf[4] = (uitmp2 >>  0) & 0xff;
 365		buf[5] = (uitmp2 >>  8) & 0xff;
 366		buf[6] = (uitmp2 >> 16) & 0xff;
 367		buf[7] = (uitmp2 >> 24) & 0xff;
 368		ret = hackrf_ctrl_msg(dev, CMD_SET_FREQ, 0, 0, buf, 8);
 369		if (ret)
 370			goto err;
 371	}
 372
 373	/* RX RF gain */
 374	if (rx && test_and_clear_bit(RX_RF_GAIN, &dev->flags)) {
 375		dev_dbg(&intf->dev, "RX RF gain val=%d->%d\n",
 376			dev->rx_rf_gain->cur.val, dev->rx_rf_gain->val);
 377
 378		u8tmp = (dev->rx_rf_gain->val) ? 1 : 0;
 379		ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
 380		if (ret)
 381			goto err;
 382		set_bit(TX_RF_GAIN, &dev->flags);
 383	}
 384
 385	/* TX RF gain */
 386	if (tx && test_and_clear_bit(TX_RF_GAIN, &dev->flags)) {
 387		dev_dbg(&intf->dev, "TX RF gain val=%d->%d\n",
 388			dev->tx_rf_gain->cur.val, dev->tx_rf_gain->val);
 389
 390		u8tmp = (dev->tx_rf_gain->val) ? 1 : 0;
 391		ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
 392		if (ret)
 393			goto err;
 394		set_bit(RX_RF_GAIN, &dev->flags);
 395	}
 396
 397	/* RX LNA gain */
 398	if (rx && test_and_clear_bit(RX_LNA_GAIN, &dev->flags)) {
 399		dev_dbg(dev->dev, "RX LNA gain val=%d->%d\n",
 400			dev->rx_lna_gain->cur.val, dev->rx_lna_gain->val);
 401
 402		ret = hackrf_ctrl_msg(dev, CMD_SET_LNA_GAIN, 0,
 403				      dev->rx_lna_gain->val, &u8tmp, 1);
 404		if (ret)
 405			goto err;
 406	}
 407
 408	/* RX IF gain */
 409	if (rx && test_and_clear_bit(RX_IF_GAIN, &dev->flags)) {
 410		dev_dbg(&intf->dev, "IF gain val=%d->%d\n",
 411			dev->rx_if_gain->cur.val, dev->rx_if_gain->val);
 412
 413		ret = hackrf_ctrl_msg(dev, CMD_SET_VGA_GAIN, 0,
 414				      dev->rx_if_gain->val, &u8tmp, 1);
 415		if (ret)
 416			goto err;
 417	}
 418
 419	/* TX LNA gain */
 420	if (tx && test_and_clear_bit(TX_LNA_GAIN, &dev->flags)) {
 421		dev_dbg(&intf->dev, "TX LNA gain val=%d->%d\n",
 422			dev->tx_lna_gain->cur.val, dev->tx_lna_gain->val);
 423
 424		ret = hackrf_ctrl_msg(dev, CMD_SET_TXVGA_GAIN, 0,
 425				      dev->tx_lna_gain->val, &u8tmp, 1);
 426		if (ret)
 427			goto err;
 428	}
 429
 430	return 0;
 431err:
 432	dev_dbg(&intf->dev, "failed=%d\n", ret);
 433	return ret;
 434}
 435
 436/* Private functions */
 437static struct hackrf_buffer *hackrf_get_next_buffer(struct hackrf_dev *dev,
 438						    struct list_head *buffer_list)
 439{
 440	unsigned long flags;
 441	struct hackrf_buffer *buffer = NULL;
 442
 443	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 444	if (list_empty(buffer_list))
 445		goto leave;
 446
 447	buffer = list_entry(buffer_list->next, struct hackrf_buffer, list);
 448	list_del(&buffer->list);
 449leave:
 450	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 451	return buffer;
 452}
 453
 454static void hackrf_copy_stream(struct hackrf_dev *dev, void *dst, void *src,
 455			       unsigned int src_len)
 456{
 457	memcpy(dst, src, src_len);
 458
 459	/* calculate sample rate and output it in 10 seconds intervals */
 460	if (unlikely(time_is_before_jiffies(dev->jiffies_next))) {
 461		#define MSECS 10000UL
 462		unsigned int msecs = jiffies_to_msecs(jiffies -
 463				dev->jiffies_next + msecs_to_jiffies(MSECS));
 464		unsigned int samples = dev->sample - dev->sample_measured;
 465
 466		dev->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
 467		dev->sample_measured = dev->sample;
 468		dev_dbg(dev->dev, "slen=%u samples=%u msecs=%u sample rate=%lu\n",
 469				src_len, samples, msecs,
 470				samples * 1000UL / msecs);
 471	}
 472
 473	/* total number of samples */
 474	dev->sample += src_len / 2;
 475}
 476
 477/*
 478 * This gets called for the bulk stream pipe. This is done in interrupt
 479 * time, so it has to be fast, not crash, and not stall. Neat.
 480 */
 481static void hackrf_urb_complete_in(struct urb *urb)
 482{
 483	struct hackrf_dev *dev = urb->context;
 484	struct usb_interface *intf = dev->intf;
 485	struct hackrf_buffer *buffer;
 486	unsigned int len;
 487
 488	dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
 489			    urb->actual_length, urb->transfer_buffer_length);
 490
 491	switch (urb->status) {
 492	case 0:             /* success */
 493	case -ETIMEDOUT:    /* NAK */
 494		break;
 495	case -ECONNRESET:   /* kill */
 496	case -ENOENT:
 497	case -ESHUTDOWN:
 498		return;
 499	default:            /* error */
 500		dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
 501		goto exit_usb_submit_urb;
 502	}
 503
 504	/* get buffer to write */
 505	buffer = hackrf_get_next_buffer(dev, &dev->rx_buffer_list);
 506	if (unlikely(buffer == NULL)) {
 507		dev->vb_full++;
 508		dev_notice_ratelimited(&intf->dev,
 509				       "buffer is full - %u packets dropped\n",
 510				       dev->vb_full);
 511		goto exit_usb_submit_urb;
 512	}
 513
 514	len = min_t(unsigned long, vb2_plane_size(&buffer->vb.vb2_buf, 0),
 515		    urb->actual_length);
 516	hackrf_copy_stream(dev, vb2_plane_vaddr(&buffer->vb.vb2_buf, 0),
 517		    urb->transfer_buffer, len);
 518	vb2_set_plane_payload(&buffer->vb.vb2_buf, 0, len);
 519	buffer->vb.sequence = dev->sequence++;
 520	buffer->vb.vb2_buf.timestamp = ktime_get_ns();
 521	vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
 522exit_usb_submit_urb:
 523	usb_submit_urb(urb, GFP_ATOMIC);
 524}
 525
 526static void hackrf_urb_complete_out(struct urb *urb)
 527{
 528	struct hackrf_dev *dev = urb->context;
 529	struct usb_interface *intf = dev->intf;
 530	struct hackrf_buffer *buffer;
 531	unsigned int len;
 532
 533	dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
 534			    urb->actual_length, urb->transfer_buffer_length);
 535
 536	switch (urb->status) {
 537	case 0:             /* success */
 538	case -ETIMEDOUT:    /* NAK */
 539		break;
 540	case -ECONNRESET:   /* kill */
 541	case -ENOENT:
 542	case -ESHUTDOWN:
 543		return;
 544	default:            /* error */
 545		dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
 546	}
 547
 548	/* get buffer to read */
 549	buffer = hackrf_get_next_buffer(dev, &dev->tx_buffer_list);
 550	if (unlikely(buffer == NULL)) {
 551		dev->vb_empty++;
 552		dev_notice_ratelimited(&intf->dev,
 553				       "buffer is empty - %u packets dropped\n",
 554				       dev->vb_empty);
 555		urb->actual_length = 0;
 556		goto exit_usb_submit_urb;
 557	}
 558
 559	len = min_t(unsigned long, urb->transfer_buffer_length,
 560		    vb2_get_plane_payload(&buffer->vb.vb2_buf, 0));
 561	hackrf_copy_stream(dev, urb->transfer_buffer,
 562			   vb2_plane_vaddr(&buffer->vb.vb2_buf, 0), len);
 563	urb->actual_length = len;
 564	buffer->vb.sequence = dev->sequence++;
 565	buffer->vb.vb2_buf.timestamp = ktime_get_ns();
 566	vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
 567exit_usb_submit_urb:
 568	usb_submit_urb(urb, GFP_ATOMIC);
 569}
 570
 571static int hackrf_kill_urbs(struct hackrf_dev *dev)
 572{
 573	int i;
 574
 575	for (i = dev->urbs_submitted - 1; i >= 0; i--) {
 576		dev_dbg(dev->dev, "kill urb=%d\n", i);
 577		/* stop the URB */
 578		usb_kill_urb(dev->urb_list[i]);
 579	}
 580	dev->urbs_submitted = 0;
 581
 582	return 0;
 583}
 584
 585static int hackrf_submit_urbs(struct hackrf_dev *dev)
 586{
 587	int i, ret;
 588
 589	for (i = 0; i < dev->urbs_initialized; i++) {
 590		dev_dbg(dev->dev, "submit urb=%d\n", i);
 591		ret = usb_submit_urb(dev->urb_list[i], GFP_KERNEL);
 592		if (ret) {
 593			dev_err(dev->dev, "Could not submit URB no. %d - get them all back\n",
 594					i);
 595			hackrf_kill_urbs(dev);
 596			return ret;
 597		}
 598		dev->urbs_submitted++;
 599	}
 600
 601	return 0;
 602}
 603
 604static int hackrf_free_stream_bufs(struct hackrf_dev *dev)
 605{
 606	if (dev->flags & USB_STATE_URB_BUF) {
 607		while (dev->buf_num) {
 608			dev->buf_num--;
 609			dev_dbg(dev->dev, "free buf=%d\n", dev->buf_num);
 610			usb_free_coherent(dev->udev, dev->buf_size,
 611					  dev->buf_list[dev->buf_num],
 612					  dev->dma_addr[dev->buf_num]);
 613		}
 614	}
 615	dev->flags &= ~USB_STATE_URB_BUF;
 616
 617	return 0;
 618}
 619
 620static int hackrf_alloc_stream_bufs(struct hackrf_dev *dev)
 621{
 622	dev->buf_num = 0;
 623	dev->buf_size = BULK_BUFFER_SIZE;
 624
 625	dev_dbg(dev->dev, "all in all I will use %u bytes for streaming\n",
 626			MAX_BULK_BUFS * BULK_BUFFER_SIZE);
 627
 628	for (dev->buf_num = 0; dev->buf_num < MAX_BULK_BUFS; dev->buf_num++) {
 629		dev->buf_list[dev->buf_num] = usb_alloc_coherent(dev->udev,
 630				BULK_BUFFER_SIZE, GFP_KERNEL,
 631				&dev->dma_addr[dev->buf_num]);
 632		if (!dev->buf_list[dev->buf_num]) {
 633			dev_dbg(dev->dev, "alloc buf=%d failed\n",
 634					dev->buf_num);
 635			hackrf_free_stream_bufs(dev);
 636			return -ENOMEM;
 637		}
 638
 639		dev_dbg(dev->dev, "alloc buf=%d %p (dma %llu)\n", dev->buf_num,
 640				dev->buf_list[dev->buf_num],
 641				(long long)dev->dma_addr[dev->buf_num]);
 642		dev->flags |= USB_STATE_URB_BUF;
 643	}
 644
 645	return 0;
 646}
 647
 648static int hackrf_free_urbs(struct hackrf_dev *dev)
 649{
 650	int i;
 651
 652	hackrf_kill_urbs(dev);
 653
 654	for (i = dev->urbs_initialized - 1; i >= 0; i--) {
 655		if (dev->urb_list[i]) {
 656			dev_dbg(dev->dev, "free urb=%d\n", i);
 657			/* free the URBs */
 658			usb_free_urb(dev->urb_list[i]);
 659		}
 660	}
 661	dev->urbs_initialized = 0;
 662
 663	return 0;
 664}
 665
 666static int hackrf_alloc_urbs(struct hackrf_dev *dev, bool rcv)
 667{
 668	int i, j;
 669	unsigned int pipe;
 670	usb_complete_t complete;
 671
 672	if (rcv) {
 673		pipe = usb_rcvbulkpipe(dev->udev, 0x81);
 674		complete = &hackrf_urb_complete_in;
 675	} else {
 676		pipe = usb_sndbulkpipe(dev->udev, 0x02);
 677		complete = &hackrf_urb_complete_out;
 678	}
 679
 680	/* allocate the URBs */
 681	for (i = 0; i < MAX_BULK_BUFS; i++) {
 682		dev_dbg(dev->dev, "alloc urb=%d\n", i);
 683		dev->urb_list[i] = usb_alloc_urb(0, GFP_KERNEL);
 684		if (!dev->urb_list[i]) {
 685			for (j = 0; j < i; j++)
 686				usb_free_urb(dev->urb_list[j]);
 687			return -ENOMEM;
 688		}
 689		usb_fill_bulk_urb(dev->urb_list[i],
 690				dev->udev,
 691				pipe,
 692				dev->buf_list[i],
 693				BULK_BUFFER_SIZE,
 694				complete, dev);
 695
 696		dev->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
 697		dev->urb_list[i]->transfer_dma = dev->dma_addr[i];
 698		dev->urbs_initialized++;
 699	}
 700
 701	return 0;
 702}
 703
 704/* The user yanked out the cable... */
 705static void hackrf_disconnect(struct usb_interface *intf)
 706{
 707	struct v4l2_device *v = usb_get_intfdata(intf);
 708	struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
 709
 710	dev_dbg(dev->dev, "\n");
 711
 712	mutex_lock(&dev->vb_queue_lock);
 713	mutex_lock(&dev->v4l2_lock);
 714	/* No need to keep the urbs around after disconnection */
 715	dev->udev = NULL;
 716	v4l2_device_disconnect(&dev->v4l2_dev);
 717	video_unregister_device(&dev->tx_vdev);
 718	video_unregister_device(&dev->rx_vdev);
 719	mutex_unlock(&dev->v4l2_lock);
 720	mutex_unlock(&dev->vb_queue_lock);
 721
 722	v4l2_device_put(&dev->v4l2_dev);
 723}
 724
 725/* Videobuf2 operations */
 726static void hackrf_return_all_buffers(struct vb2_queue *vq,
 727				      enum vb2_buffer_state state)
 728{
 729	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 730	struct usb_interface *intf = dev->intf;
 731	struct hackrf_buffer *buffer, *node;
 732	struct list_head *buffer_list;
 733	unsigned long flags;
 734
 735	dev_dbg(&intf->dev, "\n");
 736
 737	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 738		buffer_list = &dev->rx_buffer_list;
 739	else
 740		buffer_list = &dev->tx_buffer_list;
 741
 742	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 743	list_for_each_entry_safe(buffer, node, buffer_list, list) {
 744		dev_dbg(&intf->dev, "list_for_each_entry_safe\n");
 745		vb2_buffer_done(&buffer->vb.vb2_buf, state);
 746		list_del(&buffer->list);
 747	}
 748	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 749}
 750
 751static int hackrf_queue_setup(struct vb2_queue *vq,
 752		unsigned int *nbuffers,
 753		unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[])
 754{
 755	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 
 756
 757	dev_dbg(dev->dev, "nbuffers=%d\n", *nbuffers);
 758
 759	/* Need at least 8 buffers */
 760	if (vq->num_buffers + *nbuffers < 8)
 761		*nbuffers = 8 - vq->num_buffers;
 762	*nplanes = 1;
 763	sizes[0] = PAGE_ALIGN(dev->buffersize);
 764
 765	dev_dbg(dev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
 766	return 0;
 767}
 768
 769static void hackrf_buf_queue(struct vb2_buffer *vb)
 770{
 771	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
 772	struct vb2_queue *vq = vb->vb2_queue;
 773	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 774	struct hackrf_buffer *buffer = container_of(vbuf, struct hackrf_buffer, vb);
 775	struct list_head *buffer_list;
 776	unsigned long flags;
 777
 778	dev_dbg_ratelimited(&dev->intf->dev, "\n");
 779
 780	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 781		buffer_list = &dev->rx_buffer_list;
 782	else
 783		buffer_list = &dev->tx_buffer_list;
 784
 785	spin_lock_irqsave(&dev->buffer_list_lock, flags);
 786	list_add_tail(&buffer->list, buffer_list);
 787	spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
 788}
 789
 790static int hackrf_start_streaming(struct vb2_queue *vq, unsigned int count)
 791{
 792	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 793	struct usb_interface *intf = dev->intf;
 794	int ret;
 795	unsigned int mode;
 796
 797	dev_dbg(&intf->dev, "count=%i\n", count);
 798
 799	mutex_lock(&dev->v4l2_lock);
 800
 801	/* Allow only RX or TX, not both same time */
 802	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE) {
 803		if (test_bit(TX_ON, &dev->flags)) {
 804			ret = -EBUSY;
 805			goto err_hackrf_return_all_buffers;
 806		}
 807
 808		mode = 1;
 809		set_bit(RX_ON, &dev->flags);
 810	} else {
 811		if (test_bit(RX_ON, &dev->flags)) {
 812			ret = -EBUSY;
 813			goto err_hackrf_return_all_buffers;
 814		}
 815
 816		mode = 2;
 817		set_bit(TX_ON, &dev->flags);
 818	}
 819
 820	dev->sequence = 0;
 821
 822	ret = hackrf_alloc_stream_bufs(dev);
 823	if (ret)
 824		goto err;
 825
 826	ret = hackrf_alloc_urbs(dev, (mode == 1));
 827	if (ret)
 828		goto err;
 829
 830	ret = hackrf_submit_urbs(dev);
 831	if (ret)
 832		goto err;
 833
 834	ret = hackrf_set_params(dev);
 835	if (ret)
 836		goto err;
 837
 838	/* start hardware streaming */
 839	ret = hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, mode, 0, NULL, 0);
 840	if (ret)
 841		goto err;
 842
 843	mutex_unlock(&dev->v4l2_lock);
 844
 845	return 0;
 846err:
 847	hackrf_kill_urbs(dev);
 848	hackrf_free_urbs(dev);
 849	hackrf_free_stream_bufs(dev);
 850	clear_bit(RX_ON, &dev->flags);
 851	clear_bit(TX_ON, &dev->flags);
 852err_hackrf_return_all_buffers:
 853	hackrf_return_all_buffers(vq, VB2_BUF_STATE_QUEUED);
 854	mutex_unlock(&dev->v4l2_lock);
 855	dev_dbg(&intf->dev, "failed=%d\n", ret);
 856	return ret;
 857}
 858
 859static void hackrf_stop_streaming(struct vb2_queue *vq)
 860{
 861	struct hackrf_dev *dev = vb2_get_drv_priv(vq);
 862	struct usb_interface *intf = dev->intf;
 863
 864	dev_dbg(&intf->dev, "\n");
 865
 866	mutex_lock(&dev->v4l2_lock);
 867
 868	/* stop hardware streaming */
 869	hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, 0, 0, NULL, 0);
 870
 871	hackrf_kill_urbs(dev);
 872	hackrf_free_urbs(dev);
 873	hackrf_free_stream_bufs(dev);
 874
 875	hackrf_return_all_buffers(vq, VB2_BUF_STATE_ERROR);
 876
 877	if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
 878		clear_bit(RX_ON, &dev->flags);
 879	else
 880		clear_bit(TX_ON, &dev->flags);
 881
 882	mutex_unlock(&dev->v4l2_lock);
 883}
 884
 885static const struct vb2_ops hackrf_vb2_ops = {
 886	.queue_setup            = hackrf_queue_setup,
 887	.buf_queue              = hackrf_buf_queue,
 888	.start_streaming        = hackrf_start_streaming,
 889	.stop_streaming         = hackrf_stop_streaming,
 890	.wait_prepare           = vb2_ops_wait_prepare,
 891	.wait_finish            = vb2_ops_wait_finish,
 892};
 893
 894static int hackrf_querycap(struct file *file, void *fh,
 895		struct v4l2_capability *cap)
 896{
 897	struct hackrf_dev *dev = video_drvdata(file);
 898	struct usb_interface *intf = dev->intf;
 899
 900	dev_dbg(&intf->dev, "\n");
 901
 902	cap->capabilities = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER |
 903			    V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR |
 904			    V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
 905			    V4L2_CAP_DEVICE_CAPS;
 906	strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
 907	strscpy(cap->card, dev->rx_vdev.name, sizeof(cap->card));
 908	usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
 909
 910	return 0;
 911}
 912
 913static int hackrf_s_fmt_sdr(struct file *file, void *priv,
 914			    struct v4l2_format *f)
 915{
 916	struct hackrf_dev *dev = video_drvdata(file);
 917	struct video_device *vdev = video_devdata(file);
 918	struct vb2_queue *q;
 919	int i;
 920
 921	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 922			(char *)&f->fmt.sdr.pixelformat);
 923
 924	if (vdev->vfl_dir == VFL_DIR_RX)
 925		q = &dev->rx_vb2_queue;
 926	else
 927		q = &dev->tx_vb2_queue;
 928
 929	if (vb2_is_busy(q))
 930		return -EBUSY;
 931
 932	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
 933	for (i = 0; i < NUM_FORMATS; i++) {
 934		if (f->fmt.sdr.pixelformat == formats[i].pixelformat) {
 935			dev->pixelformat = formats[i].pixelformat;
 936			dev->buffersize = formats[i].buffersize;
 937			f->fmt.sdr.buffersize = formats[i].buffersize;
 938			return 0;
 939		}
 940	}
 941
 942	dev->pixelformat = formats[0].pixelformat;
 943	dev->buffersize = formats[0].buffersize;
 944	f->fmt.sdr.pixelformat = formats[0].pixelformat;
 945	f->fmt.sdr.buffersize = formats[0].buffersize;
 946
 947	return 0;
 948}
 949
 950static int hackrf_g_fmt_sdr(struct file *file, void *priv,
 951			    struct v4l2_format *f)
 952{
 953	struct hackrf_dev *dev = video_drvdata(file);
 954
 955	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 956			(char *)&dev->pixelformat);
 957
 958	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
 959	f->fmt.sdr.pixelformat = dev->pixelformat;
 960	f->fmt.sdr.buffersize = dev->buffersize;
 961
 962	return 0;
 963}
 964
 965static int hackrf_try_fmt_sdr(struct file *file, void *priv,
 966			      struct v4l2_format *f)
 967{
 968	struct hackrf_dev *dev = video_drvdata(file);
 969	int i;
 970
 971	dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
 972			(char *)&f->fmt.sdr.pixelformat);
 973
 974	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
 975	for (i = 0; i < NUM_FORMATS; i++) {
 976		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
 977			f->fmt.sdr.buffersize = formats[i].buffersize;
 978			return 0;
 979		}
 980	}
 981
 982	f->fmt.sdr.pixelformat = formats[0].pixelformat;
 983	f->fmt.sdr.buffersize = formats[0].buffersize;
 984
 985	return 0;
 986}
 987
 988static int hackrf_enum_fmt_sdr(struct file *file, void *priv,
 989			       struct v4l2_fmtdesc *f)
 990{
 991	struct hackrf_dev *dev = video_drvdata(file);
 992
 993	dev_dbg(dev->dev, "index=%d\n", f->index);
 994
 995	if (f->index >= NUM_FORMATS)
 996		return -EINVAL;
 997
 998	f->pixelformat = formats[f->index].pixelformat;
 999
1000	return 0;
1001}
1002
1003static int hackrf_s_tuner(struct file *file, void *priv,
1004		const struct v4l2_tuner *v)
1005{
1006	struct hackrf_dev *dev = video_drvdata(file);
1007	int ret;
1008
1009	dev_dbg(dev->dev, "index=%d\n", v->index);
1010
1011	if (v->index == 0)
1012		ret = 0;
1013	else if (v->index == 1)
1014		ret = 0;
1015	else
1016		ret = -EINVAL;
1017
1018	return ret;
1019}
1020
1021static int hackrf_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
1022{
1023	struct hackrf_dev *dev = video_drvdata(file);
1024	int ret;
1025
1026	dev_dbg(dev->dev, "index=%d\n", v->index);
1027
1028	if (v->index == 0) {
1029		strscpy(v->name, "HackRF ADC", sizeof(v->name));
1030		v->type = V4L2_TUNER_SDR;
1031		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1032		v->rangelow  = bands_adc_dac[0].rangelow;
1033		v->rangehigh = bands_adc_dac[0].rangehigh;
1034		ret = 0;
1035	} else if (v->index == 1) {
1036		strscpy(v->name, "HackRF RF", sizeof(v->name));
1037		v->type = V4L2_TUNER_RF;
1038		v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1039		v->rangelow  = bands_rx_tx[0].rangelow;
1040		v->rangehigh = bands_rx_tx[0].rangehigh;
1041		ret = 0;
1042	} else {
1043		ret = -EINVAL;
1044	}
1045
1046	return ret;
1047}
1048
1049static int hackrf_s_modulator(struct file *file, void *fh,
1050			      const struct v4l2_modulator *a)
1051{
1052	struct hackrf_dev *dev = video_drvdata(file);
1053
1054	dev_dbg(dev->dev, "index=%d\n", a->index);
1055
1056	return a->index > 1 ? -EINVAL : 0;
1057}
1058
1059static int hackrf_g_modulator(struct file *file, void *fh,
1060			      struct v4l2_modulator *a)
1061{
1062	struct hackrf_dev *dev = video_drvdata(file);
1063	int ret;
1064
1065	dev_dbg(dev->dev, "index=%d\n", a->index);
1066
1067	if (a->index == 0) {
1068		strscpy(a->name, "HackRF DAC", sizeof(a->name));
1069		a->type = V4L2_TUNER_SDR;
1070		a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1071		a->rangelow  = bands_adc_dac[0].rangelow;
1072		a->rangehigh = bands_adc_dac[0].rangehigh;
1073		ret = 0;
1074	} else if (a->index == 1) {
1075		strscpy(a->name, "HackRF RF", sizeof(a->name));
1076		a->type = V4L2_TUNER_RF;
1077		a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
1078		a->rangelow  = bands_rx_tx[0].rangelow;
1079		a->rangehigh = bands_rx_tx[0].rangehigh;
1080		ret = 0;
1081	} else {
1082		ret = -EINVAL;
1083	}
1084
1085	return ret;
1086}
1087
1088static int hackrf_s_frequency(struct file *file, void *priv,
1089		const struct v4l2_frequency *f)
1090{
1091	struct hackrf_dev *dev = video_drvdata(file);
1092	struct usb_interface *intf = dev->intf;
1093	struct video_device *vdev = video_devdata(file);
1094	int ret;
1095	unsigned int uitmp;
1096
1097	dev_dbg(&intf->dev, "tuner=%d type=%d frequency=%u\n",
1098			f->tuner, f->type, f->frequency);
1099
1100	if (f->tuner == 0) {
1101		uitmp = clamp(f->frequency, bands_adc_dac[0].rangelow,
1102			      bands_adc_dac[0].rangehigh);
1103		if (vdev->vfl_dir == VFL_DIR_RX) {
1104			dev->f_adc = uitmp;
1105			set_bit(RX_ADC_FREQUENCY, &dev->flags);
1106		} else {
1107			dev->f_dac = uitmp;
1108			set_bit(TX_DAC_FREQUENCY, &dev->flags);
1109		}
1110	} else if (f->tuner == 1) {
1111		uitmp = clamp(f->frequency, bands_rx_tx[0].rangelow,
1112			      bands_rx_tx[0].rangehigh);
1113		if (vdev->vfl_dir == VFL_DIR_RX) {
1114			dev->f_rx = uitmp;
1115			set_bit(RX_RF_FREQUENCY, &dev->flags);
1116		} else {
1117			dev->f_tx = uitmp;
1118			set_bit(TX_RF_FREQUENCY, &dev->flags);
1119		}
1120	} else {
1121		ret = -EINVAL;
1122		goto err;
1123	}
1124
1125	ret = hackrf_set_params(dev);
1126	if (ret)
1127		goto err;
1128
1129	return 0;
1130err:
1131	dev_dbg(&intf->dev, "failed=%d\n", ret);
1132	return ret;
1133}
1134
1135static int hackrf_g_frequency(struct file *file, void *priv,
1136		struct v4l2_frequency *f)
1137{
1138	struct hackrf_dev *dev = video_drvdata(file);
1139	struct usb_interface *intf = dev->intf;
1140	struct video_device *vdev = video_devdata(file);
1141	int ret;
1142
1143	dev_dbg(dev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
1144
1145	if (f->tuner == 0) {
1146		f->type = V4L2_TUNER_SDR;
1147		if (vdev->vfl_dir == VFL_DIR_RX)
1148			f->frequency = dev->f_adc;
1149		else
1150			f->frequency = dev->f_dac;
1151	} else if (f->tuner == 1) {
1152		f->type = V4L2_TUNER_RF;
1153		if (vdev->vfl_dir == VFL_DIR_RX)
1154			f->frequency = dev->f_rx;
1155		else
1156			f->frequency = dev->f_tx;
1157	} else {
1158		ret = -EINVAL;
1159		goto err;
1160	}
1161
1162	return 0;
1163err:
1164	dev_dbg(&intf->dev, "failed=%d\n", ret);
1165	return ret;
1166}
1167
1168static int hackrf_enum_freq_bands(struct file *file, void *priv,
1169		struct v4l2_frequency_band *band)
1170{
1171	struct hackrf_dev *dev = video_drvdata(file);
1172	int ret;
1173
1174	dev_dbg(dev->dev, "tuner=%d type=%d index=%d\n",
1175			band->tuner, band->type, band->index);
1176
1177	if (band->tuner == 0) {
1178		if (band->index >= ARRAY_SIZE(bands_adc_dac)) {
1179			ret = -EINVAL;
1180		} else {
1181			*band = bands_adc_dac[band->index];
1182			ret = 0;
1183		}
1184	} else if (band->tuner == 1) {
1185		if (band->index >= ARRAY_SIZE(bands_rx_tx)) {
1186			ret = -EINVAL;
1187		} else {
1188			*band = bands_rx_tx[band->index];
1189			ret = 0;
1190		}
1191	} else {
1192		ret = -EINVAL;
1193	}
1194
1195	return ret;
1196}
1197
1198static const struct v4l2_ioctl_ops hackrf_ioctl_ops = {
1199	.vidioc_querycap          = hackrf_querycap,
1200
1201	.vidioc_s_fmt_sdr_cap     = hackrf_s_fmt_sdr,
1202	.vidioc_g_fmt_sdr_cap     = hackrf_g_fmt_sdr,
1203	.vidioc_enum_fmt_sdr_cap  = hackrf_enum_fmt_sdr,
1204	.vidioc_try_fmt_sdr_cap   = hackrf_try_fmt_sdr,
1205
1206	.vidioc_s_fmt_sdr_out     = hackrf_s_fmt_sdr,
1207	.vidioc_g_fmt_sdr_out     = hackrf_g_fmt_sdr,
1208	.vidioc_enum_fmt_sdr_out  = hackrf_enum_fmt_sdr,
1209	.vidioc_try_fmt_sdr_out   = hackrf_try_fmt_sdr,
1210
1211	.vidioc_reqbufs           = vb2_ioctl_reqbufs,
1212	.vidioc_create_bufs       = vb2_ioctl_create_bufs,
1213	.vidioc_prepare_buf       = vb2_ioctl_prepare_buf,
1214	.vidioc_querybuf          = vb2_ioctl_querybuf,
1215	.vidioc_qbuf              = vb2_ioctl_qbuf,
1216	.vidioc_dqbuf             = vb2_ioctl_dqbuf,
1217	.vidioc_expbuf            = vb2_ioctl_expbuf,
1218
1219	.vidioc_streamon          = vb2_ioctl_streamon,
1220	.vidioc_streamoff         = vb2_ioctl_streamoff,
1221
1222	.vidioc_s_tuner           = hackrf_s_tuner,
1223	.vidioc_g_tuner           = hackrf_g_tuner,
1224
1225	.vidioc_s_modulator       = hackrf_s_modulator,
1226	.vidioc_g_modulator       = hackrf_g_modulator,
1227
1228	.vidioc_s_frequency       = hackrf_s_frequency,
1229	.vidioc_g_frequency       = hackrf_g_frequency,
1230	.vidioc_enum_freq_bands   = hackrf_enum_freq_bands,
1231
1232	.vidioc_subscribe_event   = v4l2_ctrl_subscribe_event,
1233	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1234	.vidioc_log_status        = v4l2_ctrl_log_status,
1235};
1236
1237static const struct v4l2_file_operations hackrf_fops = {
1238	.owner                    = THIS_MODULE,
1239	.open                     = v4l2_fh_open,
1240	.release                  = vb2_fop_release,
1241	.read                     = vb2_fop_read,
1242	.write                    = vb2_fop_write,
1243	.poll                     = vb2_fop_poll,
1244	.mmap                     = vb2_fop_mmap,
1245	.unlocked_ioctl           = video_ioctl2,
1246};
1247
1248static const struct video_device hackrf_template = {
1249	.name                     = "HackRF One",
1250	.release                  = video_device_release_empty,
1251	.fops                     = &hackrf_fops,
1252	.ioctl_ops                = &hackrf_ioctl_ops,
1253};
1254
1255static void hackrf_video_release(struct v4l2_device *v)
1256{
1257	struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
1258
1259	dev_dbg(dev->dev, "\n");
1260
1261	v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
1262	v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
1263	v4l2_device_unregister(&dev->v4l2_dev);
1264	kfree(dev);
1265}
1266
1267static int hackrf_s_ctrl_rx(struct v4l2_ctrl *ctrl)
1268{
1269	struct hackrf_dev *dev = container_of(ctrl->handler,
1270			struct hackrf_dev, rx_ctrl_handler);
1271	struct usb_interface *intf = dev->intf;
1272	int ret;
1273
1274	switch (ctrl->id) {
1275	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1276	case V4L2_CID_RF_TUNER_BANDWIDTH:
1277		set_bit(RX_BANDWIDTH, &dev->flags);
1278		break;
1279	case  V4L2_CID_RF_TUNER_RF_GAIN:
1280		set_bit(RX_RF_GAIN, &dev->flags);
1281		break;
1282	case  V4L2_CID_RF_TUNER_LNA_GAIN:
1283		set_bit(RX_LNA_GAIN, &dev->flags);
1284		break;
1285	case  V4L2_CID_RF_TUNER_IF_GAIN:
1286		set_bit(RX_IF_GAIN, &dev->flags);
1287		break;
1288	default:
1289		dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
1290			ctrl->id, ctrl->name);
1291		ret = -EINVAL;
1292		goto err;
1293	}
1294
1295	ret = hackrf_set_params(dev);
1296	if (ret)
1297		goto err;
1298
1299	return 0;
1300err:
1301	dev_dbg(&intf->dev, "failed=%d\n", ret);
1302	return ret;
1303}
1304
1305static int hackrf_s_ctrl_tx(struct v4l2_ctrl *ctrl)
1306{
1307	struct hackrf_dev *dev = container_of(ctrl->handler,
1308			struct hackrf_dev, tx_ctrl_handler);
1309	struct usb_interface *intf = dev->intf;
1310	int ret;
1311
1312	switch (ctrl->id) {
1313	case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
1314	case V4L2_CID_RF_TUNER_BANDWIDTH:
1315		set_bit(TX_BANDWIDTH, &dev->flags);
1316		break;
1317	case  V4L2_CID_RF_TUNER_LNA_GAIN:
1318		set_bit(TX_LNA_GAIN, &dev->flags);
1319		break;
1320	case  V4L2_CID_RF_TUNER_RF_GAIN:
1321		set_bit(TX_RF_GAIN, &dev->flags);
1322		break;
1323	default:
1324		dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
1325			ctrl->id, ctrl->name);
1326		ret = -EINVAL;
1327		goto err;
1328	}
1329
1330	ret = hackrf_set_params(dev);
1331	if (ret)
1332		goto err;
1333
1334	return 0;
1335err:
1336	dev_dbg(&intf->dev, "failed=%d\n", ret);
1337	return ret;
1338}
1339
1340static const struct v4l2_ctrl_ops hackrf_ctrl_ops_rx = {
1341	.s_ctrl = hackrf_s_ctrl_rx,
1342};
1343
1344static const struct v4l2_ctrl_ops hackrf_ctrl_ops_tx = {
1345	.s_ctrl = hackrf_s_ctrl_tx,
1346};
1347
1348static int hackrf_probe(struct usb_interface *intf,
1349		const struct usb_device_id *id)
1350{
1351	struct hackrf_dev *dev;
1352	int ret;
1353	u8 u8tmp, buf[BUF_SIZE];
1354
1355	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1356	if (!dev) {
1357		ret = -ENOMEM;
1358		goto err;
1359	}
1360
1361	mutex_init(&dev->v4l2_lock);
1362	mutex_init(&dev->vb_queue_lock);
1363	spin_lock_init(&dev->buffer_list_lock);
1364	INIT_LIST_HEAD(&dev->rx_buffer_list);
1365	INIT_LIST_HEAD(&dev->tx_buffer_list);
1366	dev->intf = intf;
1367	dev->dev = &intf->dev;
1368	dev->udev = interface_to_usbdev(intf);
1369	dev->pixelformat = formats[0].pixelformat;
1370	dev->buffersize = formats[0].buffersize;
1371	dev->f_adc = bands_adc_dac[0].rangelow;
1372	dev->f_dac = bands_adc_dac[0].rangelow;
1373	dev->f_rx = bands_rx_tx[0].rangelow;
1374	dev->f_tx = bands_rx_tx[0].rangelow;
1375	set_bit(RX_ADC_FREQUENCY, &dev->flags);
1376	set_bit(TX_DAC_FREQUENCY, &dev->flags);
1377	set_bit(RX_RF_FREQUENCY, &dev->flags);
1378	set_bit(TX_RF_FREQUENCY, &dev->flags);
1379
1380	/* Detect device */
1381	ret = hackrf_ctrl_msg(dev, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
1382	if (ret == 0)
1383		ret = hackrf_ctrl_msg(dev, CMD_VERSION_STRING_READ, 0, 0,
1384				buf, BUF_SIZE);
1385	if (ret) {
1386		dev_err(dev->dev, "Could not detect board\n");
1387		goto err_kfree;
1388	}
1389
1390	buf[BUF_SIZE - 1] = '\0';
1391	dev_info(dev->dev, "Board ID: %02x\n", u8tmp);
1392	dev_info(dev->dev, "Firmware version: %s\n", buf);
1393
1394	/* Init vb2 queue structure for receiver */
1395	dev->rx_vb2_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1396	dev->rx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1397				     VB2_READ;
1398	dev->rx_vb2_queue.ops = &hackrf_vb2_ops;
1399	dev->rx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1400	dev->rx_vb2_queue.drv_priv = dev;
1401	dev->rx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1402	dev->rx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
 
1403	ret = vb2_queue_init(&dev->rx_vb2_queue);
1404	if (ret) {
1405		dev_err(dev->dev, "Could not initialize rx vb2 queue\n");
1406		goto err_kfree;
1407	}
1408
1409	/* Init vb2 queue structure for transmitter */
1410	dev->tx_vb2_queue.type = V4L2_BUF_TYPE_SDR_OUTPUT;
1411	dev->tx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1412				     VB2_WRITE;
1413	dev->tx_vb2_queue.ops = &hackrf_vb2_ops;
1414	dev->tx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1415	dev->tx_vb2_queue.drv_priv = dev;
1416	dev->tx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1417	dev->tx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
 
1418	ret = vb2_queue_init(&dev->tx_vb2_queue);
1419	if (ret) {
1420		dev_err(dev->dev, "Could not initialize tx vb2 queue\n");
1421		goto err_kfree;
1422	}
1423
1424	/* Register controls for receiver */
1425	v4l2_ctrl_handler_init(&dev->rx_ctrl_handler, 5);
1426	dev->rx_bandwidth_auto = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1427		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1428		0, 1, 0, 1);
1429	dev->rx_bandwidth = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1430		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH,
1431		1750000, 28000000, 50000, 1750000);
1432	v4l2_ctrl_auto_cluster(2, &dev->rx_bandwidth_auto, 0, false);
1433	dev->rx_rf_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1434		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 12, 12, 0);
1435	dev->rx_lna_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1436		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 40, 8, 0);
1437	dev->rx_if_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1438		&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_IF_GAIN, 0, 62, 2, 0);
1439	if (dev->rx_ctrl_handler.error) {
1440		ret = dev->rx_ctrl_handler.error;
1441		dev_err(dev->dev, "Could not initialize controls\n");
1442		goto err_v4l2_ctrl_handler_free_rx;
1443	}
1444	v4l2_ctrl_grab(dev->rx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1445	v4l2_ctrl_handler_setup(&dev->rx_ctrl_handler);
1446
1447	/* Register controls for transmitter */
1448	v4l2_ctrl_handler_init(&dev->tx_ctrl_handler, 4);
1449	dev->tx_bandwidth_auto = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1450		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1451		0, 1, 0, 1);
1452	dev->tx_bandwidth = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1453		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH,
1454		1750000, 28000000, 50000, 1750000);
1455	v4l2_ctrl_auto_cluster(2, &dev->tx_bandwidth_auto, 0, false);
1456	dev->tx_lna_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1457		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 47, 1, 0);
1458	dev->tx_rf_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1459		&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 15, 15, 0);
1460	if (dev->tx_ctrl_handler.error) {
1461		ret = dev->tx_ctrl_handler.error;
1462		dev_err(dev->dev, "Could not initialize controls\n");
1463		goto err_v4l2_ctrl_handler_free_tx;
1464	}
1465	v4l2_ctrl_grab(dev->tx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1466	v4l2_ctrl_handler_setup(&dev->tx_ctrl_handler);
1467
1468	/* Register the v4l2_device structure */
1469	dev->v4l2_dev.release = hackrf_video_release;
1470	ret = v4l2_device_register(&intf->dev, &dev->v4l2_dev);
1471	if (ret) {
1472		dev_err(dev->dev, "Failed to register v4l2-device (%d)\n", ret);
1473		goto err_v4l2_ctrl_handler_free_tx;
1474	}
1475
1476	/* Init video_device structure for receiver */
1477	dev->rx_vdev = hackrf_template;
1478	dev->rx_vdev.queue = &dev->rx_vb2_queue;
1479	dev->rx_vdev.queue->lock = &dev->vb_queue_lock;
1480	dev->rx_vdev.v4l2_dev = &dev->v4l2_dev;
1481	dev->rx_vdev.ctrl_handler = &dev->rx_ctrl_handler;
1482	dev->rx_vdev.lock = &dev->v4l2_lock;
1483	dev->rx_vdev.vfl_dir = VFL_DIR_RX;
1484	dev->rx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1485				   V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER;
1486	video_set_drvdata(&dev->rx_vdev, dev);
1487	ret = video_register_device(&dev->rx_vdev, VFL_TYPE_SDR, -1);
1488	if (ret) {
1489		dev_err(dev->dev,
1490			"Failed to register as video device (%d)\n", ret);
1491		goto err_v4l2_device_unregister;
1492	}
1493	dev_info(dev->dev, "Registered as %s\n",
1494		 video_device_node_name(&dev->rx_vdev));
1495
1496	/* Init video_device structure for transmitter */
1497	dev->tx_vdev = hackrf_template;
1498	dev->tx_vdev.queue = &dev->tx_vb2_queue;
1499	dev->tx_vdev.queue->lock = &dev->vb_queue_lock;
1500	dev->tx_vdev.v4l2_dev = &dev->v4l2_dev;
1501	dev->tx_vdev.ctrl_handler = &dev->tx_ctrl_handler;
1502	dev->tx_vdev.lock = &dev->v4l2_lock;
1503	dev->tx_vdev.vfl_dir = VFL_DIR_TX;
1504	dev->tx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1505				   V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR;
1506	video_set_drvdata(&dev->tx_vdev, dev);
1507	ret = video_register_device(&dev->tx_vdev, VFL_TYPE_SDR, -1);
1508	if (ret) {
1509		dev_err(dev->dev,
1510			"Failed to register as video device (%d)\n", ret);
1511		goto err_video_unregister_device_rx;
1512	}
1513	dev_info(dev->dev, "Registered as %s\n",
1514		 video_device_node_name(&dev->tx_vdev));
1515
1516	dev_notice(dev->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
1517	return 0;
1518err_video_unregister_device_rx:
1519	video_unregister_device(&dev->rx_vdev);
1520err_v4l2_device_unregister:
1521	v4l2_device_unregister(&dev->v4l2_dev);
1522err_v4l2_ctrl_handler_free_tx:
1523	v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
1524err_v4l2_ctrl_handler_free_rx:
1525	v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
1526err_kfree:
1527	kfree(dev);
1528err:
1529	dev_dbg(&intf->dev, "failed=%d\n", ret);
1530	return ret;
1531}
1532
1533/* USB device ID list */
1534static const struct usb_device_id hackrf_id_table[] = {
1535	{ USB_DEVICE(0x1d50, 0x6089) }, /* HackRF One */
1536	{ }
1537};
1538MODULE_DEVICE_TABLE(usb, hackrf_id_table);
1539
1540/* USB subsystem interface */
1541static struct usb_driver hackrf_driver = {
1542	.name                     = KBUILD_MODNAME,
1543	.probe                    = hackrf_probe,
1544	.disconnect               = hackrf_disconnect,
1545	.id_table                 = hackrf_id_table,
1546};
1547
1548module_usb_driver(hackrf_driver);
1549
1550MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
1551MODULE_DESCRIPTION("HackRF");
1552MODULE_LICENSE("GPL");