1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * vivid-sdr-cap.c - software defined radio support functions.
4  *
5  * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
6  */
7 
8 #include <linux/errno.h>
9 #include <linux/kernel.h>
10 #include <linux/delay.h>
11 #include <linux/kthread.h>
12 #include <linux/freezer.h>
13 #include <linux/math64.h>
14 #include <linux/videodev2.h>
15 #include <linux/v4l2-dv-timings.h>
16 #include <media/v4l2-common.h>
17 #include <media/v4l2-event.h>
18 #include <media/v4l2-dv-timings.h>
19 #include <linux/fixp-arith.h>
20 
21 #include "vivid-core.h"
22 #include "vivid-ctrls.h"
23 #include "vivid-sdr-cap.h"
24 
25 /* stream formats */
26 struct vivid_format {
27 	u32	pixelformat;
28 	u32	buffersize;
29 };
30 
31 /* format descriptions for capture and preview */
32 static const struct vivid_format formats[] = {
33 	{
34 		.pixelformat	= V4L2_SDR_FMT_CU8,
35 		.buffersize	= SDR_CAP_SAMPLES_PER_BUF * 2,
36 	}, {
37 		.pixelformat	= V4L2_SDR_FMT_CS8,
38 		.buffersize	= SDR_CAP_SAMPLES_PER_BUF * 2,
39 	},
40 };
41 
42 static const struct v4l2_frequency_band bands_adc[] = {
43 	{
44 		.tuner = 0,
45 		.type = V4L2_TUNER_ADC,
46 		.index = 0,
47 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
48 		.rangelow   =  300000,
49 		.rangehigh  =  300000,
50 	},
51 	{
52 		.tuner = 0,
53 		.type = V4L2_TUNER_ADC,
54 		.index = 1,
55 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
56 		.rangelow   =  900001,
57 		.rangehigh  = 2800000,
58 	},
59 	{
60 		.tuner = 0,
61 		.type = V4L2_TUNER_ADC,
62 		.index = 2,
63 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
64 		.rangelow   = 3200000,
65 		.rangehigh  = 3200000,
66 	},
67 };
68 
69 /* ADC band midpoints */
70 #define BAND_ADC_0 ((bands_adc[0].rangehigh + bands_adc[1].rangelow) / 2)
71 #define BAND_ADC_1 ((bands_adc[1].rangehigh + bands_adc[2].rangelow) / 2)
72 
73 static const struct v4l2_frequency_band bands_fm[] = {
74 	{
75 		.tuner = 1,
76 		.type = V4L2_TUNER_RF,
77 		.index = 0,
78 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
79 		.rangelow   =    50000000,
80 		.rangehigh  =  2000000000,
81 	},
82 };
83 
84 static void vivid_thread_sdr_cap_tick(struct vivid_dev *dev)
85 {
86 	struct vivid_buffer *sdr_cap_buf = NULL;
87 
88 	dprintk(dev, 1, "SDR Capture Thread Tick\n");
89 
90 	/* Drop a certain percentage of buffers. */
91 	if (dev->perc_dropped_buffers &&
92 	    prandom_u32_max(100) < dev->perc_dropped_buffers)
93 		return;
94 
95 	spin_lock(&dev->slock);
96 	if (!list_empty(&dev->sdr_cap_active)) {
97 		sdr_cap_buf = list_entry(dev->sdr_cap_active.next,
98 					 struct vivid_buffer, list);
99 		list_del(&sdr_cap_buf->list);
100 	}
101 	spin_unlock(&dev->slock);
102 
103 	if (sdr_cap_buf) {
104 		sdr_cap_buf->vb.sequence = dev->sdr_cap_seq_count;
105 		v4l2_ctrl_request_setup(sdr_cap_buf->vb.vb2_buf.req_obj.req,
106 					&dev->ctrl_hdl_sdr_cap);
107 		v4l2_ctrl_request_complete(sdr_cap_buf->vb.vb2_buf.req_obj.req,
108 					   &dev->ctrl_hdl_sdr_cap);
109 		vivid_sdr_cap_process(dev, sdr_cap_buf);
110 		sdr_cap_buf->vb.vb2_buf.timestamp =
111 			ktime_get_ns() + dev->time_wrap_offset;
112 		vb2_buffer_done(&sdr_cap_buf->vb.vb2_buf, dev->dqbuf_error ?
113 				VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
114 		dev->dqbuf_error = false;
115 	}
116 }
117 
118 static int vivid_thread_sdr_cap(void *data)
119 {
120 	struct vivid_dev *dev = data;
121 	u64 samples_since_start;
122 	u64 buffers_since_start;
123 	u64 next_jiffies_since_start;
124 	unsigned long jiffies_since_start;
125 	unsigned long cur_jiffies;
126 	unsigned wait_jiffies;
127 
128 	dprintk(dev, 1, "SDR Capture Thread Start\n");
129 
130 	set_freezable();
131 
132 	/* Resets frame counters */
133 	dev->sdr_cap_seq_offset = 0;
134 	if (dev->seq_wrap)
135 		dev->sdr_cap_seq_offset = 0xffffff80U;
136 	dev->jiffies_sdr_cap = jiffies;
137 	dev->sdr_cap_seq_resync = false;
138 
139 	for (;;) {
140 		try_to_freeze();
141 		if (kthread_should_stop())
142 			break;
143 
144 		if (!mutex_trylock(&dev->mutex)) {
145 			schedule();
146 			continue;
147 		}
148 
149 		cur_jiffies = jiffies;
150 		if (dev->sdr_cap_seq_resync) {
151 			dev->jiffies_sdr_cap = cur_jiffies;
152 			dev->sdr_cap_seq_offset = dev->sdr_cap_seq_count + 1;
153 			dev->sdr_cap_seq_count = 0;
154 			dev->sdr_cap_seq_resync = false;
155 		}
156 		/* Calculate the number of jiffies since we started streaming */
157 		jiffies_since_start = cur_jiffies - dev->jiffies_sdr_cap;
158 		/* Get the number of buffers streamed since the start */
159 		buffers_since_start =
160 			(u64)jiffies_since_start * dev->sdr_adc_freq +
161 				      (HZ * SDR_CAP_SAMPLES_PER_BUF) / 2;
162 		do_div(buffers_since_start, HZ * SDR_CAP_SAMPLES_PER_BUF);
163 
164 		/*
165 		 * After more than 0xf0000000 (rounded down to a multiple of
166 		 * 'jiffies-per-day' to ease jiffies_to_msecs calculation)
167 		 * jiffies have passed since we started streaming reset the
168 		 * counters and keep track of the sequence offset.
169 		 */
170 		if (jiffies_since_start > JIFFIES_RESYNC) {
171 			dev->jiffies_sdr_cap = cur_jiffies;
172 			dev->sdr_cap_seq_offset = buffers_since_start;
173 			buffers_since_start = 0;
174 		}
175 		dev->sdr_cap_seq_count =
176 			buffers_since_start + dev->sdr_cap_seq_offset;
177 
178 		vivid_thread_sdr_cap_tick(dev);
179 		mutex_unlock(&dev->mutex);
180 
181 		/*
182 		 * Calculate the number of samples streamed since we started,
183 		 * not including the current buffer.
184 		 */
185 		samples_since_start = buffers_since_start * SDR_CAP_SAMPLES_PER_BUF;
186 
187 		/* And the number of jiffies since we started */
188 		jiffies_since_start = jiffies - dev->jiffies_sdr_cap;
189 
190 		/* Increase by the number of samples in one buffer */
191 		samples_since_start += SDR_CAP_SAMPLES_PER_BUF;
192 		/*
193 		 * Calculate when that next buffer is supposed to start
194 		 * in jiffies since we started streaming.
195 		 */
196 		next_jiffies_since_start = samples_since_start * HZ +
197 					   dev->sdr_adc_freq / 2;
198 		do_div(next_jiffies_since_start, dev->sdr_adc_freq);
199 		/* If it is in the past, then just schedule asap */
200 		if (next_jiffies_since_start < jiffies_since_start)
201 			next_jiffies_since_start = jiffies_since_start;
202 
203 		wait_jiffies = next_jiffies_since_start - jiffies_since_start;
204 		while (jiffies - cur_jiffies < wait_jiffies &&
205 		       !kthread_should_stop())
206 			schedule();
207 	}
208 	dprintk(dev, 1, "SDR Capture Thread End\n");
209 	return 0;
210 }
211 
212 static int sdr_cap_queue_setup(struct vb2_queue *vq,
213 		       unsigned *nbuffers, unsigned *nplanes,
214 		       unsigned sizes[], struct device *alloc_devs[])
215 {
216 	/* 2 = max 16-bit sample returned */
217 	sizes[0] = SDR_CAP_SAMPLES_PER_BUF * 2;
218 	*nplanes = 1;
219 	return 0;
220 }
221 
222 static int sdr_cap_buf_prepare(struct vb2_buffer *vb)
223 {
224 	struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
225 	unsigned size = SDR_CAP_SAMPLES_PER_BUF * 2;
226 
227 	dprintk(dev, 1, "%s\n", __func__);
228 
229 	if (dev->buf_prepare_error) {
230 		/*
231 		 * Error injection: test what happens if buf_prepare() returns
232 		 * an error.
233 		 */
234 		dev->buf_prepare_error = false;
235 		return -EINVAL;
236 	}
237 	if (vb2_plane_size(vb, 0) < size) {
238 		dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n",
239 				__func__, vb2_plane_size(vb, 0), size);
240 		return -EINVAL;
241 	}
242 	vb2_set_plane_payload(vb, 0, size);
243 
244 	return 0;
245 }
246 
247 static void sdr_cap_buf_queue(struct vb2_buffer *vb)
248 {
249 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
250 	struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
251 	struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb);
252 
253 	dprintk(dev, 1, "%s\n", __func__);
254 
255 	spin_lock(&dev->slock);
256 	list_add_tail(&buf->list, &dev->sdr_cap_active);
257 	spin_unlock(&dev->slock);
258 }
259 
260 static int sdr_cap_start_streaming(struct vb2_queue *vq, unsigned count)
261 {
262 	struct vivid_dev *dev = vb2_get_drv_priv(vq);
263 	int err = 0;
264 
265 	dprintk(dev, 1, "%s\n", __func__);
266 	dev->sdr_cap_seq_count = 0;
267 	if (dev->start_streaming_error) {
268 		dev->start_streaming_error = false;
269 		err = -EINVAL;
270 	} else if (dev->kthread_sdr_cap == NULL) {
271 		dev->kthread_sdr_cap = kthread_run(vivid_thread_sdr_cap, dev,
272 				"%s-sdr-cap", dev->v4l2_dev.name);
273 
274 		if (IS_ERR(dev->kthread_sdr_cap)) {
275 			v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
276 			err = PTR_ERR(dev->kthread_sdr_cap);
277 			dev->kthread_sdr_cap = NULL;
278 		}
279 	}
280 	if (err) {
281 		struct vivid_buffer *buf, *tmp;
282 
283 		list_for_each_entry_safe(buf, tmp, &dev->sdr_cap_active, list) {
284 			list_del(&buf->list);
285 			vb2_buffer_done(&buf->vb.vb2_buf,
286 					VB2_BUF_STATE_QUEUED);
287 		}
288 	}
289 	return err;
290 }
291 
292 /* abort streaming and wait for last buffer */
293 static void sdr_cap_stop_streaming(struct vb2_queue *vq)
294 {
295 	struct vivid_dev *dev = vb2_get_drv_priv(vq);
296 
297 	if (dev->kthread_sdr_cap == NULL)
298 		return;
299 
300 	while (!list_empty(&dev->sdr_cap_active)) {
301 		struct vivid_buffer *buf;
302 
303 		buf = list_entry(dev->sdr_cap_active.next,
304 				struct vivid_buffer, list);
305 		list_del(&buf->list);
306 		v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req,
307 					   &dev->ctrl_hdl_sdr_cap);
308 		vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
309 	}
310 
311 	/* shutdown control thread */
312 	kthread_stop(dev->kthread_sdr_cap);
313 	dev->kthread_sdr_cap = NULL;
314 }
315 
316 static void sdr_cap_buf_request_complete(struct vb2_buffer *vb)
317 {
318 	struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
319 
320 	v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_sdr_cap);
321 }
322 
323 const struct vb2_ops vivid_sdr_cap_qops = {
324 	.queue_setup		= sdr_cap_queue_setup,
325 	.buf_prepare		= sdr_cap_buf_prepare,
326 	.buf_queue		= sdr_cap_buf_queue,
327 	.start_streaming	= sdr_cap_start_streaming,
328 	.stop_streaming		= sdr_cap_stop_streaming,
329 	.buf_request_complete	= sdr_cap_buf_request_complete,
330 	.wait_prepare		= vb2_ops_wait_prepare,
331 	.wait_finish		= vb2_ops_wait_finish,
332 };
333 
334 int vivid_sdr_enum_freq_bands(struct file *file, void *fh,
335 		struct v4l2_frequency_band *band)
336 {
337 	switch (band->tuner) {
338 	case 0:
339 		if (band->index >= ARRAY_SIZE(bands_adc))
340 			return -EINVAL;
341 		*band = bands_adc[band->index];
342 		return 0;
343 	case 1:
344 		if (band->index >= ARRAY_SIZE(bands_fm))
345 			return -EINVAL;
346 		*band = bands_fm[band->index];
347 		return 0;
348 	default:
349 		return -EINVAL;
350 	}
351 }
352 
353 int vivid_sdr_g_frequency(struct file *file, void *fh,
354 		struct v4l2_frequency *vf)
355 {
356 	struct vivid_dev *dev = video_drvdata(file);
357 
358 	switch (vf->tuner) {
359 	case 0:
360 		vf->frequency = dev->sdr_adc_freq;
361 		vf->type = V4L2_TUNER_ADC;
362 		return 0;
363 	case 1:
364 		vf->frequency = dev->sdr_fm_freq;
365 		vf->type = V4L2_TUNER_RF;
366 		return 0;
367 	default:
368 		return -EINVAL;
369 	}
370 }
371 
372 int vivid_sdr_s_frequency(struct file *file, void *fh,
373 		const struct v4l2_frequency *vf)
374 {
375 	struct vivid_dev *dev = video_drvdata(file);
376 	unsigned freq = vf->frequency;
377 	unsigned band;
378 
379 	switch (vf->tuner) {
380 	case 0:
381 		if (vf->type != V4L2_TUNER_ADC)
382 			return -EINVAL;
383 		if (freq < BAND_ADC_0)
384 			band = 0;
385 		else if (freq < BAND_ADC_1)
386 			band = 1;
387 		else
388 			band = 2;
389 
390 		freq = clamp_t(unsigned, freq,
391 				bands_adc[band].rangelow,
392 				bands_adc[band].rangehigh);
393 
394 		if (vb2_is_streaming(&dev->vb_sdr_cap_q) &&
395 		    freq != dev->sdr_adc_freq) {
396 			/* resync the thread's timings */
397 			dev->sdr_cap_seq_resync = true;
398 		}
399 		dev->sdr_adc_freq = freq;
400 		return 0;
401 	case 1:
402 		if (vf->type != V4L2_TUNER_RF)
403 			return -EINVAL;
404 		dev->sdr_fm_freq = clamp_t(unsigned, freq,
405 				bands_fm[0].rangelow,
406 				bands_fm[0].rangehigh);
407 		return 0;
408 	default:
409 		return -EINVAL;
410 	}
411 }
412 
413 int vivid_sdr_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
414 {
415 	switch (vt->index) {
416 	case 0:
417 		strscpy(vt->name, "ADC", sizeof(vt->name));
418 		vt->type = V4L2_TUNER_ADC;
419 		vt->capability =
420 			V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
421 		vt->rangelow = bands_adc[0].rangelow;
422 		vt->rangehigh = bands_adc[2].rangehigh;
423 		return 0;
424 	case 1:
425 		strscpy(vt->name, "RF", sizeof(vt->name));
426 		vt->type = V4L2_TUNER_RF;
427 		vt->capability =
428 			V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
429 		vt->rangelow = bands_fm[0].rangelow;
430 		vt->rangehigh = bands_fm[0].rangehigh;
431 		return 0;
432 	default:
433 		return -EINVAL;
434 	}
435 }
436 
437 int vivid_sdr_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt)
438 {
439 	if (vt->index > 1)
440 		return -EINVAL;
441 	return 0;
442 }
443 
444 int vidioc_enum_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_fmtdesc *f)
445 {
446 	if (f->index >= ARRAY_SIZE(formats))
447 		return -EINVAL;
448 	f->pixelformat = formats[f->index].pixelformat;
449 	return 0;
450 }
451 
452 int vidioc_g_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f)
453 {
454 	struct vivid_dev *dev = video_drvdata(file);
455 
456 	f->fmt.sdr.pixelformat = dev->sdr_pixelformat;
457 	f->fmt.sdr.buffersize = dev->sdr_buffersize;
458 	return 0;
459 }
460 
461 int vidioc_s_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f)
462 {
463 	struct vivid_dev *dev = video_drvdata(file);
464 	struct vb2_queue *q = &dev->vb_sdr_cap_q;
465 	int i;
466 
467 	if (vb2_is_busy(q))
468 		return -EBUSY;
469 
470 	for (i = 0; i < ARRAY_SIZE(formats); i++) {
471 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
472 			dev->sdr_pixelformat = formats[i].pixelformat;
473 			dev->sdr_buffersize = formats[i].buffersize;
474 			f->fmt.sdr.buffersize = formats[i].buffersize;
475 			return 0;
476 		}
477 	}
478 	dev->sdr_pixelformat = formats[0].pixelformat;
479 	dev->sdr_buffersize = formats[0].buffersize;
480 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
481 	f->fmt.sdr.buffersize = formats[0].buffersize;
482 	return 0;
483 }
484 
485 int vidioc_try_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f)
486 {
487 	int i;
488 
489 	for (i = 0; i < ARRAY_SIZE(formats); i++) {
490 		if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
491 			f->fmt.sdr.buffersize = formats[i].buffersize;
492 			return 0;
493 		}
494 	}
495 	f->fmt.sdr.pixelformat = formats[0].pixelformat;
496 	f->fmt.sdr.buffersize = formats[0].buffersize;
497 	return 0;
498 }
499 
500 #define FIXP_N    (15)
501 #define FIXP_FRAC (1 << FIXP_N)
502 #define FIXP_2PI  ((int)(2 * 3.141592653589 * FIXP_FRAC))
503 #define M_100000PI (3.14159 * 100000)
504 
505 void vivid_sdr_cap_process(struct vivid_dev *dev, struct vivid_buffer *buf)
506 {
507 	u8 *vbuf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
508 	unsigned long i;
509 	unsigned long plane_size = vb2_plane_size(&buf->vb.vb2_buf, 0);
510 	s64 s64tmp;
511 	s32 src_phase_step;
512 	s32 mod_phase_step;
513 	s32 fixp_i;
514 	s32 fixp_q;
515 
516 	/* calculate phase step */
517 	#define BEEP_FREQ 1000 /* 1kHz beep */
518 	src_phase_step = DIV_ROUND_CLOSEST(FIXP_2PI * BEEP_FREQ,
519 					   dev->sdr_adc_freq);
520 
521 	for (i = 0; i < plane_size; i += 2) {
522 		mod_phase_step = fixp_cos32_rad(dev->sdr_fixp_src_phase,
523 						FIXP_2PI) >> (31 - FIXP_N);
524 
525 		dev->sdr_fixp_src_phase += src_phase_step;
526 		s64tmp = (s64) mod_phase_step * dev->sdr_fm_deviation;
527 		dev->sdr_fixp_mod_phase += div_s64(s64tmp, M_100000PI);
528 
529 		/*
530 		 * Transfer phase angle to [0, 2xPI] in order to avoid variable
531 		 * overflow and make it suitable for cosine implementation
532 		 * used, which does not support negative angles.
533 		 */
534 		dev->sdr_fixp_src_phase %= FIXP_2PI;
535 		dev->sdr_fixp_mod_phase %= FIXP_2PI;
536 
537 		if (dev->sdr_fixp_mod_phase < 0)
538 			dev->sdr_fixp_mod_phase += FIXP_2PI;
539 
540 		fixp_i = fixp_cos32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI);
541 		fixp_q = fixp_sin32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI);
542 
543 		/* Normalize fraction values represented with 32 bit precision
544 		 * to fixed point representation with FIXP_N bits */
545 		fixp_i >>= (31 - FIXP_N);
546 		fixp_q >>= (31 - FIXP_N);
547 
548 		switch (dev->sdr_pixelformat) {
549 		case V4L2_SDR_FMT_CU8:
550 			/* convert 'fixp float' to u8 [0, +255] */
551 			/* u8 = X * 127.5 + 127.5; X is float [-1.0, +1.0] */
552 			fixp_i = fixp_i * 1275 + FIXP_FRAC * 1275;
553 			fixp_q = fixp_q * 1275 + FIXP_FRAC * 1275;
554 			*vbuf++ = DIV_ROUND_CLOSEST(fixp_i, FIXP_FRAC * 10);
555 			*vbuf++ = DIV_ROUND_CLOSEST(fixp_q, FIXP_FRAC * 10);
556 			break;
557 		case V4L2_SDR_FMT_CS8:
558 			/* convert 'fixp float' to s8 [-128, +127] */
559 			/* s8 = X * 127.5 - 0.5; X is float [-1.0, +1.0] */
560 			fixp_i = fixp_i * 1275 - FIXP_FRAC * 5;
561 			fixp_q = fixp_q * 1275 - FIXP_FRAC * 5;
562 			*vbuf++ = DIV_ROUND_CLOSEST(fixp_i, FIXP_FRAC * 10);
563 			*vbuf++ = DIV_ROUND_CLOSEST(fixp_q, FIXP_FRAC * 10);
564 			break;
565 		default:
566 			break;
567 		}
568 	}
569 }
570