1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * The Virtual DTV test driver serves as a reference DVB driver and helps
4  * validate the existing APIs in the media subsystem. It can also aid
5  * developers working on userspace applications.
6  *
7  * When this module is loaded, it will attempt to modprobe 'dvb_vidtv_tuner'
8  * and 'dvb_vidtv_demod'.
9  *
10  * Copyright (C) 2020 Daniel W. S. Almeida
11  */
12 
13 #include <linux/dev_printk.h>
14 #include <linux/moduleparam.h>
15 #include <linux/mutex.h>
16 #include <linux/platform_device.h>
17 #include <linux/time.h>
18 #include <linux/types.h>
19 #include <linux/workqueue.h>
20 
21 #include "vidtv_bridge.h"
22 #include "vidtv_common.h"
23 #include "vidtv_demod.h"
24 #include "vidtv_mux.h"
25 #include "vidtv_ts.h"
26 #include "vidtv_tuner.h"
27 
28 #define MUX_BUF_MIN_SZ 90164
29 #define MUX_BUF_MAX_SZ (MUX_BUF_MIN_SZ * 10)
30 #define TUNER_DEFAULT_ADDR 0x68
31 #define DEMOD_DEFAULT_ADDR 0x60
32 #define VIDTV_DEFAULT_NETWORK_ID 0xff44
33 #define VIDTV_DEFAULT_NETWORK_NAME "LinuxTV.org"
34 #define VIDTV_DEFAULT_TS_ID 0x4081
35 
36 /*
37  * The LNBf fake parameters here are the ranges used by an
38  * Universal (extended) European LNBf, which is likely the most common LNBf
39  * found on Satellite digital TV system nowadays.
40  */
41 #define LNB_CUT_FREQUENCY	11700000	/* high IF frequency */
42 #define LNB_LOW_FREQ		9750000		/* low IF frequency */
43 #define LNB_HIGH_FREQ		10600000	/* transition frequency */
44 
45 static unsigned int drop_tslock_prob_on_low_snr;
46 module_param(drop_tslock_prob_on_low_snr, uint, 0);
47 MODULE_PARM_DESC(drop_tslock_prob_on_low_snr,
48 		 "Probability of losing the TS lock if the signal quality is bad");
49 
50 static unsigned int recover_tslock_prob_on_good_snr;
51 module_param(recover_tslock_prob_on_good_snr, uint, 0);
52 MODULE_PARM_DESC(recover_tslock_prob_on_good_snr,
53 		 "Probability recovering the TS lock when the signal improves");
54 
55 static unsigned int mock_power_up_delay_msec;
56 module_param(mock_power_up_delay_msec, uint, 0);
57 MODULE_PARM_DESC(mock_power_up_delay_msec, "Simulate a power up delay");
58 
59 static unsigned int mock_tune_delay_msec;
60 module_param(mock_tune_delay_msec, uint, 0);
61 MODULE_PARM_DESC(mock_tune_delay_msec, "Simulate a tune delay");
62 
63 static unsigned int vidtv_valid_dvb_t_freqs[NUM_VALID_TUNER_FREQS] = {
64 	474000000
65 };
66 
67 module_param_array(vidtv_valid_dvb_t_freqs, uint, NULL, 0);
68 MODULE_PARM_DESC(vidtv_valid_dvb_t_freqs,
69 		 "Valid DVB-T frequencies to simulate, in Hz");
70 
71 static unsigned int vidtv_valid_dvb_c_freqs[NUM_VALID_TUNER_FREQS] = {
72 	474000000
73 };
74 
75 module_param_array(vidtv_valid_dvb_c_freqs, uint, NULL, 0);
76 MODULE_PARM_DESC(vidtv_valid_dvb_c_freqs,
77 		 "Valid DVB-C frequencies to simulate, in Hz");
78 
79 static unsigned int vidtv_valid_dvb_s_freqs[NUM_VALID_TUNER_FREQS] = {
80 	11362000
81 };
82 module_param_array(vidtv_valid_dvb_s_freqs, uint, NULL, 0);
83 MODULE_PARM_DESC(vidtv_valid_dvb_s_freqs,
84 		 "Valid DVB-S/S2 frequencies to simulate at Ku-Band, in kHz");
85 
86 static unsigned int max_frequency_shift_hz;
87 module_param(max_frequency_shift_hz, uint, 0);
88 MODULE_PARM_DESC(max_frequency_shift_hz,
89 		 "Maximum shift in HZ allowed when tuning in a channel");
90 
91 DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nums);
92 
93 /*
94  * Influences the signal acquisition time. See ISO/IEC 13818-1 : 2000. p. 113.
95  */
96 static unsigned int si_period_msec = 40;
97 module_param(si_period_msec, uint, 0);
98 MODULE_PARM_DESC(si_period_msec, "How often to send SI packets. Default: 40ms");
99 
100 static unsigned int pcr_period_msec = 40;
101 module_param(pcr_period_msec, uint, 0);
102 MODULE_PARM_DESC(pcr_period_msec,
103 		 "How often to send PCR packets. Default: 40ms");
104 
105 static unsigned int mux_rate_kbytes_sec = 4096;
106 module_param(mux_rate_kbytes_sec, uint, 0);
107 MODULE_PARM_DESC(mux_rate_kbytes_sec, "Mux rate: will pad stream if below");
108 
109 static unsigned int pcr_pid = 0x200;
110 module_param(pcr_pid, uint, 0);
111 MODULE_PARM_DESC(pcr_pid, "PCR PID for all channels: defaults to 0x200");
112 
113 static unsigned int mux_buf_sz_pkts;
114 module_param(mux_buf_sz_pkts, uint, 0);
115 MODULE_PARM_DESC(mux_buf_sz_pkts,
116 		 "Size for the internal mux buffer in multiples of 188 bytes");
117 
118 static u32 vidtv_bridge_mux_buf_sz_for_mux_rate(void)
119 {
120 	u32 max_elapsed_time_msecs =  VIDTV_MAX_SLEEP_USECS / USEC_PER_MSEC;
121 	u32 mux_buf_sz = mux_buf_sz_pkts * TS_PACKET_LEN;
122 	u32 nbytes_expected;
123 
124 	nbytes_expected = mux_rate_kbytes_sec;
125 	nbytes_expected *= max_elapsed_time_msecs;
126 
127 	mux_buf_sz = roundup(nbytes_expected, TS_PACKET_LEN);
128 	mux_buf_sz += mux_buf_sz / 10;
129 
130 	if (mux_buf_sz < MUX_BUF_MIN_SZ)
131 		mux_buf_sz = MUX_BUF_MIN_SZ;
132 
133 	if (mux_buf_sz > MUX_BUF_MAX_SZ)
134 		mux_buf_sz = MUX_BUF_MAX_SZ;
135 
136 	return mux_buf_sz;
137 }
138 
139 static bool vidtv_bridge_check_demod_lock(struct vidtv_dvb *dvb, u32 n)
140 {
141 	enum fe_status status;
142 
143 	dvb->fe[n]->ops.read_status(dvb->fe[n], &status);
144 
145 	return status == (FE_HAS_SIGNAL  |
146 			  FE_HAS_CARRIER |
147 			  FE_HAS_VITERBI |
148 			  FE_HAS_SYNC    |
149 			  FE_HAS_LOCK);
150 }
151 
152 /*
153  * called on a separate thread by the mux when new packets become available
154  */
155 static void vidtv_bridge_on_new_pkts_avail(void *priv, u8 *buf, u32 npkts)
156 {
157 	struct vidtv_dvb *dvb = priv;
158 
159 	/* drop packets if we lose the lock */
160 	if (vidtv_bridge_check_demod_lock(dvb, 0))
161 		dvb_dmx_swfilter_packets(&dvb->demux, buf, npkts);
162 }
163 
164 static int vidtv_start_streaming(struct vidtv_dvb *dvb)
165 {
166 	struct vidtv_mux_init_args mux_args = {
167 		.mux_rate_kbytes_sec         = mux_rate_kbytes_sec,
168 		.on_new_packets_available_cb = vidtv_bridge_on_new_pkts_avail,
169 		.pcr_period_usecs            = pcr_period_msec * USEC_PER_MSEC,
170 		.si_period_usecs             = si_period_msec * USEC_PER_MSEC,
171 		.pcr_pid                     = pcr_pid,
172 		.transport_stream_id         = VIDTV_DEFAULT_TS_ID,
173 		.network_id                  = VIDTV_DEFAULT_NETWORK_ID,
174 		.network_name                = VIDTV_DEFAULT_NETWORK_NAME,
175 		.priv                        = dvb,
176 	};
177 	struct device *dev = &dvb->pdev->dev;
178 	u32 mux_buf_sz;
179 
180 	if (dvb->streaming) {
181 		dev_warn_ratelimited(dev, "Already streaming. Skipping.\n");
182 		return 0;
183 	}
184 
185 	if (mux_buf_sz_pkts)
186 		mux_buf_sz = mux_buf_sz_pkts;
187 	else
188 		mux_buf_sz = vidtv_bridge_mux_buf_sz_for_mux_rate();
189 
190 	mux_args.mux_buf_sz  = mux_buf_sz;
191 
192 	dvb->streaming = true;
193 	dvb->mux = vidtv_mux_init(dvb->fe[0], dev, &mux_args);
194 	if (!dvb->mux)
195 		return -ENOMEM;
196 	vidtv_mux_start_thread(dvb->mux);
197 
198 	dev_dbg_ratelimited(dev, "Started streaming\n");
199 	return 0;
200 }
201 
202 static int vidtv_stop_streaming(struct vidtv_dvb *dvb)
203 {
204 	struct device *dev = &dvb->pdev->dev;
205 
206 	dvb->streaming = false;
207 	vidtv_mux_stop_thread(dvb->mux);
208 	vidtv_mux_destroy(dvb->mux);
209 	dvb->mux = NULL;
210 
211 	dev_dbg_ratelimited(dev, "Stopped streaming\n");
212 	return 0;
213 }
214 
215 static int vidtv_start_feed(struct dvb_demux_feed *feed)
216 {
217 	struct dvb_demux *demux = feed->demux;
218 	struct vidtv_dvb *dvb   = demux->priv;
219 	int ret;
220 	int rc;
221 
222 	if (!demux->dmx.frontend)
223 		return -EINVAL;
224 
225 	mutex_lock(&dvb->feed_lock);
226 
227 	dvb->nfeeds++;
228 	rc = dvb->nfeeds;
229 
230 	if (dvb->nfeeds == 1) {
231 		ret = vidtv_start_streaming(dvb);
232 		if (ret < 0)
233 			rc = ret;
234 	}
235 
236 	mutex_unlock(&dvb->feed_lock);
237 	return rc;
238 }
239 
240 static int vidtv_stop_feed(struct dvb_demux_feed *feed)
241 {
242 	struct dvb_demux *demux = feed->demux;
243 	struct vidtv_dvb *dvb   = demux->priv;
244 	int err = 0;
245 
246 	mutex_lock(&dvb->feed_lock);
247 	dvb->nfeeds--;
248 
249 	if (!dvb->nfeeds)
250 		err = vidtv_stop_streaming(dvb);
251 
252 	mutex_unlock(&dvb->feed_lock);
253 	return err;
254 }
255 
256 static struct dvb_frontend *vidtv_get_frontend_ptr(struct i2c_client *c)
257 {
258 	struct vidtv_demod_state *state = i2c_get_clientdata(c);
259 
260 	/* the demod will set this when its probe function runs */
261 	return &state->frontend;
262 }
263 
264 static int vidtv_master_xfer(struct i2c_adapter *i2c_adap,
265 			     struct i2c_msg msgs[],
266 			     int num)
267 {
268 	/*
269 	 * Right now, this virtual driver doesn't really send or receive
270 	 * messages from I2C. A real driver will require an implementation
271 	 * here.
272 	 */
273 	return 0;
274 }
275 
276 static u32 vidtv_i2c_func(struct i2c_adapter *adapter)
277 {
278 	return I2C_FUNC_I2C;
279 }
280 
281 static const struct i2c_algorithm vidtv_i2c_algorithm = {
282 	.master_xfer   = vidtv_master_xfer,
283 	.functionality = vidtv_i2c_func,
284 };
285 
286 static int vidtv_bridge_i2c_register_adap(struct vidtv_dvb *dvb)
287 {
288 	struct i2c_adapter *i2c_adapter = &dvb->i2c_adapter;
289 
290 	strscpy(i2c_adapter->name, "vidtv_i2c", sizeof(i2c_adapter->name));
291 	i2c_adapter->owner      = THIS_MODULE;
292 	i2c_adapter->algo       = &vidtv_i2c_algorithm;
293 	i2c_adapter->algo_data  = NULL;
294 	i2c_adapter->timeout    = 500;
295 	i2c_adapter->retries    = 3;
296 	i2c_adapter->dev.parent = &dvb->pdev->dev;
297 
298 	i2c_set_adapdata(i2c_adapter, dvb);
299 	return i2c_add_adapter(&dvb->i2c_adapter);
300 }
301 
302 static int vidtv_bridge_register_adap(struct vidtv_dvb *dvb)
303 {
304 	int ret = 0;
305 
306 	ret = dvb_register_adapter(&dvb->adapter,
307 				   KBUILD_MODNAME,
308 				   THIS_MODULE,
309 				   &dvb->i2c_adapter.dev,
310 				   adapter_nums);
311 
312 	return ret;
313 }
314 
315 static int vidtv_bridge_dmx_init(struct vidtv_dvb *dvb)
316 {
317 	dvb->demux.dmx.capabilities = DMX_TS_FILTERING |
318 				      DMX_SECTION_FILTERING;
319 
320 	dvb->demux.priv       = dvb;
321 	dvb->demux.filternum  = 256;
322 	dvb->demux.feednum    = 256;
323 	dvb->demux.start_feed = vidtv_start_feed;
324 	dvb->demux.stop_feed  = vidtv_stop_feed;
325 
326 	return dvb_dmx_init(&dvb->demux);
327 }
328 
329 static int vidtv_bridge_dmxdev_init(struct vidtv_dvb *dvb)
330 {
331 	dvb->dmx_dev.filternum    = 256;
332 	dvb->dmx_dev.demux        = &dvb->demux.dmx;
333 	dvb->dmx_dev.capabilities = 0;
334 
335 	return dvb_dmxdev_init(&dvb->dmx_dev, &dvb->adapter);
336 }
337 
338 static int vidtv_bridge_probe_demod(struct vidtv_dvb *dvb, u32 n)
339 {
340 	struct vidtv_demod_config cfg = {
341 		.drop_tslock_prob_on_low_snr     = drop_tslock_prob_on_low_snr,
342 		.recover_tslock_prob_on_good_snr = recover_tslock_prob_on_good_snr,
343 	};
344 	dvb->i2c_client_demod[n] = dvb_module_probe("dvb_vidtv_demod",
345 						    NULL,
346 						    &dvb->i2c_adapter,
347 						    DEMOD_DEFAULT_ADDR,
348 						    &cfg);
349 
350 	/* driver will not work anyways so bail out */
351 	if (!dvb->i2c_client_demod[n])
352 		return -ENODEV;
353 
354 	/* retrieve a ptr to the frontend state */
355 	dvb->fe[n] = vidtv_get_frontend_ptr(dvb->i2c_client_demod[n]);
356 
357 	return 0;
358 }
359 
360 static int vidtv_bridge_probe_tuner(struct vidtv_dvb *dvb, u32 n)
361 {
362 	struct vidtv_tuner_config cfg = {
363 		.fe                       = dvb->fe[n],
364 		.mock_power_up_delay_msec = mock_power_up_delay_msec,
365 		.mock_tune_delay_msec     = mock_tune_delay_msec,
366 	};
367 	u32 freq;
368 	int i;
369 
370 	/* TODO: check if the frequencies are at a valid range */
371 
372 	memcpy(cfg.vidtv_valid_dvb_t_freqs,
373 	       vidtv_valid_dvb_t_freqs,
374 	       sizeof(vidtv_valid_dvb_t_freqs));
375 
376 	memcpy(cfg.vidtv_valid_dvb_c_freqs,
377 	       vidtv_valid_dvb_c_freqs,
378 	       sizeof(vidtv_valid_dvb_c_freqs));
379 
380 	/*
381 	 * Convert Satellite frequencies from Ku-band in kHZ into S-band
382 	 * frequencies in Hz.
383 	 */
384 	for (i = 0; i < ARRAY_SIZE(vidtv_valid_dvb_s_freqs); i++) {
385 		freq = vidtv_valid_dvb_s_freqs[i];
386 		if (freq) {
387 			if (freq < LNB_CUT_FREQUENCY)
388 				freq = abs(freq - LNB_LOW_FREQ);
389 			else
390 				freq = abs(freq - LNB_HIGH_FREQ);
391 		}
392 		cfg.vidtv_valid_dvb_s_freqs[i] = freq;
393 	}
394 
395 	cfg.max_frequency_shift_hz = max_frequency_shift_hz;
396 
397 	dvb->i2c_client_tuner[n] = dvb_module_probe("dvb_vidtv_tuner",
398 						    NULL,
399 						    &dvb->i2c_adapter,
400 						    TUNER_DEFAULT_ADDR,
401 						    &cfg);
402 
403 	return (dvb->i2c_client_tuner[n]) ? 0 : -ENODEV;
404 }
405 
406 static int vidtv_bridge_dvb_init(struct vidtv_dvb *dvb)
407 {
408 	int ret, i, j;
409 
410 	ret = vidtv_bridge_i2c_register_adap(dvb);
411 	if (ret < 0)
412 		goto fail_i2c;
413 
414 	ret = vidtv_bridge_register_adap(dvb);
415 	if (ret < 0)
416 		goto fail_adapter;
417 
418 	for (i = 0; i < NUM_FE; ++i) {
419 		ret = vidtv_bridge_probe_demod(dvb, i);
420 		if (ret < 0)
421 			goto fail_demod_probe;
422 
423 		ret = vidtv_bridge_probe_tuner(dvb, i);
424 		if (ret < 0)
425 			goto fail_tuner_probe;
426 
427 		ret = dvb_register_frontend(&dvb->adapter, dvb->fe[i]);
428 		if (ret < 0)
429 			goto fail_fe;
430 	}
431 
432 	ret = vidtv_bridge_dmx_init(dvb);
433 	if (ret < 0)
434 		goto fail_dmx;
435 
436 	ret = vidtv_bridge_dmxdev_init(dvb);
437 	if (ret < 0)
438 		goto fail_dmx_dev;
439 
440 	for (j = 0; j < NUM_FE; ++j) {
441 		ret = dvb->demux.dmx.connect_frontend(&dvb->demux.dmx,
442 						      &dvb->dmx_fe[j]);
443 		if (ret < 0)
444 			goto fail_dmx_conn;
445 
446 		/*
447 		 * The source of the demux is a frontend connected
448 		 * to the demux.
449 		 */
450 		dvb->dmx_fe[j].source = DMX_FRONTEND_0;
451 	}
452 
453 	return ret;
454 
455 fail_dmx_conn:
456 	for (j = j - 1; j >= 0; --j)
457 		dvb->demux.dmx.remove_frontend(&dvb->demux.dmx,
458 					       &dvb->dmx_fe[j]);
459 fail_dmx_dev:
460 	dvb_dmxdev_release(&dvb->dmx_dev);
461 fail_dmx:
462 	dvb_dmx_release(&dvb->demux);
463 fail_fe:
464 	for (j = i; j >= 0; --j)
465 		dvb_unregister_frontend(dvb->fe[j]);
466 fail_tuner_probe:
467 	for (j = i; j >= 0; --j)
468 		if (dvb->i2c_client_tuner[j])
469 			dvb_module_release(dvb->i2c_client_tuner[j]);
470 
471 fail_demod_probe:
472 	for (j = i; j >= 0; --j)
473 		if (dvb->i2c_client_demod[j])
474 			dvb_module_release(dvb->i2c_client_demod[j]);
475 
476 fail_adapter:
477 	dvb_unregister_adapter(&dvb->adapter);
478 
479 fail_i2c:
480 	i2c_del_adapter(&dvb->i2c_adapter);
481 
482 	return ret;
483 }
484 
485 static int vidtv_bridge_probe(struct platform_device *pdev)
486 {
487 	struct vidtv_dvb *dvb;
488 	int ret;
489 
490 	dvb = kzalloc(sizeof(*dvb), GFP_KERNEL);
491 	if (!dvb)
492 		return -ENOMEM;
493 
494 	dvb->pdev = pdev;
495 
496 	ret = vidtv_bridge_dvb_init(dvb);
497 	if (ret < 0)
498 		goto err_dvb;
499 
500 	mutex_init(&dvb->feed_lock);
501 
502 	platform_set_drvdata(pdev, dvb);
503 
504 	dev_info(&pdev->dev, "Successfully initialized vidtv!\n");
505 	return ret;
506 
507 err_dvb:
508 	kfree(dvb);
509 	return ret;
510 }
511 
512 static int vidtv_bridge_remove(struct platform_device *pdev)
513 {
514 	struct vidtv_dvb *dvb;
515 	u32 i;
516 
517 	dvb = platform_get_drvdata(pdev);
518 
519 	mutex_destroy(&dvb->feed_lock);
520 
521 	for (i = 0; i < NUM_FE; ++i) {
522 		dvb_unregister_frontend(dvb->fe[i]);
523 		dvb_module_release(dvb->i2c_client_tuner[i]);
524 		dvb_module_release(dvb->i2c_client_demod[i]);
525 	}
526 
527 	dvb_dmxdev_release(&dvb->dmx_dev);
528 	dvb_dmx_release(&dvb->demux);
529 	dvb_unregister_adapter(&dvb->adapter);
530 
531 	return 0;
532 }
533 
534 static void vidtv_bridge_dev_release(struct device *dev)
535 {
536 }
537 
538 static struct platform_device vidtv_bridge_dev = {
539 	.name		= "vidtv_bridge",
540 	.dev.release	= vidtv_bridge_dev_release,
541 };
542 
543 static struct platform_driver vidtv_bridge_driver = {
544 	.driver = {
545 		.name                = "vidtv_bridge",
546 		.suppress_bind_attrs = true,
547 	},
548 	.probe    = vidtv_bridge_probe,
549 	.remove   = vidtv_bridge_remove,
550 };
551 
552 static void __exit vidtv_bridge_exit(void)
553 {
554 	platform_driver_unregister(&vidtv_bridge_driver);
555 	platform_device_unregister(&vidtv_bridge_dev);
556 }
557 
558 static int __init vidtv_bridge_init(void)
559 {
560 	int ret;
561 
562 	ret = platform_device_register(&vidtv_bridge_dev);
563 	if (ret)
564 		return ret;
565 
566 	ret = platform_driver_register(&vidtv_bridge_driver);
567 	if (ret)
568 		platform_device_unregister(&vidtv_bridge_dev);
569 
570 	return ret;
571 }
572 
573 module_init(vidtv_bridge_init);
574 module_exit(vidtv_bridge_exit);
575 
576 MODULE_DESCRIPTION("Virtual Digital TV Test Driver");
577 MODULE_AUTHOR("Daniel W. S. Almeida");
578 MODULE_LICENSE("GPL");
579 MODULE_ALIAS("vidtv");
580 MODULE_ALIAS("dvb_vidtv");
581