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