1 /*
2  * vivid-sdr-cap.c - software defined radio support functions.
3  *
4  * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
5  *
6  * This program is free software; you may redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; version 2 of the License.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
11  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
13  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
14  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
15  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
16  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17  * SOFTWARE.
18  */
19 
20 #include <linux/errno.h>
21 #include <linux/kernel.h>
22 #include <linux/delay.h>
23 #include <linux/kthread.h>
24 #include <linux/freezer.h>
25 #include <linux/videodev2.h>
26 #include <linux/v4l2-dv-timings.h>
27 #include <media/v4l2-common.h>
28 #include <media/v4l2-event.h>
29 #include <media/v4l2-dv-timings.h>
30 #include <linux/fixp-arith.h>
31 
32 #include "vivid-core.h"
33 #include "vivid-ctrls.h"
34 #include "vivid-sdr-cap.h"
35 
36 static const struct v4l2_frequency_band bands_adc[] = {
37 	{
38 		.tuner = 0,
39 		.type = V4L2_TUNER_ADC,
40 		.index = 0,
41 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
42 		.rangelow   =  300000,
43 		.rangehigh  =  300000,
44 	},
45 	{
46 		.tuner = 0,
47 		.type = V4L2_TUNER_ADC,
48 		.index = 1,
49 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
50 		.rangelow   =  900001,
51 		.rangehigh  = 2800000,
52 	},
53 	{
54 		.tuner = 0,
55 		.type = V4L2_TUNER_ADC,
56 		.index = 2,
57 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
58 		.rangelow   = 3200000,
59 		.rangehigh  = 3200000,
60 	},
61 };
62 
63 /* ADC band midpoints */
64 #define BAND_ADC_0 ((bands_adc[0].rangehigh + bands_adc[1].rangelow) / 2)
65 #define BAND_ADC_1 ((bands_adc[1].rangehigh + bands_adc[2].rangelow) / 2)
66 
67 static const struct v4l2_frequency_band bands_fm[] = {
68 	{
69 		.tuner = 1,
70 		.type = V4L2_TUNER_RF,
71 		.index = 0,
72 		.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
73 		.rangelow   =    50000000,
74 		.rangehigh  =  2000000000,
75 	},
76 };
77 
vivid_thread_sdr_cap_tick(struct vivid_dev * dev)78 static void vivid_thread_sdr_cap_tick(struct vivid_dev *dev)
79 {
80 	struct vivid_buffer *sdr_cap_buf = NULL;
81 
82 	dprintk(dev, 1, "SDR Capture Thread Tick\n");
83 
84 	/* Drop a certain percentage of buffers. */
85 	if (dev->perc_dropped_buffers &&
86 	    prandom_u32_max(100) < dev->perc_dropped_buffers)
87 		return;
88 
89 	spin_lock(&dev->slock);
90 	if (!list_empty(&dev->sdr_cap_active)) {
91 		sdr_cap_buf = list_entry(dev->sdr_cap_active.next,
92 					 struct vivid_buffer, list);
93 		list_del(&sdr_cap_buf->list);
94 	}
95 	spin_unlock(&dev->slock);
96 
97 	if (sdr_cap_buf) {
98 		sdr_cap_buf->vb.v4l2_buf.sequence = dev->sdr_cap_seq_count;
99 		vivid_sdr_cap_process(dev, sdr_cap_buf);
100 		v4l2_get_timestamp(&sdr_cap_buf->vb.v4l2_buf.timestamp);
101 		sdr_cap_buf->vb.v4l2_buf.timestamp.tv_sec += dev->time_wrap_offset;
102 		vb2_buffer_done(&sdr_cap_buf->vb, dev->dqbuf_error ?
103 				VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
104 		dev->dqbuf_error = false;
105 	}
106 }
107 
vivid_thread_sdr_cap(void * data)108 static int vivid_thread_sdr_cap(void *data)
109 {
110 	struct vivid_dev *dev = data;
111 	u64 samples_since_start;
112 	u64 buffers_since_start;
113 	u64 next_jiffies_since_start;
114 	unsigned long jiffies_since_start;
115 	unsigned long cur_jiffies;
116 	unsigned wait_jiffies;
117 
118 	dprintk(dev, 1, "SDR Capture Thread Start\n");
119 
120 	set_freezable();
121 
122 	/* Resets frame counters */
123 	dev->sdr_cap_seq_offset = 0;
124 	if (dev->seq_wrap)
125 		dev->sdr_cap_seq_offset = 0xffffff80U;
126 	dev->jiffies_sdr_cap = jiffies;
127 	dev->sdr_cap_seq_resync = false;
128 
129 	for (;;) {
130 		try_to_freeze();
131 		if (kthread_should_stop())
132 			break;
133 
134 		mutex_lock(&dev->mutex);
135 		cur_jiffies = jiffies;
136 		if (dev->sdr_cap_seq_resync) {
137 			dev->jiffies_sdr_cap = cur_jiffies;
138 			dev->sdr_cap_seq_offset = dev->sdr_cap_seq_count + 1;
139 			dev->sdr_cap_seq_count = 0;
140 			dev->sdr_cap_seq_resync = false;
141 		}
142 		/* Calculate the number of jiffies since we started streaming */
143 		jiffies_since_start = cur_jiffies - dev->jiffies_sdr_cap;
144 		/* Get the number of buffers streamed since the start */
145 		buffers_since_start = (u64)jiffies_since_start * dev->sdr_adc_freq +
146 				      (HZ * SDR_CAP_SAMPLES_PER_BUF) / 2;
147 		do_div(buffers_since_start, HZ * SDR_CAP_SAMPLES_PER_BUF);
148 
149 		/*
150 		 * After more than 0xf0000000 (rounded down to a multiple of
151 		 * 'jiffies-per-day' to ease jiffies_to_msecs calculation)
152 		 * jiffies have passed since we started streaming reset the
153 		 * counters and keep track of the sequence offset.
154 		 */
155 		if (jiffies_since_start > JIFFIES_RESYNC) {
156 			dev->jiffies_sdr_cap = cur_jiffies;
157 			dev->sdr_cap_seq_offset = buffers_since_start;
158 			buffers_since_start = 0;
159 		}
160 		dev->sdr_cap_seq_count = buffers_since_start + dev->sdr_cap_seq_offset;
161 
162 		vivid_thread_sdr_cap_tick(dev);
163 		mutex_unlock(&dev->mutex);
164 
165 		/*
166 		 * Calculate the number of samples streamed since we started,
167 		 * not including the current buffer.
168 		 */
169 		samples_since_start = buffers_since_start * SDR_CAP_SAMPLES_PER_BUF;
170 
171 		/* And the number of jiffies since we started */
172 		jiffies_since_start = jiffies - dev->jiffies_sdr_cap;
173 
174 		/* Increase by the number of samples in one buffer */
175 		samples_since_start += SDR_CAP_SAMPLES_PER_BUF;
176 		/*
177 		 * Calculate when that next buffer is supposed to start
178 		 * in jiffies since we started streaming.
179 		 */
180 		next_jiffies_since_start = samples_since_start * HZ +
181 					   dev->sdr_adc_freq / 2;
182 		do_div(next_jiffies_since_start, dev->sdr_adc_freq);
183 		/* If it is in the past, then just schedule asap */
184 		if (next_jiffies_since_start < jiffies_since_start)
185 			next_jiffies_since_start = jiffies_since_start;
186 
187 		wait_jiffies = next_jiffies_since_start - jiffies_since_start;
188 		schedule_timeout_interruptible(wait_jiffies ? wait_jiffies : 1);
189 	}
190 	dprintk(dev, 1, "SDR Capture Thread End\n");
191 	return 0;
192 }
193 
sdr_cap_queue_setup(struct vb2_queue * vq,const struct v4l2_format * fmt,unsigned * nbuffers,unsigned * nplanes,unsigned sizes[],void * alloc_ctxs[])194 static int sdr_cap_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
195 		       unsigned *nbuffers, unsigned *nplanes,
196 		       unsigned sizes[], void *alloc_ctxs[])
197 {
198 	/* 2 = max 16-bit sample returned */
199 	sizes[0] = SDR_CAP_SAMPLES_PER_BUF * 2;
200 	*nplanes = 1;
201 	return 0;
202 }
203 
sdr_cap_buf_prepare(struct vb2_buffer * vb)204 static int sdr_cap_buf_prepare(struct vb2_buffer *vb)
205 {
206 	struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
207 	unsigned size = SDR_CAP_SAMPLES_PER_BUF * 2;
208 
209 	dprintk(dev, 1, "%s\n", __func__);
210 
211 	if (dev->buf_prepare_error) {
212 		/*
213 		 * Error injection: test what happens if buf_prepare() returns
214 		 * an error.
215 		 */
216 		dev->buf_prepare_error = false;
217 		return -EINVAL;
218 	}
219 	if (vb2_plane_size(vb, 0) < size) {
220 		dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n",
221 				__func__, vb2_plane_size(vb, 0), size);
222 		return -EINVAL;
223 	}
224 	vb2_set_plane_payload(vb, 0, size);
225 
226 	return 0;
227 }
228 
sdr_cap_buf_queue(struct vb2_buffer * vb)229 static void sdr_cap_buf_queue(struct vb2_buffer *vb)
230 {
231 	struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
232 	struct vivid_buffer *buf = container_of(vb, struct vivid_buffer, vb);
233 
234 	dprintk(dev, 1, "%s\n", __func__);
235 
236 	spin_lock(&dev->slock);
237 	list_add_tail(&buf->list, &dev->sdr_cap_active);
238 	spin_unlock(&dev->slock);
239 }
240 
sdr_cap_start_streaming(struct vb2_queue * vq,unsigned count)241 static int sdr_cap_start_streaming(struct vb2_queue *vq, unsigned count)
242 {
243 	struct vivid_dev *dev = vb2_get_drv_priv(vq);
244 	int err = 0;
245 
246 	dprintk(dev, 1, "%s\n", __func__);
247 	dev->sdr_cap_seq_count = 0;
248 	if (dev->start_streaming_error) {
249 		dev->start_streaming_error = false;
250 		err = -EINVAL;
251 	} else if (dev->kthread_sdr_cap == NULL) {
252 		dev->kthread_sdr_cap = kthread_run(vivid_thread_sdr_cap, dev,
253 				"%s-sdr-cap", dev->v4l2_dev.name);
254 
255 		if (IS_ERR(dev->kthread_sdr_cap)) {
256 			v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
257 			err = PTR_ERR(dev->kthread_sdr_cap);
258 			dev->kthread_sdr_cap = NULL;
259 		}
260 	}
261 	if (err) {
262 		struct vivid_buffer *buf, *tmp;
263 
264 		list_for_each_entry_safe(buf, tmp, &dev->sdr_cap_active, list) {
265 			list_del(&buf->list);
266 			vb2_buffer_done(&buf->vb, VB2_BUF_STATE_QUEUED);
267 		}
268 	}
269 	return err;
270 }
271 
272 /* abort streaming and wait for last buffer */
sdr_cap_stop_streaming(struct vb2_queue * vq)273 static void sdr_cap_stop_streaming(struct vb2_queue *vq)
274 {
275 	struct vivid_dev *dev = vb2_get_drv_priv(vq);
276 
277 	if (dev->kthread_sdr_cap == NULL)
278 		return;
279 
280 	while (!list_empty(&dev->sdr_cap_active)) {
281 		struct vivid_buffer *buf;
282 
283 		buf = list_entry(dev->sdr_cap_active.next, struct vivid_buffer, list);
284 		list_del(&buf->list);
285 		vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
286 	}
287 
288 	/* shutdown control thread */
289 	mutex_unlock(&dev->mutex);
290 	kthread_stop(dev->kthread_sdr_cap);
291 	dev->kthread_sdr_cap = NULL;
292 	mutex_lock(&dev->mutex);
293 }
294 
295 const struct vb2_ops vivid_sdr_cap_qops = {
296 	.queue_setup		= sdr_cap_queue_setup,
297 	.buf_prepare		= sdr_cap_buf_prepare,
298 	.buf_queue		= sdr_cap_buf_queue,
299 	.start_streaming	= sdr_cap_start_streaming,
300 	.stop_streaming		= sdr_cap_stop_streaming,
301 	.wait_prepare		= vb2_ops_wait_prepare,
302 	.wait_finish		= vb2_ops_wait_finish,
303 };
304 
vivid_sdr_enum_freq_bands(struct file * file,void * fh,struct v4l2_frequency_band * band)305 int vivid_sdr_enum_freq_bands(struct file *file, void *fh, struct v4l2_frequency_band *band)
306 {
307 	switch (band->tuner) {
308 	case 0:
309 		if (band->index >= ARRAY_SIZE(bands_adc))
310 			return -EINVAL;
311 		*band = bands_adc[band->index];
312 		return 0;
313 	case 1:
314 		if (band->index >= ARRAY_SIZE(bands_fm))
315 			return -EINVAL;
316 		*band = bands_fm[band->index];
317 		return 0;
318 	default:
319 		return -EINVAL;
320 	}
321 }
322 
vivid_sdr_g_frequency(struct file * file,void * fh,struct v4l2_frequency * vf)323 int vivid_sdr_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf)
324 {
325 	struct vivid_dev *dev = video_drvdata(file);
326 
327 	switch (vf->tuner) {
328 	case 0:
329 		vf->frequency = dev->sdr_adc_freq;
330 		vf->type = V4L2_TUNER_ADC;
331 		return 0;
332 	case 1:
333 		vf->frequency = dev->sdr_fm_freq;
334 		vf->type = V4L2_TUNER_RF;
335 		return 0;
336 	default:
337 		return -EINVAL;
338 	}
339 }
340 
vivid_sdr_s_frequency(struct file * file,void * fh,const struct v4l2_frequency * vf)341 int vivid_sdr_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf)
342 {
343 	struct vivid_dev *dev = video_drvdata(file);
344 	unsigned freq = vf->frequency;
345 	unsigned band;
346 
347 	switch (vf->tuner) {
348 	case 0:
349 		if (vf->type != V4L2_TUNER_ADC)
350 			return -EINVAL;
351 		if (freq < BAND_ADC_0)
352 			band = 0;
353 		else if (freq < BAND_ADC_1)
354 			band = 1;
355 		else
356 			band = 2;
357 
358 		freq = clamp_t(unsigned, freq,
359 				bands_adc[band].rangelow,
360 				bands_adc[band].rangehigh);
361 
362 		if (vb2_is_streaming(&dev->vb_sdr_cap_q) &&
363 		    freq != dev->sdr_adc_freq) {
364 			/* resync the thread's timings */
365 			dev->sdr_cap_seq_resync = true;
366 		}
367 		dev->sdr_adc_freq = freq;
368 		return 0;
369 	case 1:
370 		if (vf->type != V4L2_TUNER_RF)
371 			return -EINVAL;
372 		dev->sdr_fm_freq = clamp_t(unsigned, freq,
373 				bands_fm[0].rangelow,
374 				bands_fm[0].rangehigh);
375 		return 0;
376 	default:
377 		return -EINVAL;
378 	}
379 }
380 
vivid_sdr_g_tuner(struct file * file,void * fh,struct v4l2_tuner * vt)381 int vivid_sdr_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
382 {
383 	switch (vt->index) {
384 	case 0:
385 		strlcpy(vt->name, "ADC", sizeof(vt->name));
386 		vt->type = V4L2_TUNER_ADC;
387 		vt->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
388 		vt->rangelow = bands_adc[0].rangelow;
389 		vt->rangehigh = bands_adc[2].rangehigh;
390 		return 0;
391 	case 1:
392 		strlcpy(vt->name, "RF", sizeof(vt->name));
393 		vt->type = V4L2_TUNER_RF;
394 		vt->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
395 		vt->rangelow = bands_fm[0].rangelow;
396 		vt->rangehigh = bands_fm[0].rangehigh;
397 		return 0;
398 	default:
399 		return -EINVAL;
400 	}
401 }
402 
vivid_sdr_s_tuner(struct file * file,void * fh,const struct v4l2_tuner * vt)403 int vivid_sdr_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt)
404 {
405 	if (vt->index > 1)
406 		return -EINVAL;
407 	return 0;
408 }
409 
vidioc_enum_fmt_sdr_cap(struct file * file,void * fh,struct v4l2_fmtdesc * f)410 int vidioc_enum_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_fmtdesc *f)
411 {
412 	if (f->index)
413 		return -EINVAL;
414 	f->pixelformat = V4L2_SDR_FMT_CU8;
415 	strlcpy(f->description, "IQ U8", sizeof(f->description));
416 	return 0;
417 }
418 
vidioc_g_fmt_sdr_cap(struct file * file,void * fh,struct v4l2_format * f)419 int vidioc_g_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f)
420 {
421 	f->fmt.sdr.pixelformat = V4L2_SDR_FMT_CU8;
422 	f->fmt.sdr.buffersize = SDR_CAP_SAMPLES_PER_BUF * 2;
423 	memset(f->fmt.sdr.reserved, 0, sizeof(f->fmt.sdr.reserved));
424 	return 0;
425 }
426 
427 #define FIXP_N    (15)
428 #define FIXP_FRAC (1 << FIXP_N)
429 #define FIXP_2PI  ((int)(2 * 3.141592653589 * FIXP_FRAC))
430 
vivid_sdr_cap_process(struct vivid_dev * dev,struct vivid_buffer * buf)431 void vivid_sdr_cap_process(struct vivid_dev *dev, struct vivid_buffer *buf)
432 {
433 	u8 *vbuf = vb2_plane_vaddr(&buf->vb, 0);
434 	unsigned long i;
435 	unsigned long plane_size = vb2_plane_size(&buf->vb, 0);
436 	s32 src_phase_step;
437 	s32 mod_phase_step;
438 	s32 fixp_i;
439 	s32 fixp_q;
440 
441 	/*
442 	 * TODO: Generated beep tone goes very crackly when sample rate is
443 	 * increased to ~1Msps or more. That is because of huge rounding error
444 	 * of phase angle caused by used cosine implementation.
445 	 */
446 
447 	/* calculate phase step */
448 	#define BEEP_FREQ 1000 /* 1kHz beep */
449 	src_phase_step = DIV_ROUND_CLOSEST(FIXP_2PI * BEEP_FREQ,
450 			dev->sdr_adc_freq);
451 
452 	for (i = 0; i < plane_size; i += 2) {
453 		mod_phase_step = fixp_cos32_rad(dev->sdr_fixp_src_phase,
454 						FIXP_2PI) >> (31 - FIXP_N);
455 
456 		dev->sdr_fixp_src_phase += src_phase_step;
457 		dev->sdr_fixp_mod_phase += mod_phase_step / 4;
458 
459 		/*
460 		 * Transfer phases to [0 / 2xPI] in order to avoid variable
461 		 * overflow and make it suitable for cosine implementation
462 		 * used, which does not support negative angles.
463 		 */
464 		while (dev->sdr_fixp_mod_phase < FIXP_2PI)
465 			dev->sdr_fixp_mod_phase += FIXP_2PI;
466 		while (dev->sdr_fixp_mod_phase > FIXP_2PI)
467 			dev->sdr_fixp_mod_phase -= FIXP_2PI;
468 
469 		while (dev->sdr_fixp_src_phase > FIXP_2PI)
470 			dev->sdr_fixp_src_phase -= FIXP_2PI;
471 
472 		fixp_i = fixp_cos32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI);
473 		fixp_q = fixp_sin32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI);
474 
475 		/* Normalize fraction values represented with 32 bit precision
476 		 * to fixed point representation with FIXP_N bits */
477 		fixp_i >>= (31 - FIXP_N);
478 		fixp_q >>= (31 - FIXP_N);
479 
480 		/* convert 'fixp float' to u8 */
481 		/* u8 = X * 127.5f + 127.5f; where X is float [-1.0 / +1.0] */
482 		fixp_i = fixp_i * 1275 + FIXP_FRAC * 1275;
483 		fixp_q = fixp_q * 1275 + FIXP_FRAC * 1275;
484 		*vbuf++ = DIV_ROUND_CLOSEST(fixp_i, FIXP_FRAC * 10);
485 		*vbuf++ = DIV_ROUND_CLOSEST(fixp_q, FIXP_FRAC * 10);
486 	}
487 }
488