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