1 /*
2  * dvb_frontend.c: DVB frontend tuning interface/thread
3  *
4  *
5  * Copyright (C) 1999-2001 Ralph  Metzler
6  *			   Marcus Metzler
7  *			   Holger Waechtler
8  *				      for convergence integrated media GmbH
9  *
10  * Copyright (C) 2004 Andrew de Quincey (tuning thread cleanup)
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
20  * GNU General Public License for more details.
21  * To obtain the license, point your browser to
22  * http://www.gnu.org/copyleft/gpl.html
23  */
24 
25 /* Enables DVBv3 compatibility bits at the headers */
26 #define __DVB_CORE__
27 
28 #define pr_fmt(fmt) "dvb_frontend: " fmt
29 
30 #include <linux/string.h>
31 #include <linux/kernel.h>
32 #include <linux/sched/signal.h>
33 #include <linux/wait.h>
34 #include <linux/slab.h>
35 #include <linux/poll.h>
36 #include <linux/semaphore.h>
37 #include <linux/module.h>
38 #include <linux/list.h>
39 #include <linux/freezer.h>
40 #include <linux/jiffies.h>
41 #include <linux/kthread.h>
42 #include <linux/ktime.h>
43 #include <asm/processor.h>
44 
45 #include "dvb_frontend.h"
46 #include "dvbdev.h"
47 #include <linux/dvb/version.h>
48 
49 static int dvb_frontend_debug;
50 static int dvb_shutdown_timeout;
51 static int dvb_force_auto_inversion;
52 static int dvb_override_tune_delay;
53 static int dvb_powerdown_on_sleep = 1;
54 static int dvb_mfe_wait_time = 5;
55 
56 module_param_named(frontend_debug, dvb_frontend_debug, int, 0644);
57 MODULE_PARM_DESC(frontend_debug, "Turn on/off frontend core debugging (default:off).");
58 module_param(dvb_shutdown_timeout, int, 0644);
59 MODULE_PARM_DESC(dvb_shutdown_timeout, "wait <shutdown_timeout> seconds after close() before suspending hardware");
60 module_param(dvb_force_auto_inversion, int, 0644);
61 MODULE_PARM_DESC(dvb_force_auto_inversion, "0: normal (default), 1: INVERSION_AUTO forced always");
62 module_param(dvb_override_tune_delay, int, 0644);
63 MODULE_PARM_DESC(dvb_override_tune_delay, "0: normal (default), >0 => delay in milliseconds to wait for lock after a tune attempt");
64 module_param(dvb_powerdown_on_sleep, int, 0644);
65 MODULE_PARM_DESC(dvb_powerdown_on_sleep, "0: do not power down, 1: turn LNB voltage off on sleep (default)");
66 module_param(dvb_mfe_wait_time, int, 0644);
67 MODULE_PARM_DESC(dvb_mfe_wait_time, "Wait up to <mfe_wait_time> seconds on open() for multi-frontend to become available (default:5 seconds)");
68 
69 #define dprintk(fmt, arg...) \
70 	printk(KERN_DEBUG pr_fmt("%s: " fmt), __func__, ##arg)
71 
72 #define FESTATE_IDLE 1
73 #define FESTATE_RETUNE 2
74 #define FESTATE_TUNING_FAST 4
75 #define FESTATE_TUNING_SLOW 8
76 #define FESTATE_TUNED 16
77 #define FESTATE_ZIGZAG_FAST 32
78 #define FESTATE_ZIGZAG_SLOW 64
79 #define FESTATE_DISEQC 128
80 #define FESTATE_ERROR 256
81 #define FESTATE_WAITFORLOCK (FESTATE_TUNING_FAST | FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW | FESTATE_DISEQC)
82 #define FESTATE_SEARCHING_FAST (FESTATE_TUNING_FAST | FESTATE_ZIGZAG_FAST)
83 #define FESTATE_SEARCHING_SLOW (FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_SLOW)
84 #define FESTATE_LOSTLOCK (FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW)
85 
86 /*
87  * FESTATE_IDLE. No tuning parameters have been supplied and the loop is idling.
88  * FESTATE_RETUNE. Parameters have been supplied, but we have not yet performed the first tune.
89  * FESTATE_TUNING_FAST. Tuning parameters have been supplied and fast zigzag scan is in progress.
90  * FESTATE_TUNING_SLOW. Tuning parameters have been supplied. Fast zigzag failed, so we're trying again, but slower.
91  * FESTATE_TUNED. The frontend has successfully locked on.
92  * FESTATE_ZIGZAG_FAST. The lock has been lost, and a fast zigzag has been initiated to try and regain it.
93  * FESTATE_ZIGZAG_SLOW. The lock has been lost. Fast zigzag has been failed, so we're trying again, but slower.
94  * FESTATE_DISEQC. A DISEQC command has just been issued.
95  * FESTATE_WAITFORLOCK. When we're waiting for a lock.
96  * FESTATE_SEARCHING_FAST. When we're searching for a signal using a fast zigzag scan.
97  * FESTATE_SEARCHING_SLOW. When we're searching for a signal using a slow zigzag scan.
98  * FESTATE_LOSTLOCK. When the lock has been lost, and we're searching it again.
99  */
100 
101 static DEFINE_MUTEX(frontend_mutex);
102 
103 struct dvb_frontend_private {
104 	/* thread/frontend values */
105 	struct dvb_device *dvbdev;
106 	struct dvb_frontend_parameters parameters_out;
107 	struct dvb_fe_events events;
108 	struct semaphore sem;
109 	struct list_head list_head;
110 	wait_queue_head_t wait_queue;
111 	struct task_struct *thread;
112 	unsigned long release_jiffies;
113 	unsigned int wakeup;
114 	enum fe_status status;
115 	unsigned long tune_mode_flags;
116 	unsigned int delay;
117 	unsigned int reinitialise;
118 	int tone;
119 	int voltage;
120 
121 	/* swzigzag values */
122 	unsigned int state;
123 	unsigned int bending;
124 	int lnb_drift;
125 	unsigned int inversion;
126 	unsigned int auto_step;
127 	unsigned int auto_sub_step;
128 	unsigned int started_auto_step;
129 	unsigned int min_delay;
130 	unsigned int max_drift;
131 	unsigned int step_size;
132 	int quality;
133 	unsigned int check_wrapped;
134 	enum dvbfe_search algo_status;
135 
136 #if defined(CONFIG_MEDIA_CONTROLLER_DVB)
137 	struct media_pipeline pipe;
138 #endif
139 };
140 
141 static void dvb_frontend_invoke_release(struct dvb_frontend *fe,
142 					void (*release)(struct dvb_frontend *fe));
143 
144 static void __dvb_frontend_free(struct dvb_frontend *fe)
145 {
146 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
147 
148 	if (!fepriv)
149 		return;
150 
151 	dvb_free_device(fepriv->dvbdev);
152 
153 	dvb_frontend_invoke_release(fe, fe->ops.release);
154 
155 	kfree(fepriv);
156 	fe->frontend_priv = NULL;
157 }
158 
159 static void dvb_frontend_free(struct kref *ref)
160 {
161 	struct dvb_frontend *fe =
162 		container_of(ref, struct dvb_frontend, refcount);
163 
164 	__dvb_frontend_free(fe);
165 }
166 
167 static void dvb_frontend_put(struct dvb_frontend *fe)
168 {
169 	/*
170 	 * Check if the frontend was registered, as otherwise
171 	 * kref was not initialized yet.
172 	 */
173 	if (fe->frontend_priv)
174 		kref_put(&fe->refcount, dvb_frontend_free);
175 	else
176 		__dvb_frontend_free(fe);
177 }
178 
179 static void dvb_frontend_get(struct dvb_frontend *fe)
180 {
181 	kref_get(&fe->refcount);
182 }
183 
184 static void dvb_frontend_wakeup(struct dvb_frontend *fe);
185 static int dtv_get_frontend(struct dvb_frontend *fe,
186 			    struct dtv_frontend_properties *c,
187 			    struct dvb_frontend_parameters *p_out);
188 static int
189 dtv_property_legacy_params_sync(struct dvb_frontend *fe,
190 				const struct dtv_frontend_properties *c,
191 				struct dvb_frontend_parameters *p);
192 
193 static bool has_get_frontend(struct dvb_frontend *fe)
194 {
195 	return fe->ops.get_frontend != NULL;
196 }
197 
198 /*
199  * Due to DVBv3 API calls, a delivery system should be mapped into one of
200  * the 4 DVBv3 delivery systems (FE_QPSK, FE_QAM, FE_OFDM or FE_ATSC),
201  * otherwise, a DVBv3 call will fail.
202  */
203 enum dvbv3_emulation_type {
204 	DVBV3_UNKNOWN,
205 	DVBV3_QPSK,
206 	DVBV3_QAM,
207 	DVBV3_OFDM,
208 	DVBV3_ATSC,
209 };
210 
211 static enum dvbv3_emulation_type dvbv3_type(u32 delivery_system)
212 {
213 	switch (delivery_system) {
214 	case SYS_DVBC_ANNEX_A:
215 	case SYS_DVBC_ANNEX_C:
216 		return DVBV3_QAM;
217 	case SYS_DVBS:
218 	case SYS_DVBS2:
219 	case SYS_TURBO:
220 	case SYS_ISDBS:
221 	case SYS_DSS:
222 		return DVBV3_QPSK;
223 	case SYS_DVBT:
224 	case SYS_DVBT2:
225 	case SYS_ISDBT:
226 	case SYS_DTMB:
227 		return DVBV3_OFDM;
228 	case SYS_ATSC:
229 	case SYS_ATSCMH:
230 	case SYS_DVBC_ANNEX_B:
231 		return DVBV3_ATSC;
232 	case SYS_UNDEFINED:
233 	case SYS_ISDBC:
234 	case SYS_DVBH:
235 	case SYS_DAB:
236 	default:
237 		/*
238 		 * Doesn't know how to emulate those types and/or
239 		 * there's no frontend driver from this type yet
240 		 * with some emulation code, so, we're not sure yet how
241 		 * to handle them, or they're not compatible with a DVBv3 call.
242 		 */
243 		return DVBV3_UNKNOWN;
244 	}
245 }
246 
247 static void dvb_frontend_add_event(struct dvb_frontend *fe,
248 				   enum fe_status status)
249 {
250 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
251 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
252 	struct dvb_fe_events *events = &fepriv->events;
253 	struct dvb_frontend_event *e;
254 	int wp;
255 
256 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
257 
258 	if ((status & FE_HAS_LOCK) && has_get_frontend(fe))
259 		dtv_get_frontend(fe, c, &fepriv->parameters_out);
260 
261 	mutex_lock(&events->mtx);
262 
263 	wp = (events->eventw + 1) % MAX_EVENT;
264 	if (wp == events->eventr) {
265 		events->overflow = 1;
266 		events->eventr = (events->eventr + 1) % MAX_EVENT;
267 	}
268 
269 	e = &events->events[events->eventw];
270 	e->status = status;
271 	e->parameters = fepriv->parameters_out;
272 
273 	events->eventw = wp;
274 
275 	mutex_unlock(&events->mtx);
276 
277 	wake_up_interruptible (&events->wait_queue);
278 }
279 
280 static int dvb_frontend_get_event(struct dvb_frontend *fe,
281 			    struct dvb_frontend_event *event, int flags)
282 {
283 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
284 	struct dvb_fe_events *events = &fepriv->events;
285 
286 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
287 
288 	if (events->overflow) {
289 		events->overflow = 0;
290 		return -EOVERFLOW;
291 	}
292 
293 	if (events->eventw == events->eventr) {
294 		int ret;
295 
296 		if (flags & O_NONBLOCK)
297 			return -EWOULDBLOCK;
298 
299 		up(&fepriv->sem);
300 
301 		ret = wait_event_interruptible (events->wait_queue,
302 						events->eventw != events->eventr);
303 
304 		if (down_interruptible (&fepriv->sem))
305 			return -ERESTARTSYS;
306 
307 		if (ret < 0)
308 			return ret;
309 	}
310 
311 	mutex_lock(&events->mtx);
312 	*event = events->events[events->eventr];
313 	events->eventr = (events->eventr + 1) % MAX_EVENT;
314 	mutex_unlock(&events->mtx);
315 
316 	return 0;
317 }
318 
319 static void dvb_frontend_clear_events(struct dvb_frontend *fe)
320 {
321 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
322 	struct dvb_fe_events *events = &fepriv->events;
323 
324 	mutex_lock(&events->mtx);
325 	events->eventr = events->eventw;
326 	mutex_unlock(&events->mtx);
327 }
328 
329 static void dvb_frontend_init(struct dvb_frontend *fe)
330 {
331 	dev_dbg(fe->dvb->device,
332 			"%s: initialising adapter %i frontend %i (%s)...\n",
333 			__func__, fe->dvb->num, fe->id, fe->ops.info.name);
334 
335 	if (fe->ops.init)
336 		fe->ops.init(fe);
337 	if (fe->ops.tuner_ops.init) {
338 		if (fe->ops.i2c_gate_ctrl)
339 			fe->ops.i2c_gate_ctrl(fe, 1);
340 		fe->ops.tuner_ops.init(fe);
341 		if (fe->ops.i2c_gate_ctrl)
342 			fe->ops.i2c_gate_ctrl(fe, 0);
343 	}
344 }
345 
346 void dvb_frontend_reinitialise(struct dvb_frontend *fe)
347 {
348 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
349 
350 	fepriv->reinitialise = 1;
351 	dvb_frontend_wakeup(fe);
352 }
353 EXPORT_SYMBOL(dvb_frontend_reinitialise);
354 
355 static void dvb_frontend_swzigzag_update_delay(struct dvb_frontend_private *fepriv, int locked)
356 {
357 	int q2;
358 	struct dvb_frontend *fe = fepriv->dvbdev->priv;
359 
360 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
361 
362 	if (locked)
363 		(fepriv->quality) = (fepriv->quality * 220 + 36*256) / 256;
364 	else
365 		(fepriv->quality) = (fepriv->quality * 220 + 0) / 256;
366 
367 	q2 = fepriv->quality - 128;
368 	q2 *= q2;
369 
370 	fepriv->delay = fepriv->min_delay + q2 * HZ / (128*128);
371 }
372 
373 /**
374  * Performs automatic twiddling of frontend parameters.
375  *
376  * @param fe The frontend concerned.
377  * @param check_wrapped Checks if an iteration has completed. DO NOT SET ON THE FIRST ATTEMPT
378  * @returns Number of complete iterations that have been performed.
379  */
380 static int dvb_frontend_swzigzag_autotune(struct dvb_frontend *fe, int check_wrapped)
381 {
382 	int autoinversion;
383 	int ready = 0;
384 	int fe_set_err = 0;
385 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
386 	struct dtv_frontend_properties *c = &fe->dtv_property_cache, tmp;
387 	int original_inversion = c->inversion;
388 	u32 original_frequency = c->frequency;
389 
390 	/* are we using autoinversion? */
391 	autoinversion = ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) &&
392 			 (c->inversion == INVERSION_AUTO));
393 
394 	/* setup parameters correctly */
395 	while(!ready) {
396 		/* calculate the lnb_drift */
397 		fepriv->lnb_drift = fepriv->auto_step * fepriv->step_size;
398 
399 		/* wrap the auto_step if we've exceeded the maximum drift */
400 		if (fepriv->lnb_drift > fepriv->max_drift) {
401 			fepriv->auto_step = 0;
402 			fepriv->auto_sub_step = 0;
403 			fepriv->lnb_drift = 0;
404 		}
405 
406 		/* perform inversion and +/- zigzag */
407 		switch(fepriv->auto_sub_step) {
408 		case 0:
409 			/* try with the current inversion and current drift setting */
410 			ready = 1;
411 			break;
412 
413 		case 1:
414 			if (!autoinversion) break;
415 
416 			fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF;
417 			ready = 1;
418 			break;
419 
420 		case 2:
421 			if (fepriv->lnb_drift == 0) break;
422 
423 			fepriv->lnb_drift = -fepriv->lnb_drift;
424 			ready = 1;
425 			break;
426 
427 		case 3:
428 			if (fepriv->lnb_drift == 0) break;
429 			if (!autoinversion) break;
430 
431 			fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF;
432 			fepriv->lnb_drift = -fepriv->lnb_drift;
433 			ready = 1;
434 			break;
435 
436 		default:
437 			fepriv->auto_step++;
438 			fepriv->auto_sub_step = -1; /* it'll be incremented to 0 in a moment */
439 			break;
440 		}
441 
442 		if (!ready) fepriv->auto_sub_step++;
443 	}
444 
445 	/* if this attempt would hit where we started, indicate a complete
446 	 * iteration has occurred */
447 	if ((fepriv->auto_step == fepriv->started_auto_step) &&
448 	    (fepriv->auto_sub_step == 0) && check_wrapped) {
449 		return 1;
450 	}
451 
452 	dev_dbg(fe->dvb->device, "%s: drift:%i inversion:%i auto_step:%i " \
453 			"auto_sub_step:%i started_auto_step:%i\n",
454 			__func__, fepriv->lnb_drift, fepriv->inversion,
455 			fepriv->auto_step, fepriv->auto_sub_step,
456 			fepriv->started_auto_step);
457 
458 	/* set the frontend itself */
459 	c->frequency += fepriv->lnb_drift;
460 	if (autoinversion)
461 		c->inversion = fepriv->inversion;
462 	tmp = *c;
463 	if (fe->ops.set_frontend)
464 		fe_set_err = fe->ops.set_frontend(fe);
465 	*c = tmp;
466 	if (fe_set_err < 0) {
467 		fepriv->state = FESTATE_ERROR;
468 		return fe_set_err;
469 	}
470 
471 	c->frequency = original_frequency;
472 	c->inversion = original_inversion;
473 
474 	fepriv->auto_sub_step++;
475 	return 0;
476 }
477 
478 static void dvb_frontend_swzigzag(struct dvb_frontend *fe)
479 {
480 	enum fe_status s = FE_NONE;
481 	int retval = 0;
482 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
483 	struct dtv_frontend_properties *c = &fe->dtv_property_cache, tmp;
484 
485 	/* if we've got no parameters, just keep idling */
486 	if (fepriv->state & FESTATE_IDLE) {
487 		fepriv->delay = 3*HZ;
488 		fepriv->quality = 0;
489 		return;
490 	}
491 
492 	/* in SCAN mode, we just set the frontend when asked and leave it alone */
493 	if (fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT) {
494 		if (fepriv->state & FESTATE_RETUNE) {
495 			tmp = *c;
496 			if (fe->ops.set_frontend)
497 				retval = fe->ops.set_frontend(fe);
498 			*c = tmp;
499 			if (retval < 0)
500 				fepriv->state = FESTATE_ERROR;
501 			else
502 				fepriv->state = FESTATE_TUNED;
503 		}
504 		fepriv->delay = 3*HZ;
505 		fepriv->quality = 0;
506 		return;
507 	}
508 
509 	/* get the frontend status */
510 	if (fepriv->state & FESTATE_RETUNE) {
511 		s = 0;
512 	} else {
513 		if (fe->ops.read_status)
514 			fe->ops.read_status(fe, &s);
515 		if (s != fepriv->status) {
516 			dvb_frontend_add_event(fe, s);
517 			fepriv->status = s;
518 		}
519 	}
520 
521 	/* if we're not tuned, and we have a lock, move to the TUNED state */
522 	if ((fepriv->state & FESTATE_WAITFORLOCK) && (s & FE_HAS_LOCK)) {
523 		dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
524 		fepriv->state = FESTATE_TUNED;
525 
526 		/* if we're tuned, then we have determined the correct inversion */
527 		if ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) &&
528 		    (c->inversion == INVERSION_AUTO)) {
529 			c->inversion = fepriv->inversion;
530 		}
531 		return;
532 	}
533 
534 	/* if we are tuned already, check we're still locked */
535 	if (fepriv->state & FESTATE_TUNED) {
536 		dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
537 
538 		/* we're tuned, and the lock is still good... */
539 		if (s & FE_HAS_LOCK) {
540 			return;
541 		} else { /* if we _WERE_ tuned, but now don't have a lock */
542 			fepriv->state = FESTATE_ZIGZAG_FAST;
543 			fepriv->started_auto_step = fepriv->auto_step;
544 			fepriv->check_wrapped = 0;
545 		}
546 	}
547 
548 	/* don't actually do anything if we're in the LOSTLOCK state,
549 	 * the frontend is set to FE_CAN_RECOVER, and the max_drift is 0 */
550 	if ((fepriv->state & FESTATE_LOSTLOCK) &&
551 	    (fe->ops.info.caps & FE_CAN_RECOVER) && (fepriv->max_drift == 0)) {
552 		dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
553 		return;
554 	}
555 
556 	/* don't do anything if we're in the DISEQC state, since this
557 	 * might be someone with a motorized dish controlled by DISEQC.
558 	 * If its actually a re-tune, there will be a SET_FRONTEND soon enough.	*/
559 	if (fepriv->state & FESTATE_DISEQC) {
560 		dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
561 		return;
562 	}
563 
564 	/* if we're in the RETUNE state, set everything up for a brand
565 	 * new scan, keeping the current inversion setting, as the next
566 	 * tune is _very_ likely to require the same */
567 	if (fepriv->state & FESTATE_RETUNE) {
568 		fepriv->lnb_drift = 0;
569 		fepriv->auto_step = 0;
570 		fepriv->auto_sub_step = 0;
571 		fepriv->started_auto_step = 0;
572 		fepriv->check_wrapped = 0;
573 	}
574 
575 	/* fast zigzag. */
576 	if ((fepriv->state & FESTATE_SEARCHING_FAST) || (fepriv->state & FESTATE_RETUNE)) {
577 		fepriv->delay = fepriv->min_delay;
578 
579 		/* perform a tune */
580 		retval = dvb_frontend_swzigzag_autotune(fe,
581 							fepriv->check_wrapped);
582 		if (retval < 0) {
583 			return;
584 		} else if (retval) {
585 			/* OK, if we've run out of trials at the fast speed.
586 			 * Drop back to slow for the _next_ attempt */
587 			fepriv->state = FESTATE_SEARCHING_SLOW;
588 			fepriv->started_auto_step = fepriv->auto_step;
589 			return;
590 		}
591 		fepriv->check_wrapped = 1;
592 
593 		/* if we've just retuned, enter the ZIGZAG_FAST state.
594 		 * This ensures we cannot return from an
595 		 * FE_SET_FRONTEND ioctl before the first frontend tune
596 		 * occurs */
597 		if (fepriv->state & FESTATE_RETUNE) {
598 			fepriv->state = FESTATE_TUNING_FAST;
599 		}
600 	}
601 
602 	/* slow zigzag */
603 	if (fepriv->state & FESTATE_SEARCHING_SLOW) {
604 		dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
605 
606 		/* Note: don't bother checking for wrapping; we stay in this
607 		 * state until we get a lock */
608 		dvb_frontend_swzigzag_autotune(fe, 0);
609 	}
610 }
611 
612 static int dvb_frontend_is_exiting(struct dvb_frontend *fe)
613 {
614 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
615 
616 	if (fe->exit != DVB_FE_NO_EXIT)
617 		return 1;
618 
619 	if (fepriv->dvbdev->writers == 1)
620 		if (time_after_eq(jiffies, fepriv->release_jiffies +
621 				  dvb_shutdown_timeout * HZ))
622 			return 1;
623 
624 	return 0;
625 }
626 
627 static int dvb_frontend_should_wakeup(struct dvb_frontend *fe)
628 {
629 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
630 
631 	if (fepriv->wakeup) {
632 		fepriv->wakeup = 0;
633 		return 1;
634 	}
635 	return dvb_frontend_is_exiting(fe);
636 }
637 
638 static void dvb_frontend_wakeup(struct dvb_frontend *fe)
639 {
640 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
641 
642 	fepriv->wakeup = 1;
643 	wake_up_interruptible(&fepriv->wait_queue);
644 }
645 
646 static int dvb_frontend_thread(void *data)
647 {
648 	struct dvb_frontend *fe = data;
649 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
650 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
651 	enum fe_status s = FE_NONE;
652 	enum dvbfe_algo algo;
653 	bool re_tune = false;
654 	bool semheld = false;
655 
656 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
657 
658 	fepriv->check_wrapped = 0;
659 	fepriv->quality = 0;
660 	fepriv->delay = 3*HZ;
661 	fepriv->status = 0;
662 	fepriv->wakeup = 0;
663 	fepriv->reinitialise = 0;
664 
665 	dvb_frontend_init(fe);
666 
667 	set_freezable();
668 	while (1) {
669 		up(&fepriv->sem);	    /* is locked when we enter the thread... */
670 restart:
671 		wait_event_interruptible_timeout(fepriv->wait_queue,
672 			dvb_frontend_should_wakeup(fe) || kthread_should_stop()
673 				|| freezing(current),
674 			fepriv->delay);
675 
676 		if (kthread_should_stop() || dvb_frontend_is_exiting(fe)) {
677 			/* got signal or quitting */
678 			if (!down_interruptible(&fepriv->sem))
679 				semheld = true;
680 			fe->exit = DVB_FE_NORMAL_EXIT;
681 			break;
682 		}
683 
684 		if (try_to_freeze())
685 			goto restart;
686 
687 		if (down_interruptible(&fepriv->sem))
688 			break;
689 
690 		if (fepriv->reinitialise) {
691 			dvb_frontend_init(fe);
692 			if (fe->ops.set_tone && fepriv->tone != -1)
693 				fe->ops.set_tone(fe, fepriv->tone);
694 			if (fe->ops.set_voltage && fepriv->voltage != -1)
695 				fe->ops.set_voltage(fe, fepriv->voltage);
696 			fepriv->reinitialise = 0;
697 		}
698 
699 		/* do an iteration of the tuning loop */
700 		if (fe->ops.get_frontend_algo) {
701 			algo = fe->ops.get_frontend_algo(fe);
702 			switch (algo) {
703 			case DVBFE_ALGO_HW:
704 				dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_HW\n", __func__);
705 
706 				if (fepriv->state & FESTATE_RETUNE) {
707 					dev_dbg(fe->dvb->device, "%s: Retune requested, FESTATE_RETUNE\n", __func__);
708 					re_tune = true;
709 					fepriv->state = FESTATE_TUNED;
710 				} else {
711 					re_tune = false;
712 				}
713 
714 				if (fe->ops.tune)
715 					fe->ops.tune(fe, re_tune, fepriv->tune_mode_flags, &fepriv->delay, &s);
716 
717 				if (s != fepriv->status && !(fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT)) {
718 					dev_dbg(fe->dvb->device, "%s: state changed, adding current state\n", __func__);
719 					dvb_frontend_add_event(fe, s);
720 					fepriv->status = s;
721 				}
722 				break;
723 			case DVBFE_ALGO_SW:
724 				dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_SW\n", __func__);
725 				dvb_frontend_swzigzag(fe);
726 				break;
727 			case DVBFE_ALGO_CUSTOM:
728 				dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_CUSTOM, state=%d\n", __func__, fepriv->state);
729 				if (fepriv->state & FESTATE_RETUNE) {
730 					dev_dbg(fe->dvb->device, "%s: Retune requested, FESTAT_RETUNE\n", __func__);
731 					fepriv->state = FESTATE_TUNED;
732 				}
733 				/* Case where we are going to search for a carrier
734 				 * User asked us to retune again for some reason, possibly
735 				 * requesting a search with a new set of parameters
736 				 */
737 				if (fepriv->algo_status & DVBFE_ALGO_SEARCH_AGAIN) {
738 					if (fe->ops.search) {
739 						fepriv->algo_status = fe->ops.search(fe);
740 						/* We did do a search as was requested, the flags are
741 						 * now unset as well and has the flags wrt to search.
742 						 */
743 					} else {
744 						fepriv->algo_status &= ~DVBFE_ALGO_SEARCH_AGAIN;
745 					}
746 				}
747 				/* Track the carrier if the search was successful */
748 				if (fepriv->algo_status != DVBFE_ALGO_SEARCH_SUCCESS) {
749 					fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN;
750 					fepriv->delay = HZ / 2;
751 				}
752 				dtv_property_legacy_params_sync(fe, c, &fepriv->parameters_out);
753 				fe->ops.read_status(fe, &s);
754 				if (s != fepriv->status) {
755 					dvb_frontend_add_event(fe, s); /* update event list */
756 					fepriv->status = s;
757 					if (!(s & FE_HAS_LOCK)) {
758 						fepriv->delay = HZ / 10;
759 						fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN;
760 					} else {
761 						fepriv->delay = 60 * HZ;
762 					}
763 				}
764 				break;
765 			default:
766 				dev_dbg(fe->dvb->device, "%s: UNDEFINED ALGO !\n", __func__);
767 				break;
768 			}
769 		} else {
770 			dvb_frontend_swzigzag(fe);
771 		}
772 	}
773 
774 	if (dvb_powerdown_on_sleep) {
775 		if (fe->ops.set_voltage)
776 			fe->ops.set_voltage(fe, SEC_VOLTAGE_OFF);
777 		if (fe->ops.tuner_ops.sleep) {
778 			if (fe->ops.i2c_gate_ctrl)
779 				fe->ops.i2c_gate_ctrl(fe, 1);
780 			fe->ops.tuner_ops.sleep(fe);
781 			if (fe->ops.i2c_gate_ctrl)
782 				fe->ops.i2c_gate_ctrl(fe, 0);
783 		}
784 		if (fe->ops.sleep)
785 			fe->ops.sleep(fe);
786 	}
787 
788 	fepriv->thread = NULL;
789 	if (kthread_should_stop())
790 		fe->exit = DVB_FE_DEVICE_REMOVED;
791 	else
792 		fe->exit = DVB_FE_NO_EXIT;
793 	mb();
794 
795 	if (semheld)
796 		up(&fepriv->sem);
797 	dvb_frontend_wakeup(fe);
798 	return 0;
799 }
800 
801 static void dvb_frontend_stop(struct dvb_frontend *fe)
802 {
803 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
804 
805 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
806 
807 	if (fe->exit != DVB_FE_DEVICE_REMOVED)
808 		fe->exit = DVB_FE_NORMAL_EXIT;
809 	mb();
810 
811 	if (!fepriv->thread)
812 		return;
813 
814 	kthread_stop(fepriv->thread);
815 
816 	sema_init(&fepriv->sem, 1);
817 	fepriv->state = FESTATE_IDLE;
818 
819 	/* paranoia check in case a signal arrived */
820 	if (fepriv->thread)
821 		dev_warn(fe->dvb->device,
822 				"dvb_frontend_stop: warning: thread %p won't exit\n",
823 				fepriv->thread);
824 }
825 
826 /*
827  * Sleep for the amount of time given by add_usec parameter
828  *
829  * This needs to be as precise as possible, as it affects the detection of
830  * the dish tone command at the satellite subsystem. The precision is improved
831  * by using a scheduled msleep followed by udelay for the remainder.
832  */
833 void dvb_frontend_sleep_until(ktime_t *waketime, u32 add_usec)
834 {
835 	s32 delta;
836 
837 	*waketime = ktime_add_us(*waketime, add_usec);
838 	delta = ktime_us_delta(ktime_get_boottime(), *waketime);
839 	if (delta > 2500) {
840 		msleep((delta - 1500) / 1000);
841 		delta = ktime_us_delta(ktime_get_boottime(), *waketime);
842 	}
843 	if (delta > 0)
844 		udelay(delta);
845 }
846 EXPORT_SYMBOL(dvb_frontend_sleep_until);
847 
848 static int dvb_frontend_start(struct dvb_frontend *fe)
849 {
850 	int ret;
851 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
852 	struct task_struct *fe_thread;
853 
854 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
855 
856 	if (fepriv->thread) {
857 		if (fe->exit == DVB_FE_NO_EXIT)
858 			return 0;
859 		else
860 			dvb_frontend_stop (fe);
861 	}
862 
863 	if (signal_pending(current))
864 		return -EINTR;
865 	if (down_interruptible (&fepriv->sem))
866 		return -EINTR;
867 
868 	fepriv->state = FESTATE_IDLE;
869 	fe->exit = DVB_FE_NO_EXIT;
870 	fepriv->thread = NULL;
871 	mb();
872 
873 	fe_thread = kthread_run(dvb_frontend_thread, fe,
874 		"kdvb-ad-%i-fe-%i", fe->dvb->num,fe->id);
875 	if (IS_ERR(fe_thread)) {
876 		ret = PTR_ERR(fe_thread);
877 		dev_warn(fe->dvb->device,
878 				"dvb_frontend_start: failed to start kthread (%d)\n",
879 				ret);
880 		up(&fepriv->sem);
881 		return ret;
882 	}
883 	fepriv->thread = fe_thread;
884 	return 0;
885 }
886 
887 static void dvb_frontend_get_frequency_limits(struct dvb_frontend *fe,
888 					u32 *freq_min, u32 *freq_max)
889 {
890 	*freq_min = max(fe->ops.info.frequency_min, fe->ops.tuner_ops.info.frequency_min);
891 
892 	if (fe->ops.info.frequency_max == 0)
893 		*freq_max = fe->ops.tuner_ops.info.frequency_max;
894 	else if (fe->ops.tuner_ops.info.frequency_max == 0)
895 		*freq_max = fe->ops.info.frequency_max;
896 	else
897 		*freq_max = min(fe->ops.info.frequency_max, fe->ops.tuner_ops.info.frequency_max);
898 
899 	if (*freq_min == 0 || *freq_max == 0)
900 		dev_warn(fe->dvb->device, "DVB: adapter %i frontend %u frequency limits undefined - fix the driver\n",
901 				fe->dvb->num, fe->id);
902 }
903 
904 static int dvb_frontend_check_parameters(struct dvb_frontend *fe)
905 {
906 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
907 	u32 freq_min;
908 	u32 freq_max;
909 
910 	/* range check: frequency */
911 	dvb_frontend_get_frequency_limits(fe, &freq_min, &freq_max);
912 	if ((freq_min && c->frequency < freq_min) ||
913 	    (freq_max && c->frequency > freq_max)) {
914 		dev_warn(fe->dvb->device, "DVB: adapter %i frontend %i frequency %u out of range (%u..%u)\n",
915 				fe->dvb->num, fe->id, c->frequency,
916 				freq_min, freq_max);
917 		return -EINVAL;
918 	}
919 
920 	/* range check: symbol rate */
921 	switch (c->delivery_system) {
922 	case SYS_DVBS:
923 	case SYS_DVBS2:
924 	case SYS_TURBO:
925 	case SYS_DVBC_ANNEX_A:
926 	case SYS_DVBC_ANNEX_C:
927 		if ((fe->ops.info.symbol_rate_min &&
928 		     c->symbol_rate < fe->ops.info.symbol_rate_min) ||
929 		    (fe->ops.info.symbol_rate_max &&
930 		     c->symbol_rate > fe->ops.info.symbol_rate_max)) {
931 			dev_warn(fe->dvb->device, "DVB: adapter %i frontend %i symbol rate %u out of range (%u..%u)\n",
932 					fe->dvb->num, fe->id, c->symbol_rate,
933 					fe->ops.info.symbol_rate_min,
934 					fe->ops.info.symbol_rate_max);
935 			return -EINVAL;
936 		}
937 	default:
938 		break;
939 	}
940 
941 	return 0;
942 }
943 
944 static int dvb_frontend_clear_cache(struct dvb_frontend *fe)
945 {
946 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
947 	int i;
948 	u32 delsys;
949 
950 	delsys = c->delivery_system;
951 	memset(c, 0, offsetof(struct dtv_frontend_properties, strength));
952 	c->delivery_system = delsys;
953 
954 	c->state = DTV_CLEAR;
955 
956 	dev_dbg(fe->dvb->device, "%s: Clearing cache for delivery system %d\n",
957 			__func__, c->delivery_system);
958 
959 	c->transmission_mode = TRANSMISSION_MODE_AUTO;
960 	c->bandwidth_hz = 0;	/* AUTO */
961 	c->guard_interval = GUARD_INTERVAL_AUTO;
962 	c->hierarchy = HIERARCHY_AUTO;
963 	c->symbol_rate = 0;
964 	c->code_rate_HP = FEC_AUTO;
965 	c->code_rate_LP = FEC_AUTO;
966 	c->fec_inner = FEC_AUTO;
967 	c->rolloff = ROLLOFF_AUTO;
968 	c->voltage = SEC_VOLTAGE_OFF;
969 	c->sectone = SEC_TONE_OFF;
970 	c->pilot = PILOT_AUTO;
971 
972 	c->isdbt_partial_reception = 0;
973 	c->isdbt_sb_mode = 0;
974 	c->isdbt_sb_subchannel = 0;
975 	c->isdbt_sb_segment_idx = 0;
976 	c->isdbt_sb_segment_count = 0;
977 	c->isdbt_layer_enabled = 0;
978 	for (i = 0; i < 3; i++) {
979 		c->layer[i].fec = FEC_AUTO;
980 		c->layer[i].modulation = QAM_AUTO;
981 		c->layer[i].interleaving = 0;
982 		c->layer[i].segment_count = 0;
983 	}
984 
985 	c->stream_id = NO_STREAM_ID_FILTER;
986 
987 	switch (c->delivery_system) {
988 	case SYS_DVBS:
989 	case SYS_DVBS2:
990 	case SYS_TURBO:
991 		c->modulation = QPSK;   /* implied for DVB-S in legacy API */
992 		c->rolloff = ROLLOFF_35;/* implied for DVB-S */
993 		break;
994 	case SYS_ATSC:
995 		c->modulation = VSB_8;
996 		break;
997 	case SYS_ISDBS:
998 		c->symbol_rate = 28860000;
999 		c->rolloff = ROLLOFF_35;
1000 		c->bandwidth_hz = c->symbol_rate / 100 * 135;
1001 		break;
1002 	default:
1003 		c->modulation = QAM_AUTO;
1004 		break;
1005 	}
1006 
1007 	c->lna = LNA_AUTO;
1008 
1009 	return 0;
1010 }
1011 
1012 #define _DTV_CMD(n, s, b) \
1013 [n] = { \
1014 	.name = #n, \
1015 	.cmd  = n, \
1016 	.set  = s,\
1017 	.buffer = b \
1018 }
1019 
1020 struct dtv_cmds_h {
1021 	char	*name;		/* A display name for debugging purposes */
1022 
1023 	__u32	cmd;		/* A unique ID */
1024 
1025 	/* Flags */
1026 	__u32	set:1;		/* Either a set or get property */
1027 	__u32	buffer:1;	/* Does this property use the buffer? */
1028 	__u32	reserved:30;	/* Align */
1029 };
1030 
1031 static struct dtv_cmds_h dtv_cmds[DTV_MAX_COMMAND + 1] = {
1032 	_DTV_CMD(DTV_TUNE, 1, 0),
1033 	_DTV_CMD(DTV_CLEAR, 1, 0),
1034 
1035 	/* Set */
1036 	_DTV_CMD(DTV_FREQUENCY, 1, 0),
1037 	_DTV_CMD(DTV_BANDWIDTH_HZ, 1, 0),
1038 	_DTV_CMD(DTV_MODULATION, 1, 0),
1039 	_DTV_CMD(DTV_INVERSION, 1, 0),
1040 	_DTV_CMD(DTV_DISEQC_MASTER, 1, 1),
1041 	_DTV_CMD(DTV_SYMBOL_RATE, 1, 0),
1042 	_DTV_CMD(DTV_INNER_FEC, 1, 0),
1043 	_DTV_CMD(DTV_VOLTAGE, 1, 0),
1044 	_DTV_CMD(DTV_TONE, 1, 0),
1045 	_DTV_CMD(DTV_PILOT, 1, 0),
1046 	_DTV_CMD(DTV_ROLLOFF, 1, 0),
1047 	_DTV_CMD(DTV_DELIVERY_SYSTEM, 1, 0),
1048 	_DTV_CMD(DTV_HIERARCHY, 1, 0),
1049 	_DTV_CMD(DTV_CODE_RATE_HP, 1, 0),
1050 	_DTV_CMD(DTV_CODE_RATE_LP, 1, 0),
1051 	_DTV_CMD(DTV_GUARD_INTERVAL, 1, 0),
1052 	_DTV_CMD(DTV_TRANSMISSION_MODE, 1, 0),
1053 	_DTV_CMD(DTV_INTERLEAVING, 1, 0),
1054 
1055 	_DTV_CMD(DTV_ISDBT_PARTIAL_RECEPTION, 1, 0),
1056 	_DTV_CMD(DTV_ISDBT_SOUND_BROADCASTING, 1, 0),
1057 	_DTV_CMD(DTV_ISDBT_SB_SUBCHANNEL_ID, 1, 0),
1058 	_DTV_CMD(DTV_ISDBT_SB_SEGMENT_IDX, 1, 0),
1059 	_DTV_CMD(DTV_ISDBT_SB_SEGMENT_COUNT, 1, 0),
1060 	_DTV_CMD(DTV_ISDBT_LAYER_ENABLED, 1, 0),
1061 	_DTV_CMD(DTV_ISDBT_LAYERA_FEC, 1, 0),
1062 	_DTV_CMD(DTV_ISDBT_LAYERA_MODULATION, 1, 0),
1063 	_DTV_CMD(DTV_ISDBT_LAYERA_SEGMENT_COUNT, 1, 0),
1064 	_DTV_CMD(DTV_ISDBT_LAYERA_TIME_INTERLEAVING, 1, 0),
1065 	_DTV_CMD(DTV_ISDBT_LAYERB_FEC, 1, 0),
1066 	_DTV_CMD(DTV_ISDBT_LAYERB_MODULATION, 1, 0),
1067 	_DTV_CMD(DTV_ISDBT_LAYERB_SEGMENT_COUNT, 1, 0),
1068 	_DTV_CMD(DTV_ISDBT_LAYERB_TIME_INTERLEAVING, 1, 0),
1069 	_DTV_CMD(DTV_ISDBT_LAYERC_FEC, 1, 0),
1070 	_DTV_CMD(DTV_ISDBT_LAYERC_MODULATION, 1, 0),
1071 	_DTV_CMD(DTV_ISDBT_LAYERC_SEGMENT_COUNT, 1, 0),
1072 	_DTV_CMD(DTV_ISDBT_LAYERC_TIME_INTERLEAVING, 1, 0),
1073 
1074 	_DTV_CMD(DTV_STREAM_ID, 1, 0),
1075 	_DTV_CMD(DTV_DVBT2_PLP_ID_LEGACY, 1, 0),
1076 	_DTV_CMD(DTV_LNA, 1, 0),
1077 
1078 	/* Get */
1079 	_DTV_CMD(DTV_DISEQC_SLAVE_REPLY, 0, 1),
1080 	_DTV_CMD(DTV_API_VERSION, 0, 0),
1081 
1082 	_DTV_CMD(DTV_ENUM_DELSYS, 0, 0),
1083 
1084 	_DTV_CMD(DTV_ATSCMH_PARADE_ID, 1, 0),
1085 	_DTV_CMD(DTV_ATSCMH_RS_FRAME_ENSEMBLE, 1, 0),
1086 
1087 	_DTV_CMD(DTV_ATSCMH_FIC_VER, 0, 0),
1088 	_DTV_CMD(DTV_ATSCMH_NOG, 0, 0),
1089 	_DTV_CMD(DTV_ATSCMH_TNOG, 0, 0),
1090 	_DTV_CMD(DTV_ATSCMH_SGN, 0, 0),
1091 	_DTV_CMD(DTV_ATSCMH_PRC, 0, 0),
1092 	_DTV_CMD(DTV_ATSCMH_RS_FRAME_MODE, 0, 0),
1093 	_DTV_CMD(DTV_ATSCMH_RS_CODE_MODE_PRI, 0, 0),
1094 	_DTV_CMD(DTV_ATSCMH_RS_CODE_MODE_SEC, 0, 0),
1095 	_DTV_CMD(DTV_ATSCMH_SCCC_BLOCK_MODE, 0, 0),
1096 	_DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_A, 0, 0),
1097 	_DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_B, 0, 0),
1098 	_DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_C, 0, 0),
1099 	_DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_D, 0, 0),
1100 
1101 	/* Statistics API */
1102 	_DTV_CMD(DTV_STAT_SIGNAL_STRENGTH, 0, 0),
1103 	_DTV_CMD(DTV_STAT_CNR, 0, 0),
1104 	_DTV_CMD(DTV_STAT_PRE_ERROR_BIT_COUNT, 0, 0),
1105 	_DTV_CMD(DTV_STAT_PRE_TOTAL_BIT_COUNT, 0, 0),
1106 	_DTV_CMD(DTV_STAT_POST_ERROR_BIT_COUNT, 0, 0),
1107 	_DTV_CMD(DTV_STAT_POST_TOTAL_BIT_COUNT, 0, 0),
1108 	_DTV_CMD(DTV_STAT_ERROR_BLOCK_COUNT, 0, 0),
1109 	_DTV_CMD(DTV_STAT_TOTAL_BLOCK_COUNT, 0, 0),
1110 };
1111 
1112 static void dtv_property_dump(struct dvb_frontend *fe,
1113 			      bool is_set,
1114 			      struct dtv_property *tvp)
1115 {
1116 	int i;
1117 
1118 	if (tvp->cmd <= 0 || tvp->cmd > DTV_MAX_COMMAND) {
1119 		dev_warn(fe->dvb->device, "%s: %s tvp.cmd = 0x%08x undefined\n",
1120 				__func__,
1121 				is_set ? "SET" : "GET",
1122 				tvp->cmd);
1123 		return;
1124 	}
1125 
1126 	dev_dbg(fe->dvb->device, "%s: %s tvp.cmd    = 0x%08x (%s)\n", __func__,
1127 		is_set ? "SET" : "GET",
1128 		tvp->cmd,
1129 		dtv_cmds[tvp->cmd].name);
1130 
1131 	if (dtv_cmds[tvp->cmd].buffer) {
1132 		dev_dbg(fe->dvb->device, "%s: tvp.u.buffer.len = 0x%02x\n",
1133 			__func__, tvp->u.buffer.len);
1134 
1135 		for(i = 0; i < tvp->u.buffer.len; i++)
1136 			dev_dbg(fe->dvb->device,
1137 					"%s: tvp.u.buffer.data[0x%02x] = 0x%02x\n",
1138 					__func__, i, tvp->u.buffer.data[i]);
1139 	} else {
1140 		dev_dbg(fe->dvb->device, "%s: tvp.u.data = 0x%08x\n", __func__,
1141 				tvp->u.data);
1142 	}
1143 }
1144 
1145 /* Synchronise the legacy tuning parameters into the cache, so that demodulator
1146  * drivers can use a single set_frontend tuning function, regardless of whether
1147  * it's being used for the legacy or new API, reducing code and complexity.
1148  */
1149 static int dtv_property_cache_sync(struct dvb_frontend *fe,
1150 				   struct dtv_frontend_properties *c,
1151 				   const struct dvb_frontend_parameters *p)
1152 {
1153 	c->frequency = p->frequency;
1154 	c->inversion = p->inversion;
1155 
1156 	switch (dvbv3_type(c->delivery_system)) {
1157 	case DVBV3_QPSK:
1158 		dev_dbg(fe->dvb->device, "%s: Preparing QPSK req\n", __func__);
1159 		c->symbol_rate = p->u.qpsk.symbol_rate;
1160 		c->fec_inner = p->u.qpsk.fec_inner;
1161 		break;
1162 	case DVBV3_QAM:
1163 		dev_dbg(fe->dvb->device, "%s: Preparing QAM req\n", __func__);
1164 		c->symbol_rate = p->u.qam.symbol_rate;
1165 		c->fec_inner = p->u.qam.fec_inner;
1166 		c->modulation = p->u.qam.modulation;
1167 		break;
1168 	case DVBV3_OFDM:
1169 		dev_dbg(fe->dvb->device, "%s: Preparing OFDM req\n", __func__);
1170 
1171 		switch (p->u.ofdm.bandwidth) {
1172 		case BANDWIDTH_10_MHZ:
1173 			c->bandwidth_hz = 10000000;
1174 			break;
1175 		case BANDWIDTH_8_MHZ:
1176 			c->bandwidth_hz = 8000000;
1177 			break;
1178 		case BANDWIDTH_7_MHZ:
1179 			c->bandwidth_hz = 7000000;
1180 			break;
1181 		case BANDWIDTH_6_MHZ:
1182 			c->bandwidth_hz = 6000000;
1183 			break;
1184 		case BANDWIDTH_5_MHZ:
1185 			c->bandwidth_hz = 5000000;
1186 			break;
1187 		case BANDWIDTH_1_712_MHZ:
1188 			c->bandwidth_hz = 1712000;
1189 			break;
1190 		case BANDWIDTH_AUTO:
1191 			c->bandwidth_hz = 0;
1192 		}
1193 
1194 		c->code_rate_HP = p->u.ofdm.code_rate_HP;
1195 		c->code_rate_LP = p->u.ofdm.code_rate_LP;
1196 		c->modulation = p->u.ofdm.constellation;
1197 		c->transmission_mode = p->u.ofdm.transmission_mode;
1198 		c->guard_interval = p->u.ofdm.guard_interval;
1199 		c->hierarchy = p->u.ofdm.hierarchy_information;
1200 		break;
1201 	case DVBV3_ATSC:
1202 		dev_dbg(fe->dvb->device, "%s: Preparing ATSC req\n", __func__);
1203 		c->modulation = p->u.vsb.modulation;
1204 		if (c->delivery_system == SYS_ATSCMH)
1205 			break;
1206 		if ((c->modulation == VSB_8) || (c->modulation == VSB_16))
1207 			c->delivery_system = SYS_ATSC;
1208 		else
1209 			c->delivery_system = SYS_DVBC_ANNEX_B;
1210 		break;
1211 	case DVBV3_UNKNOWN:
1212 		dev_err(fe->dvb->device,
1213 				"%s: doesn't know how to handle a DVBv3 call to delivery system %i\n",
1214 				__func__, c->delivery_system);
1215 		return -EINVAL;
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 /* Ensure the cached values are set correctly in the frontend
1222  * legacy tuning structures, for the advanced tuning API.
1223  */
1224 static int
1225 dtv_property_legacy_params_sync(struct dvb_frontend *fe,
1226 				const struct dtv_frontend_properties *c,
1227 				struct dvb_frontend_parameters *p)
1228 {
1229 	p->frequency = c->frequency;
1230 	p->inversion = c->inversion;
1231 
1232 	switch (dvbv3_type(c->delivery_system)) {
1233 	case DVBV3_UNKNOWN:
1234 		dev_err(fe->dvb->device,
1235 				"%s: doesn't know how to handle a DVBv3 call to delivery system %i\n",
1236 				__func__, c->delivery_system);
1237 		return -EINVAL;
1238 	case DVBV3_QPSK:
1239 		dev_dbg(fe->dvb->device, "%s: Preparing QPSK req\n", __func__);
1240 		p->u.qpsk.symbol_rate = c->symbol_rate;
1241 		p->u.qpsk.fec_inner = c->fec_inner;
1242 		break;
1243 	case DVBV3_QAM:
1244 		dev_dbg(fe->dvb->device, "%s: Preparing QAM req\n", __func__);
1245 		p->u.qam.symbol_rate = c->symbol_rate;
1246 		p->u.qam.fec_inner = c->fec_inner;
1247 		p->u.qam.modulation = c->modulation;
1248 		break;
1249 	case DVBV3_OFDM:
1250 		dev_dbg(fe->dvb->device, "%s: Preparing OFDM req\n", __func__);
1251 		switch (c->bandwidth_hz) {
1252 		case 10000000:
1253 			p->u.ofdm.bandwidth = BANDWIDTH_10_MHZ;
1254 			break;
1255 		case 8000000:
1256 			p->u.ofdm.bandwidth = BANDWIDTH_8_MHZ;
1257 			break;
1258 		case 7000000:
1259 			p->u.ofdm.bandwidth = BANDWIDTH_7_MHZ;
1260 			break;
1261 		case 6000000:
1262 			p->u.ofdm.bandwidth = BANDWIDTH_6_MHZ;
1263 			break;
1264 		case 5000000:
1265 			p->u.ofdm.bandwidth = BANDWIDTH_5_MHZ;
1266 			break;
1267 		case 1712000:
1268 			p->u.ofdm.bandwidth = BANDWIDTH_1_712_MHZ;
1269 			break;
1270 		case 0:
1271 		default:
1272 			p->u.ofdm.bandwidth = BANDWIDTH_AUTO;
1273 		}
1274 		p->u.ofdm.code_rate_HP = c->code_rate_HP;
1275 		p->u.ofdm.code_rate_LP = c->code_rate_LP;
1276 		p->u.ofdm.constellation = c->modulation;
1277 		p->u.ofdm.transmission_mode = c->transmission_mode;
1278 		p->u.ofdm.guard_interval = c->guard_interval;
1279 		p->u.ofdm.hierarchy_information = c->hierarchy;
1280 		break;
1281 	case DVBV3_ATSC:
1282 		dev_dbg(fe->dvb->device, "%s: Preparing VSB req\n", __func__);
1283 		p->u.vsb.modulation = c->modulation;
1284 		break;
1285 	}
1286 	return 0;
1287 }
1288 
1289 /**
1290  * dtv_get_frontend - calls a callback for retrieving DTV parameters
1291  * @fe:		struct dvb_frontend pointer
1292  * @c:		struct dtv_frontend_properties pointer (DVBv5 cache)
1293  * @p_out	struct dvb_frontend_parameters pointer (DVBv3 FE struct)
1294  *
1295  * This routine calls either the DVBv3 or DVBv5 get_frontend call.
1296  * If c is not null, it will update the DVBv5 cache struct pointed by it.
1297  * If p_out is not null, it will update the DVBv3 params pointed by it.
1298  */
1299 static int dtv_get_frontend(struct dvb_frontend *fe,
1300 			    struct dtv_frontend_properties *c,
1301 			    struct dvb_frontend_parameters *p_out)
1302 {
1303 	int r;
1304 
1305 	if (fe->ops.get_frontend) {
1306 		r = fe->ops.get_frontend(fe, c);
1307 		if (unlikely(r < 0))
1308 			return r;
1309 		if (p_out)
1310 			dtv_property_legacy_params_sync(fe, c, p_out);
1311 		return 0;
1312 	}
1313 
1314 	/* As everything is in cache, get_frontend fops are always supported */
1315 	return 0;
1316 }
1317 
1318 static int dvb_frontend_ioctl_legacy(struct file *file,
1319 			unsigned int cmd, void *parg);
1320 static int dvb_frontend_ioctl_properties(struct file *file,
1321 			unsigned int cmd, void *parg);
1322 
1323 static int dtv_property_process_get(struct dvb_frontend *fe,
1324 				    const struct dtv_frontend_properties *c,
1325 				    struct dtv_property *tvp,
1326 				    struct file *file)
1327 {
1328 	int r, ncaps;
1329 
1330 	switch(tvp->cmd) {
1331 	case DTV_ENUM_DELSYS:
1332 		ncaps = 0;
1333 		while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) {
1334 			tvp->u.buffer.data[ncaps] = fe->ops.delsys[ncaps];
1335 			ncaps++;
1336 		}
1337 		tvp->u.buffer.len = ncaps;
1338 		break;
1339 	case DTV_FREQUENCY:
1340 		tvp->u.data = c->frequency;
1341 		break;
1342 	case DTV_MODULATION:
1343 		tvp->u.data = c->modulation;
1344 		break;
1345 	case DTV_BANDWIDTH_HZ:
1346 		tvp->u.data = c->bandwidth_hz;
1347 		break;
1348 	case DTV_INVERSION:
1349 		tvp->u.data = c->inversion;
1350 		break;
1351 	case DTV_SYMBOL_RATE:
1352 		tvp->u.data = c->symbol_rate;
1353 		break;
1354 	case DTV_INNER_FEC:
1355 		tvp->u.data = c->fec_inner;
1356 		break;
1357 	case DTV_PILOT:
1358 		tvp->u.data = c->pilot;
1359 		break;
1360 	case DTV_ROLLOFF:
1361 		tvp->u.data = c->rolloff;
1362 		break;
1363 	case DTV_DELIVERY_SYSTEM:
1364 		tvp->u.data = c->delivery_system;
1365 		break;
1366 	case DTV_VOLTAGE:
1367 		tvp->u.data = c->voltage;
1368 		break;
1369 	case DTV_TONE:
1370 		tvp->u.data = c->sectone;
1371 		break;
1372 	case DTV_API_VERSION:
1373 		tvp->u.data = (DVB_API_VERSION << 8) | DVB_API_VERSION_MINOR;
1374 		break;
1375 	case DTV_CODE_RATE_HP:
1376 		tvp->u.data = c->code_rate_HP;
1377 		break;
1378 	case DTV_CODE_RATE_LP:
1379 		tvp->u.data = c->code_rate_LP;
1380 		break;
1381 	case DTV_GUARD_INTERVAL:
1382 		tvp->u.data = c->guard_interval;
1383 		break;
1384 	case DTV_TRANSMISSION_MODE:
1385 		tvp->u.data = c->transmission_mode;
1386 		break;
1387 	case DTV_HIERARCHY:
1388 		tvp->u.data = c->hierarchy;
1389 		break;
1390 	case DTV_INTERLEAVING:
1391 		tvp->u.data = c->interleaving;
1392 		break;
1393 
1394 	/* ISDB-T Support here */
1395 	case DTV_ISDBT_PARTIAL_RECEPTION:
1396 		tvp->u.data = c->isdbt_partial_reception;
1397 		break;
1398 	case DTV_ISDBT_SOUND_BROADCASTING:
1399 		tvp->u.data = c->isdbt_sb_mode;
1400 		break;
1401 	case DTV_ISDBT_SB_SUBCHANNEL_ID:
1402 		tvp->u.data = c->isdbt_sb_subchannel;
1403 		break;
1404 	case DTV_ISDBT_SB_SEGMENT_IDX:
1405 		tvp->u.data = c->isdbt_sb_segment_idx;
1406 		break;
1407 	case DTV_ISDBT_SB_SEGMENT_COUNT:
1408 		tvp->u.data = c->isdbt_sb_segment_count;
1409 		break;
1410 	case DTV_ISDBT_LAYER_ENABLED:
1411 		tvp->u.data = c->isdbt_layer_enabled;
1412 		break;
1413 	case DTV_ISDBT_LAYERA_FEC:
1414 		tvp->u.data = c->layer[0].fec;
1415 		break;
1416 	case DTV_ISDBT_LAYERA_MODULATION:
1417 		tvp->u.data = c->layer[0].modulation;
1418 		break;
1419 	case DTV_ISDBT_LAYERA_SEGMENT_COUNT:
1420 		tvp->u.data = c->layer[0].segment_count;
1421 		break;
1422 	case DTV_ISDBT_LAYERA_TIME_INTERLEAVING:
1423 		tvp->u.data = c->layer[0].interleaving;
1424 		break;
1425 	case DTV_ISDBT_LAYERB_FEC:
1426 		tvp->u.data = c->layer[1].fec;
1427 		break;
1428 	case DTV_ISDBT_LAYERB_MODULATION:
1429 		tvp->u.data = c->layer[1].modulation;
1430 		break;
1431 	case DTV_ISDBT_LAYERB_SEGMENT_COUNT:
1432 		tvp->u.data = c->layer[1].segment_count;
1433 		break;
1434 	case DTV_ISDBT_LAYERB_TIME_INTERLEAVING:
1435 		tvp->u.data = c->layer[1].interleaving;
1436 		break;
1437 	case DTV_ISDBT_LAYERC_FEC:
1438 		tvp->u.data = c->layer[2].fec;
1439 		break;
1440 	case DTV_ISDBT_LAYERC_MODULATION:
1441 		tvp->u.data = c->layer[2].modulation;
1442 		break;
1443 	case DTV_ISDBT_LAYERC_SEGMENT_COUNT:
1444 		tvp->u.data = c->layer[2].segment_count;
1445 		break;
1446 	case DTV_ISDBT_LAYERC_TIME_INTERLEAVING:
1447 		tvp->u.data = c->layer[2].interleaving;
1448 		break;
1449 
1450 	/* Multistream support */
1451 	case DTV_STREAM_ID:
1452 	case DTV_DVBT2_PLP_ID_LEGACY:
1453 		tvp->u.data = c->stream_id;
1454 		break;
1455 
1456 	/* ATSC-MH */
1457 	case DTV_ATSCMH_FIC_VER:
1458 		tvp->u.data = fe->dtv_property_cache.atscmh_fic_ver;
1459 		break;
1460 	case DTV_ATSCMH_PARADE_ID:
1461 		tvp->u.data = fe->dtv_property_cache.atscmh_parade_id;
1462 		break;
1463 	case DTV_ATSCMH_NOG:
1464 		tvp->u.data = fe->dtv_property_cache.atscmh_nog;
1465 		break;
1466 	case DTV_ATSCMH_TNOG:
1467 		tvp->u.data = fe->dtv_property_cache.atscmh_tnog;
1468 		break;
1469 	case DTV_ATSCMH_SGN:
1470 		tvp->u.data = fe->dtv_property_cache.atscmh_sgn;
1471 		break;
1472 	case DTV_ATSCMH_PRC:
1473 		tvp->u.data = fe->dtv_property_cache.atscmh_prc;
1474 		break;
1475 	case DTV_ATSCMH_RS_FRAME_MODE:
1476 		tvp->u.data = fe->dtv_property_cache.atscmh_rs_frame_mode;
1477 		break;
1478 	case DTV_ATSCMH_RS_FRAME_ENSEMBLE:
1479 		tvp->u.data = fe->dtv_property_cache.atscmh_rs_frame_ensemble;
1480 		break;
1481 	case DTV_ATSCMH_RS_CODE_MODE_PRI:
1482 		tvp->u.data = fe->dtv_property_cache.atscmh_rs_code_mode_pri;
1483 		break;
1484 	case DTV_ATSCMH_RS_CODE_MODE_SEC:
1485 		tvp->u.data = fe->dtv_property_cache.atscmh_rs_code_mode_sec;
1486 		break;
1487 	case DTV_ATSCMH_SCCC_BLOCK_MODE:
1488 		tvp->u.data = fe->dtv_property_cache.atscmh_sccc_block_mode;
1489 		break;
1490 	case DTV_ATSCMH_SCCC_CODE_MODE_A:
1491 		tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_a;
1492 		break;
1493 	case DTV_ATSCMH_SCCC_CODE_MODE_B:
1494 		tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_b;
1495 		break;
1496 	case DTV_ATSCMH_SCCC_CODE_MODE_C:
1497 		tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_c;
1498 		break;
1499 	case DTV_ATSCMH_SCCC_CODE_MODE_D:
1500 		tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_d;
1501 		break;
1502 
1503 	case DTV_LNA:
1504 		tvp->u.data = c->lna;
1505 		break;
1506 
1507 	/* Fill quality measures */
1508 	case DTV_STAT_SIGNAL_STRENGTH:
1509 		tvp->u.st = c->strength;
1510 		break;
1511 	case DTV_STAT_CNR:
1512 		tvp->u.st = c->cnr;
1513 		break;
1514 	case DTV_STAT_PRE_ERROR_BIT_COUNT:
1515 		tvp->u.st = c->pre_bit_error;
1516 		break;
1517 	case DTV_STAT_PRE_TOTAL_BIT_COUNT:
1518 		tvp->u.st = c->pre_bit_count;
1519 		break;
1520 	case DTV_STAT_POST_ERROR_BIT_COUNT:
1521 		tvp->u.st = c->post_bit_error;
1522 		break;
1523 	case DTV_STAT_POST_TOTAL_BIT_COUNT:
1524 		tvp->u.st = c->post_bit_count;
1525 		break;
1526 	case DTV_STAT_ERROR_BLOCK_COUNT:
1527 		tvp->u.st = c->block_error;
1528 		break;
1529 	case DTV_STAT_TOTAL_BLOCK_COUNT:
1530 		tvp->u.st = c->block_count;
1531 		break;
1532 	default:
1533 		dev_dbg(fe->dvb->device,
1534 			"%s: FE property %d doesn't exist\n",
1535 			__func__, tvp->cmd);
1536 		return -EINVAL;
1537 	}
1538 
1539 	/* Allow the frontend to override outgoing properties */
1540 	if (fe->ops.get_property) {
1541 		r = fe->ops.get_property(fe, tvp);
1542 		if (r < 0)
1543 			return r;
1544 	}
1545 
1546 	dtv_property_dump(fe, false, tvp);
1547 
1548 	return 0;
1549 }
1550 
1551 static int dtv_set_frontend(struct dvb_frontend *fe);
1552 
1553 static bool is_dvbv3_delsys(u32 delsys)
1554 {
1555 	return (delsys == SYS_DVBT) || (delsys == SYS_DVBC_ANNEX_A) ||
1556 	       (delsys == SYS_DVBS) || (delsys == SYS_ATSC);
1557 }
1558 
1559 /**
1560  * emulate_delivery_system - emulate a DVBv5 delivery system with a DVBv3 type
1561  * @fe:			struct frontend;
1562  * @delsys:			DVBv5 type that will be used for emulation
1563  *
1564  * Provides emulation for delivery systems that are compatible with the old
1565  * DVBv3 call. Among its usages, it provices support for ISDB-T, and allows
1566  * using a DVB-S2 only frontend just like it were a DVB-S, if the frontent
1567  * parameters are compatible with DVB-S spec.
1568  */
1569 static int emulate_delivery_system(struct dvb_frontend *fe, u32 delsys)
1570 {
1571 	int i;
1572 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1573 
1574 	c->delivery_system = delsys;
1575 
1576 	/*
1577 	 * If the call is for ISDB-T, put it into full-seg, auto mode, TV
1578 	 */
1579 	if (c->delivery_system == SYS_ISDBT) {
1580 		dev_dbg(fe->dvb->device,
1581 			"%s: Using defaults for SYS_ISDBT\n",
1582 			__func__);
1583 
1584 		if (!c->bandwidth_hz)
1585 			c->bandwidth_hz = 6000000;
1586 
1587 		c->isdbt_partial_reception = 0;
1588 		c->isdbt_sb_mode = 0;
1589 		c->isdbt_sb_subchannel = 0;
1590 		c->isdbt_sb_segment_idx = 0;
1591 		c->isdbt_sb_segment_count = 0;
1592 		c->isdbt_layer_enabled = 7;
1593 		for (i = 0; i < 3; i++) {
1594 			c->layer[i].fec = FEC_AUTO;
1595 			c->layer[i].modulation = QAM_AUTO;
1596 			c->layer[i].interleaving = 0;
1597 			c->layer[i].segment_count = 0;
1598 		}
1599 	}
1600 	dev_dbg(fe->dvb->device, "%s: change delivery system on cache to %d\n",
1601 		__func__, c->delivery_system);
1602 
1603 	return 0;
1604 }
1605 
1606 /**
1607  * dvbv5_set_delivery_system - Sets the delivery system for a DVBv5 API call
1608  * @fe:			frontend struct
1609  * @desired_system:	delivery system requested by the user
1610  *
1611  * A DVBv5 call know what's the desired system it wants. So, set it.
1612  *
1613  * There are, however, a few known issues with early DVBv5 applications that
1614  * are also handled by this logic:
1615  *
1616  * 1) Some early apps use SYS_UNDEFINED as the desired delivery system.
1617  *    This is an API violation, but, as we don't want to break userspace,
1618  *    convert it to the first supported delivery system.
1619  * 2) Some apps might be using a DVBv5 call in a wrong way, passing, for
1620  *    example, SYS_DVBT instead of SYS_ISDBT. This is because early usage of
1621  *    ISDB-T provided backward compat with DVB-T.
1622  */
1623 static int dvbv5_set_delivery_system(struct dvb_frontend *fe,
1624 				     u32 desired_system)
1625 {
1626 	int ncaps;
1627 	u32 delsys = SYS_UNDEFINED;
1628 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1629 	enum dvbv3_emulation_type type;
1630 
1631 	/*
1632 	 * It was reported that some old DVBv5 applications were
1633 	 * filling delivery_system with SYS_UNDEFINED. If this happens,
1634 	 * assume that the application wants to use the first supported
1635 	 * delivery system.
1636 	 */
1637 	if (desired_system == SYS_UNDEFINED)
1638 		desired_system = fe->ops.delsys[0];
1639 
1640 	/*
1641 	 * This is a DVBv5 call. So, it likely knows the supported
1642 	 * delivery systems. So, check if the desired delivery system is
1643 	 * supported
1644 	 */
1645 	ncaps = 0;
1646 	while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) {
1647 		if (fe->ops.delsys[ncaps] == desired_system) {
1648 			c->delivery_system = desired_system;
1649 			dev_dbg(fe->dvb->device,
1650 					"%s: Changing delivery system to %d\n",
1651 					__func__, desired_system);
1652 			return 0;
1653 		}
1654 		ncaps++;
1655 	}
1656 
1657 	/*
1658 	 * The requested delivery system isn't supported. Maybe userspace
1659 	 * is requesting a DVBv3 compatible delivery system.
1660 	 *
1661 	 * The emulation only works if the desired system is one of the
1662 	 * delivery systems supported by DVBv3 API
1663 	 */
1664 	if (!is_dvbv3_delsys(desired_system)) {
1665 		dev_dbg(fe->dvb->device,
1666 			"%s: Delivery system %d not supported.\n",
1667 			__func__, desired_system);
1668 		return -EINVAL;
1669 	}
1670 
1671 	type = dvbv3_type(desired_system);
1672 
1673 	/*
1674 	* Get the last non-DVBv3 delivery system that has the same type
1675 	* of the desired system
1676 	*/
1677 	ncaps = 0;
1678 	while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) {
1679 		if (dvbv3_type(fe->ops.delsys[ncaps]) == type)
1680 			delsys = fe->ops.delsys[ncaps];
1681 		ncaps++;
1682 	}
1683 
1684 	/* There's nothing compatible with the desired delivery system */
1685 	if (delsys == SYS_UNDEFINED) {
1686 		dev_dbg(fe->dvb->device,
1687 			"%s: Delivery system %d not supported on emulation mode.\n",
1688 			__func__, desired_system);
1689 		return -EINVAL;
1690 	}
1691 
1692 	dev_dbg(fe->dvb->device,
1693 		"%s: Using delivery system %d emulated as if it were %d\n",
1694 		__func__, delsys, desired_system);
1695 
1696 	return emulate_delivery_system(fe, desired_system);
1697 }
1698 
1699 /**
1700  * dvbv3_set_delivery_system - Sets the delivery system for a DVBv3 API call
1701  * @fe:	frontend struct
1702  *
1703  * A DVBv3 call doesn't know what's the desired system it wants. It also
1704  * doesn't allow to switch between different types. Due to that, userspace
1705  * should use DVBv5 instead.
1706  * However, in order to avoid breaking userspace API, limited backward
1707  * compatibility support is provided.
1708  *
1709  * There are some delivery systems that are incompatible with DVBv3 calls.
1710  *
1711  * This routine should work fine for frontends that support just one delivery
1712  * system.
1713  *
1714  * For frontends that support multiple frontends:
1715  * 1) It defaults to use the first supported delivery system. There's an
1716  *    userspace application that allows changing it at runtime;
1717  *
1718  * 2) If the current delivery system is not compatible with DVBv3, it gets
1719  *    the first one that it is compatible.
1720  *
1721  * NOTE: in order for this to work with applications like Kaffeine that
1722  *	uses a DVBv5 call for DVB-S2 and a DVBv3 call to go back to
1723  *	DVB-S, drivers that support both DVB-S and DVB-S2 should have the
1724  *	SYS_DVBS entry before the SYS_DVBS2, otherwise it won't switch back
1725  *	to DVB-S.
1726  */
1727 static int dvbv3_set_delivery_system(struct dvb_frontend *fe)
1728 {
1729 	int ncaps;
1730 	u32 delsys = SYS_UNDEFINED;
1731 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1732 
1733 	/* If not set yet, defaults to the first supported delivery system */
1734 	if (c->delivery_system == SYS_UNDEFINED)
1735 		c->delivery_system = fe->ops.delsys[0];
1736 
1737 	/*
1738 	 * Trivial case: just use the current one, if it already a DVBv3
1739 	 * delivery system
1740 	 */
1741 	if (is_dvbv3_delsys(c->delivery_system)) {
1742 		dev_dbg(fe->dvb->device,
1743 				"%s: Using delivery system to %d\n",
1744 				__func__, c->delivery_system);
1745 		return 0;
1746 	}
1747 
1748 	/*
1749 	 * Seek for the first delivery system that it is compatible with a
1750 	 * DVBv3 standard
1751 	 */
1752 	ncaps = 0;
1753 	while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) {
1754 		if (dvbv3_type(fe->ops.delsys[ncaps]) != DVBV3_UNKNOWN) {
1755 			delsys = fe->ops.delsys[ncaps];
1756 			break;
1757 		}
1758 		ncaps++;
1759 	}
1760 	if (delsys == SYS_UNDEFINED) {
1761 		dev_dbg(fe->dvb->device,
1762 			"%s: Couldn't find a delivery system that works with FE_SET_FRONTEND\n",
1763 			__func__);
1764 		return -EINVAL;
1765 	}
1766 	return emulate_delivery_system(fe, delsys);
1767 }
1768 
1769 static int dtv_property_process_set(struct dvb_frontend *fe,
1770 				    struct dtv_property *tvp,
1771 				    struct file *file)
1772 {
1773 	int r = 0;
1774 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1775 
1776 	/* Allow the frontend to validate incoming properties */
1777 	if (fe->ops.set_property) {
1778 		r = fe->ops.set_property(fe, tvp);
1779 		if (r < 0)
1780 			return r;
1781 	}
1782 
1783 	dtv_property_dump(fe, true, tvp);
1784 
1785 	switch(tvp->cmd) {
1786 	case DTV_CLEAR:
1787 		/*
1788 		 * Reset a cache of data specific to the frontend here. This does
1789 		 * not effect hardware.
1790 		 */
1791 		dvb_frontend_clear_cache(fe);
1792 		break;
1793 	case DTV_TUNE:
1794 		/* interpret the cache of data, build either a traditional frontend
1795 		 * tunerequest so we can pass validation in the FE_SET_FRONTEND
1796 		 * ioctl.
1797 		 */
1798 		c->state = tvp->cmd;
1799 		dev_dbg(fe->dvb->device, "%s: Finalised property cache\n",
1800 				__func__);
1801 
1802 		r = dtv_set_frontend(fe);
1803 		break;
1804 	case DTV_FREQUENCY:
1805 		c->frequency = tvp->u.data;
1806 		break;
1807 	case DTV_MODULATION:
1808 		c->modulation = tvp->u.data;
1809 		break;
1810 	case DTV_BANDWIDTH_HZ:
1811 		c->bandwidth_hz = tvp->u.data;
1812 		break;
1813 	case DTV_INVERSION:
1814 		c->inversion = tvp->u.data;
1815 		break;
1816 	case DTV_SYMBOL_RATE:
1817 		c->symbol_rate = tvp->u.data;
1818 		break;
1819 	case DTV_INNER_FEC:
1820 		c->fec_inner = tvp->u.data;
1821 		break;
1822 	case DTV_PILOT:
1823 		c->pilot = tvp->u.data;
1824 		break;
1825 	case DTV_ROLLOFF:
1826 		c->rolloff = tvp->u.data;
1827 		break;
1828 	case DTV_DELIVERY_SYSTEM:
1829 		r = dvbv5_set_delivery_system(fe, tvp->u.data);
1830 		break;
1831 	case DTV_VOLTAGE:
1832 		c->voltage = tvp->u.data;
1833 		r = dvb_frontend_ioctl_legacy(file, FE_SET_VOLTAGE,
1834 			(void *)c->voltage);
1835 		break;
1836 	case DTV_TONE:
1837 		c->sectone = tvp->u.data;
1838 		r = dvb_frontend_ioctl_legacy(file, FE_SET_TONE,
1839 			(void *)c->sectone);
1840 		break;
1841 	case DTV_CODE_RATE_HP:
1842 		c->code_rate_HP = tvp->u.data;
1843 		break;
1844 	case DTV_CODE_RATE_LP:
1845 		c->code_rate_LP = tvp->u.data;
1846 		break;
1847 	case DTV_GUARD_INTERVAL:
1848 		c->guard_interval = tvp->u.data;
1849 		break;
1850 	case DTV_TRANSMISSION_MODE:
1851 		c->transmission_mode = tvp->u.data;
1852 		break;
1853 	case DTV_HIERARCHY:
1854 		c->hierarchy = tvp->u.data;
1855 		break;
1856 	case DTV_INTERLEAVING:
1857 		c->interleaving = tvp->u.data;
1858 		break;
1859 
1860 	/* ISDB-T Support here */
1861 	case DTV_ISDBT_PARTIAL_RECEPTION:
1862 		c->isdbt_partial_reception = tvp->u.data;
1863 		break;
1864 	case DTV_ISDBT_SOUND_BROADCASTING:
1865 		c->isdbt_sb_mode = tvp->u.data;
1866 		break;
1867 	case DTV_ISDBT_SB_SUBCHANNEL_ID:
1868 		c->isdbt_sb_subchannel = tvp->u.data;
1869 		break;
1870 	case DTV_ISDBT_SB_SEGMENT_IDX:
1871 		c->isdbt_sb_segment_idx = tvp->u.data;
1872 		break;
1873 	case DTV_ISDBT_SB_SEGMENT_COUNT:
1874 		c->isdbt_sb_segment_count = tvp->u.data;
1875 		break;
1876 	case DTV_ISDBT_LAYER_ENABLED:
1877 		c->isdbt_layer_enabled = tvp->u.data;
1878 		break;
1879 	case DTV_ISDBT_LAYERA_FEC:
1880 		c->layer[0].fec = tvp->u.data;
1881 		break;
1882 	case DTV_ISDBT_LAYERA_MODULATION:
1883 		c->layer[0].modulation = tvp->u.data;
1884 		break;
1885 	case DTV_ISDBT_LAYERA_SEGMENT_COUNT:
1886 		c->layer[0].segment_count = tvp->u.data;
1887 		break;
1888 	case DTV_ISDBT_LAYERA_TIME_INTERLEAVING:
1889 		c->layer[0].interleaving = tvp->u.data;
1890 		break;
1891 	case DTV_ISDBT_LAYERB_FEC:
1892 		c->layer[1].fec = tvp->u.data;
1893 		break;
1894 	case DTV_ISDBT_LAYERB_MODULATION:
1895 		c->layer[1].modulation = tvp->u.data;
1896 		break;
1897 	case DTV_ISDBT_LAYERB_SEGMENT_COUNT:
1898 		c->layer[1].segment_count = tvp->u.data;
1899 		break;
1900 	case DTV_ISDBT_LAYERB_TIME_INTERLEAVING:
1901 		c->layer[1].interleaving = tvp->u.data;
1902 		break;
1903 	case DTV_ISDBT_LAYERC_FEC:
1904 		c->layer[2].fec = tvp->u.data;
1905 		break;
1906 	case DTV_ISDBT_LAYERC_MODULATION:
1907 		c->layer[2].modulation = tvp->u.data;
1908 		break;
1909 	case DTV_ISDBT_LAYERC_SEGMENT_COUNT:
1910 		c->layer[2].segment_count = tvp->u.data;
1911 		break;
1912 	case DTV_ISDBT_LAYERC_TIME_INTERLEAVING:
1913 		c->layer[2].interleaving = tvp->u.data;
1914 		break;
1915 
1916 	/* Multistream support */
1917 	case DTV_STREAM_ID:
1918 	case DTV_DVBT2_PLP_ID_LEGACY:
1919 		c->stream_id = tvp->u.data;
1920 		break;
1921 
1922 	/* ATSC-MH */
1923 	case DTV_ATSCMH_PARADE_ID:
1924 		fe->dtv_property_cache.atscmh_parade_id = tvp->u.data;
1925 		break;
1926 	case DTV_ATSCMH_RS_FRAME_ENSEMBLE:
1927 		fe->dtv_property_cache.atscmh_rs_frame_ensemble = tvp->u.data;
1928 		break;
1929 
1930 	case DTV_LNA:
1931 		c->lna = tvp->u.data;
1932 		if (fe->ops.set_lna)
1933 			r = fe->ops.set_lna(fe);
1934 		if (r < 0)
1935 			c->lna = LNA_AUTO;
1936 		break;
1937 
1938 	default:
1939 		return -EINVAL;
1940 	}
1941 
1942 	return r;
1943 }
1944 
1945 static int dvb_frontend_ioctl(struct file *file,
1946 			unsigned int cmd, void *parg)
1947 {
1948 	struct dvb_device *dvbdev = file->private_data;
1949 	struct dvb_frontend *fe = dvbdev->priv;
1950 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1951 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
1952 	int err = -EOPNOTSUPP;
1953 
1954 	dev_dbg(fe->dvb->device, "%s: (%d)\n", __func__, _IOC_NR(cmd));
1955 	if (down_interruptible(&fepriv->sem))
1956 		return -ERESTARTSYS;
1957 
1958 	if (fe->exit != DVB_FE_NO_EXIT) {
1959 		up(&fepriv->sem);
1960 		return -ENODEV;
1961 	}
1962 
1963 	if ((file->f_flags & O_ACCMODE) == O_RDONLY &&
1964 	    (_IOC_DIR(cmd) != _IOC_READ || cmd == FE_GET_EVENT ||
1965 	     cmd == FE_DISEQC_RECV_SLAVE_REPLY)) {
1966 		up(&fepriv->sem);
1967 		return -EPERM;
1968 	}
1969 
1970 	if ((cmd == FE_SET_PROPERTY) || (cmd == FE_GET_PROPERTY))
1971 		err = dvb_frontend_ioctl_properties(file, cmd, parg);
1972 	else {
1973 		c->state = DTV_UNDEFINED;
1974 		err = dvb_frontend_ioctl_legacy(file, cmd, parg);
1975 	}
1976 
1977 	up(&fepriv->sem);
1978 	return err;
1979 }
1980 
1981 static int dvb_frontend_ioctl_properties(struct file *file,
1982 			unsigned int cmd, void *parg)
1983 {
1984 	struct dvb_device *dvbdev = file->private_data;
1985 	struct dvb_frontend *fe = dvbdev->priv;
1986 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
1987 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
1988 	int err = 0;
1989 
1990 	struct dtv_properties *tvps = parg;
1991 	struct dtv_property *tvp = NULL;
1992 	int i;
1993 
1994 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
1995 
1996 	if (cmd == FE_SET_PROPERTY) {
1997 		dev_dbg(fe->dvb->device, "%s: properties.num = %d\n", __func__, tvps->num);
1998 		dev_dbg(fe->dvb->device, "%s: properties.props = %p\n", __func__, tvps->props);
1999 
2000 		/* Put an arbitrary limit on the number of messages that can
2001 		 * be sent at once */
2002 		if ((tvps->num == 0) || (tvps->num > DTV_IOCTL_MAX_MSGS))
2003 			return -EINVAL;
2004 
2005 		tvp = memdup_user(tvps->props, tvps->num * sizeof(*tvp));
2006 		if (IS_ERR(tvp))
2007 			return PTR_ERR(tvp);
2008 
2009 		for (i = 0; i < tvps->num; i++) {
2010 			err = dtv_property_process_set(fe, tvp + i, file);
2011 			if (err < 0)
2012 				goto out;
2013 			(tvp + i)->result = err;
2014 		}
2015 
2016 		if (c->state == DTV_TUNE)
2017 			dev_dbg(fe->dvb->device, "%s: Property cache is full, tuning\n", __func__);
2018 
2019 	} else if (cmd == FE_GET_PROPERTY) {
2020 		struct dtv_frontend_properties getp = fe->dtv_property_cache;
2021 
2022 		dev_dbg(fe->dvb->device, "%s: properties.num = %d\n", __func__, tvps->num);
2023 		dev_dbg(fe->dvb->device, "%s: properties.props = %p\n", __func__, tvps->props);
2024 
2025 		/* Put an arbitrary limit on the number of messages that can
2026 		 * be sent at once */
2027 		if ((tvps->num == 0) || (tvps->num > DTV_IOCTL_MAX_MSGS))
2028 			return -EINVAL;
2029 
2030 		tvp = memdup_user(tvps->props, tvps->num * sizeof(*tvp));
2031 		if (IS_ERR(tvp))
2032 			return PTR_ERR(tvp);
2033 
2034 		/*
2035 		 * Let's use our own copy of property cache, in order to
2036 		 * avoid mangling with DTV zigzag logic, as drivers might
2037 		 * return crap, if they don't check if the data is available
2038 		 * before updating the properties cache.
2039 		 */
2040 		if (fepriv->state != FESTATE_IDLE) {
2041 			err = dtv_get_frontend(fe, &getp, NULL);
2042 			if (err < 0)
2043 				goto out;
2044 		}
2045 		for (i = 0; i < tvps->num; i++) {
2046 			err = dtv_property_process_get(fe, &getp, tvp + i, file);
2047 			if (err < 0)
2048 				goto out;
2049 			(tvp + i)->result = err;
2050 		}
2051 
2052 		if (copy_to_user((void __user *)tvps->props, tvp,
2053 				 tvps->num * sizeof(struct dtv_property))) {
2054 			err = -EFAULT;
2055 			goto out;
2056 		}
2057 
2058 	} else
2059 		err = -EOPNOTSUPP;
2060 
2061 out:
2062 	kfree(tvp);
2063 	return err;
2064 }
2065 
2066 static int dtv_set_frontend(struct dvb_frontend *fe)
2067 {
2068 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2069 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
2070 	struct dvb_frontend_tune_settings fetunesettings;
2071 	u32 rolloff = 0;
2072 
2073 	if (dvb_frontend_check_parameters(fe) < 0)
2074 		return -EINVAL;
2075 
2076 	/*
2077 	 * Initialize output parameters to match the values given by
2078 	 * the user. FE_SET_FRONTEND triggers an initial frontend event
2079 	 * with status = 0, which copies output parameters to userspace.
2080 	 */
2081 	dtv_property_legacy_params_sync(fe, c, &fepriv->parameters_out);
2082 
2083 	/*
2084 	 * Be sure that the bandwidth will be filled for all
2085 	 * non-satellite systems, as tuners need to know what
2086 	 * low pass/Nyquist half filter should be applied, in
2087 	 * order to avoid inter-channel noise.
2088 	 *
2089 	 * ISDB-T and DVB-T/T2 already sets bandwidth.
2090 	 * ATSC and DVB-C don't set, so, the core should fill it.
2091 	 *
2092 	 * On DVB-C Annex A and C, the bandwidth is a function of
2093 	 * the roll-off and symbol rate. Annex B defines different
2094 	 * roll-off factors depending on the modulation. Fortunately,
2095 	 * Annex B is only used with 6MHz, so there's no need to
2096 	 * calculate it.
2097 	 *
2098 	 * While not officially supported, a side effect of handling it at
2099 	 * the cache level is that a program could retrieve the bandwidth
2100 	 * via DTV_BANDWIDTH_HZ, which may be useful for test programs.
2101 	 */
2102 	switch (c->delivery_system) {
2103 	case SYS_ATSC:
2104 	case SYS_DVBC_ANNEX_B:
2105 		c->bandwidth_hz = 6000000;
2106 		break;
2107 	case SYS_DVBC_ANNEX_A:
2108 		rolloff = 115;
2109 		break;
2110 	case SYS_DVBC_ANNEX_C:
2111 		rolloff = 113;
2112 		break;
2113 	case SYS_DVBS:
2114 	case SYS_TURBO:
2115 	case SYS_ISDBS:
2116 		rolloff = 135;
2117 		break;
2118 	case SYS_DVBS2:
2119 		switch (c->rolloff) {
2120 		case ROLLOFF_20:
2121 			rolloff = 120;
2122 			break;
2123 		case ROLLOFF_25:
2124 			rolloff = 125;
2125 			break;
2126 		default:
2127 		case ROLLOFF_35:
2128 			rolloff = 135;
2129 		}
2130 		break;
2131 	default:
2132 		break;
2133 	}
2134 	if (rolloff)
2135 		c->bandwidth_hz = mult_frac(c->symbol_rate, rolloff, 100);
2136 
2137 	/* force auto frequency inversion if requested */
2138 	if (dvb_force_auto_inversion)
2139 		c->inversion = INVERSION_AUTO;
2140 
2141 	/*
2142 	 * without hierarchical coding code_rate_LP is irrelevant,
2143 	 * so we tolerate the otherwise invalid FEC_NONE setting
2144 	 */
2145 	if (c->hierarchy == HIERARCHY_NONE && c->code_rate_LP == FEC_NONE)
2146 		c->code_rate_LP = FEC_AUTO;
2147 
2148 	/* get frontend-specific tuning settings */
2149 	memset(&fetunesettings, 0, sizeof(struct dvb_frontend_tune_settings));
2150 	if (fe->ops.get_tune_settings && (fe->ops.get_tune_settings(fe, &fetunesettings) == 0)) {
2151 		fepriv->min_delay = (fetunesettings.min_delay_ms * HZ) / 1000;
2152 		fepriv->max_drift = fetunesettings.max_drift;
2153 		fepriv->step_size = fetunesettings.step_size;
2154 	} else {
2155 		/* default values */
2156 		switch (c->delivery_system) {
2157 		case SYS_DVBS:
2158 		case SYS_DVBS2:
2159 		case SYS_ISDBS:
2160 		case SYS_TURBO:
2161 		case SYS_DVBC_ANNEX_A:
2162 		case SYS_DVBC_ANNEX_C:
2163 			fepriv->min_delay = HZ / 20;
2164 			fepriv->step_size = c->symbol_rate / 16000;
2165 			fepriv->max_drift = c->symbol_rate / 2000;
2166 			break;
2167 		case SYS_DVBT:
2168 		case SYS_DVBT2:
2169 		case SYS_ISDBT:
2170 		case SYS_DTMB:
2171 			fepriv->min_delay = HZ / 20;
2172 			fepriv->step_size = fe->ops.info.frequency_stepsize * 2;
2173 			fepriv->max_drift = (fe->ops.info.frequency_stepsize * 2) + 1;
2174 			break;
2175 		default:
2176 			/*
2177 			 * FIXME: This sounds wrong! if freqency_stepsize is
2178 			 * defined by the frontend, why not use it???
2179 			 */
2180 			fepriv->min_delay = HZ / 20;
2181 			fepriv->step_size = 0; /* no zigzag */
2182 			fepriv->max_drift = 0;
2183 			break;
2184 		}
2185 	}
2186 	if (dvb_override_tune_delay > 0)
2187 		fepriv->min_delay = (dvb_override_tune_delay * HZ) / 1000;
2188 
2189 	fepriv->state = FESTATE_RETUNE;
2190 
2191 	/* Request the search algorithm to search */
2192 	fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN;
2193 
2194 	dvb_frontend_clear_events(fe);
2195 	dvb_frontend_add_event(fe, 0);
2196 	dvb_frontend_wakeup(fe);
2197 	fepriv->status = 0;
2198 
2199 	return 0;
2200 }
2201 
2202 
2203 static int dvb_frontend_ioctl_legacy(struct file *file,
2204 			unsigned int cmd, void *parg)
2205 {
2206 	struct dvb_device *dvbdev = file->private_data;
2207 	struct dvb_frontend *fe = dvbdev->priv;
2208 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2209 	struct dtv_frontend_properties *c = &fe->dtv_property_cache;
2210 	int err = -EOPNOTSUPP;
2211 
2212 	switch (cmd) {
2213 	case FE_GET_INFO: {
2214 		struct dvb_frontend_info* info = parg;
2215 
2216 		memcpy(info, &fe->ops.info, sizeof(struct dvb_frontend_info));
2217 		dvb_frontend_get_frequency_limits(fe, &info->frequency_min, &info->frequency_max);
2218 
2219 		/*
2220 		 * Associate the 4 delivery systems supported by DVBv3
2221 		 * API with their DVBv5 counterpart. For the other standards,
2222 		 * use the closest type, assuming that it would hopefully
2223 		 * work with a DVBv3 application.
2224 		 * It should be noticed that, on multi-frontend devices with
2225 		 * different types (terrestrial and cable, for example),
2226 		 * a pure DVBv3 application won't be able to use all delivery
2227 		 * systems. Yet, changing the DVBv5 cache to the other delivery
2228 		 * system should be enough for making it work.
2229 		 */
2230 		switch (dvbv3_type(c->delivery_system)) {
2231 		case DVBV3_QPSK:
2232 			info->type = FE_QPSK;
2233 			break;
2234 		case DVBV3_ATSC:
2235 			info->type = FE_ATSC;
2236 			break;
2237 		case DVBV3_QAM:
2238 			info->type = FE_QAM;
2239 			break;
2240 		case DVBV3_OFDM:
2241 			info->type = FE_OFDM;
2242 			break;
2243 		default:
2244 			dev_err(fe->dvb->device,
2245 					"%s: doesn't know how to handle a DVBv3 call to delivery system %i\n",
2246 					__func__, c->delivery_system);
2247 			fe->ops.info.type = FE_OFDM;
2248 		}
2249 		dev_dbg(fe->dvb->device, "%s: current delivery system on cache: %d, V3 type: %d\n",
2250 				 __func__, c->delivery_system, fe->ops.info.type);
2251 
2252 		/* Set CAN_INVERSION_AUTO bit on in other than oneshot mode */
2253 		if (!(fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT))
2254 			info->caps |= FE_CAN_INVERSION_AUTO;
2255 		err = 0;
2256 		break;
2257 	}
2258 
2259 	case FE_READ_STATUS: {
2260 		enum fe_status *status = parg;
2261 
2262 		/* if retune was requested but hasn't occurred yet, prevent
2263 		 * that user get signal state from previous tuning */
2264 		if (fepriv->state == FESTATE_RETUNE ||
2265 		    fepriv->state == FESTATE_ERROR) {
2266 			err=0;
2267 			*status = 0;
2268 			break;
2269 		}
2270 
2271 		if (fe->ops.read_status)
2272 			err = fe->ops.read_status(fe, status);
2273 		break;
2274 	}
2275 
2276 	case FE_READ_BER:
2277 		if (fe->ops.read_ber) {
2278 			if (fepriv->thread)
2279 				err = fe->ops.read_ber(fe, (__u32 *) parg);
2280 			else
2281 				err = -EAGAIN;
2282 		}
2283 		break;
2284 
2285 	case FE_READ_SIGNAL_STRENGTH:
2286 		if (fe->ops.read_signal_strength) {
2287 			if (fepriv->thread)
2288 				err = fe->ops.read_signal_strength(fe, (__u16 *) parg);
2289 			else
2290 				err = -EAGAIN;
2291 		}
2292 		break;
2293 
2294 	case FE_READ_SNR:
2295 		if (fe->ops.read_snr) {
2296 			if (fepriv->thread)
2297 				err = fe->ops.read_snr(fe, (__u16 *) parg);
2298 			else
2299 				err = -EAGAIN;
2300 		}
2301 		break;
2302 
2303 	case FE_READ_UNCORRECTED_BLOCKS:
2304 		if (fe->ops.read_ucblocks) {
2305 			if (fepriv->thread)
2306 				err = fe->ops.read_ucblocks(fe, (__u32 *) parg);
2307 			else
2308 				err = -EAGAIN;
2309 		}
2310 		break;
2311 
2312 	case FE_DISEQC_RESET_OVERLOAD:
2313 		if (fe->ops.diseqc_reset_overload) {
2314 			err = fe->ops.diseqc_reset_overload(fe);
2315 			fepriv->state = FESTATE_DISEQC;
2316 			fepriv->status = 0;
2317 		}
2318 		break;
2319 
2320 	case FE_DISEQC_SEND_MASTER_CMD:
2321 		if (fe->ops.diseqc_send_master_cmd) {
2322 			struct dvb_diseqc_master_cmd *cmd = parg;
2323 
2324 			if (cmd->msg_len > sizeof(cmd->msg)) {
2325 				err = -EINVAL;
2326 				break;
2327 			}
2328 			err = fe->ops.diseqc_send_master_cmd(fe, cmd);
2329 			fepriv->state = FESTATE_DISEQC;
2330 			fepriv->status = 0;
2331 		}
2332 		break;
2333 
2334 	case FE_DISEQC_SEND_BURST:
2335 		if (fe->ops.diseqc_send_burst) {
2336 			err = fe->ops.diseqc_send_burst(fe,
2337 						(enum fe_sec_mini_cmd)parg);
2338 			fepriv->state = FESTATE_DISEQC;
2339 			fepriv->status = 0;
2340 		}
2341 		break;
2342 
2343 	case FE_SET_TONE:
2344 		if (fe->ops.set_tone) {
2345 			err = fe->ops.set_tone(fe,
2346 					       (enum fe_sec_tone_mode)parg);
2347 			fepriv->tone = (enum fe_sec_tone_mode)parg;
2348 			fepriv->state = FESTATE_DISEQC;
2349 			fepriv->status = 0;
2350 		}
2351 		break;
2352 
2353 	case FE_SET_VOLTAGE:
2354 		if (fe->ops.set_voltage) {
2355 			err = fe->ops.set_voltage(fe,
2356 						  (enum fe_sec_voltage)parg);
2357 			fepriv->voltage = (enum fe_sec_voltage)parg;
2358 			fepriv->state = FESTATE_DISEQC;
2359 			fepriv->status = 0;
2360 		}
2361 		break;
2362 
2363 	case FE_DISHNETWORK_SEND_LEGACY_CMD:
2364 		if (fe->ops.dishnetwork_send_legacy_command) {
2365 			err = fe->ops.dishnetwork_send_legacy_command(fe,
2366 							 (unsigned long)parg);
2367 			fepriv->state = FESTATE_DISEQC;
2368 			fepriv->status = 0;
2369 		} else if (fe->ops.set_voltage) {
2370 			/*
2371 			 * NOTE: This is a fallback condition.  Some frontends
2372 			 * (stv0299 for instance) take longer than 8msec to
2373 			 * respond to a set_voltage command.  Those switches
2374 			 * need custom routines to switch properly.  For all
2375 			 * other frontends, the following should work ok.
2376 			 * Dish network legacy switches (as used by Dish500)
2377 			 * are controlled by sending 9-bit command words
2378 			 * spaced 8msec apart.
2379 			 * the actual command word is switch/port dependent
2380 			 * so it is up to the userspace application to send
2381 			 * the right command.
2382 			 * The command must always start with a '0' after
2383 			 * initialization, so parg is 8 bits and does not
2384 			 * include the initialization or start bit
2385 			 */
2386 			unsigned long swcmd = ((unsigned long) parg) << 1;
2387 			ktime_t nexttime;
2388 			ktime_t tv[10];
2389 			int i;
2390 			u8 last = 1;
2391 			if (dvb_frontend_debug)
2392 				dprintk("%s switch command: 0x%04lx\n",
2393 					__func__, swcmd);
2394 			nexttime = ktime_get_boottime();
2395 			if (dvb_frontend_debug)
2396 				tv[0] = nexttime;
2397 			/* before sending a command, initialize by sending
2398 			 * a 32ms 18V to the switch
2399 			 */
2400 			fe->ops.set_voltage(fe, SEC_VOLTAGE_18);
2401 			dvb_frontend_sleep_until(&nexttime, 32000);
2402 
2403 			for (i = 0; i < 9; i++) {
2404 				if (dvb_frontend_debug)
2405 					tv[i+1] = ktime_get_boottime();
2406 				if ((swcmd & 0x01) != last) {
2407 					/* set voltage to (last ? 13V : 18V) */
2408 					fe->ops.set_voltage(fe, (last) ? SEC_VOLTAGE_13 : SEC_VOLTAGE_18);
2409 					last = (last) ? 0 : 1;
2410 				}
2411 				swcmd = swcmd >> 1;
2412 				if (i != 8)
2413 					dvb_frontend_sleep_until(&nexttime, 8000);
2414 			}
2415 			if (dvb_frontend_debug) {
2416 				dprintk("%s(%d): switch delay (should be 32k followed by all 8k)\n",
2417 					__func__, fe->dvb->num);
2418 				for (i = 1; i < 10; i++)
2419 					pr_info("%d: %d\n", i,
2420 					(int) ktime_us_delta(tv[i], tv[i-1]));
2421 			}
2422 			err = 0;
2423 			fepriv->state = FESTATE_DISEQC;
2424 			fepriv->status = 0;
2425 		}
2426 		break;
2427 
2428 	case FE_DISEQC_RECV_SLAVE_REPLY:
2429 		if (fe->ops.diseqc_recv_slave_reply)
2430 			err = fe->ops.diseqc_recv_slave_reply(fe, (struct dvb_diseqc_slave_reply*) parg);
2431 		break;
2432 
2433 	case FE_ENABLE_HIGH_LNB_VOLTAGE:
2434 		if (fe->ops.enable_high_lnb_voltage)
2435 			err = fe->ops.enable_high_lnb_voltage(fe, (long) parg);
2436 		break;
2437 
2438 	case FE_SET_FRONTEND:
2439 		err = dvbv3_set_delivery_system(fe);
2440 		if (err)
2441 			break;
2442 
2443 		err = dtv_property_cache_sync(fe, c, parg);
2444 		if (err)
2445 			break;
2446 		err = dtv_set_frontend(fe);
2447 		break;
2448 	case FE_GET_EVENT:
2449 		err = dvb_frontend_get_event (fe, parg, file->f_flags);
2450 		break;
2451 
2452 	case FE_GET_FRONTEND: {
2453 		struct dtv_frontend_properties getp = fe->dtv_property_cache;
2454 
2455 		/*
2456 		 * Let's use our own copy of property cache, in order to
2457 		 * avoid mangling with DTV zigzag logic, as drivers might
2458 		 * return crap, if they don't check if the data is available
2459 		 * before updating the properties cache.
2460 		 */
2461 		err = dtv_get_frontend(fe, &getp, parg);
2462 		break;
2463 	}
2464 	case FE_SET_FRONTEND_TUNE_MODE:
2465 		fepriv->tune_mode_flags = (unsigned long) parg;
2466 		err = 0;
2467 		break;
2468 	}
2469 
2470 	return err;
2471 }
2472 
2473 
2474 static unsigned int dvb_frontend_poll(struct file *file, struct poll_table_struct *wait)
2475 {
2476 	struct dvb_device *dvbdev = file->private_data;
2477 	struct dvb_frontend *fe = dvbdev->priv;
2478 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2479 
2480 	dev_dbg_ratelimited(fe->dvb->device, "%s:\n", __func__);
2481 
2482 	poll_wait (file, &fepriv->events.wait_queue, wait);
2483 
2484 	if (fepriv->events.eventw != fepriv->events.eventr)
2485 		return (POLLIN | POLLRDNORM | POLLPRI);
2486 
2487 	return 0;
2488 }
2489 
2490 static int dvb_frontend_open(struct inode *inode, struct file *file)
2491 {
2492 	struct dvb_device *dvbdev = file->private_data;
2493 	struct dvb_frontend *fe = dvbdev->priv;
2494 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2495 	struct dvb_adapter *adapter = fe->dvb;
2496 	int ret;
2497 
2498 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
2499 	if (fe->exit == DVB_FE_DEVICE_REMOVED)
2500 		return -ENODEV;
2501 
2502 	if (adapter->mfe_shared) {
2503 		mutex_lock (&adapter->mfe_lock);
2504 
2505 		if (adapter->mfe_dvbdev == NULL)
2506 			adapter->mfe_dvbdev = dvbdev;
2507 
2508 		else if (adapter->mfe_dvbdev != dvbdev) {
2509 			struct dvb_device
2510 				*mfedev = adapter->mfe_dvbdev;
2511 			struct dvb_frontend
2512 				*mfe = mfedev->priv;
2513 			struct dvb_frontend_private
2514 				*mfepriv = mfe->frontend_priv;
2515 			int mferetry = (dvb_mfe_wait_time << 1);
2516 
2517 			mutex_unlock (&adapter->mfe_lock);
2518 			while (mferetry-- && (mfedev->users != -1 ||
2519 					mfepriv->thread != NULL)) {
2520 				if(msleep_interruptible(500)) {
2521 					if(signal_pending(current))
2522 						return -EINTR;
2523 				}
2524 			}
2525 
2526 			mutex_lock (&adapter->mfe_lock);
2527 			if(adapter->mfe_dvbdev != dvbdev) {
2528 				mfedev = adapter->mfe_dvbdev;
2529 				mfe = mfedev->priv;
2530 				mfepriv = mfe->frontend_priv;
2531 				if (mfedev->users != -1 ||
2532 						mfepriv->thread != NULL) {
2533 					mutex_unlock (&adapter->mfe_lock);
2534 					return -EBUSY;
2535 				}
2536 				adapter->mfe_dvbdev = dvbdev;
2537 			}
2538 		}
2539 	}
2540 
2541 	if (dvbdev->users == -1 && fe->ops.ts_bus_ctrl) {
2542 		if ((ret = fe->ops.ts_bus_ctrl(fe, 1)) < 0)
2543 			goto err0;
2544 
2545 		/* If we took control of the bus, we need to force
2546 		   reinitialization.  This is because many ts_bus_ctrl()
2547 		   functions strobe the RESET pin on the demod, and if the
2548 		   frontend thread already exists then the dvb_init() routine
2549 		   won't get called (which is what usually does initial
2550 		   register configuration). */
2551 		fepriv->reinitialise = 1;
2552 	}
2553 
2554 	if ((ret = dvb_generic_open (inode, file)) < 0)
2555 		goto err1;
2556 
2557 	if ((file->f_flags & O_ACCMODE) != O_RDONLY) {
2558 		/* normal tune mode when opened R/W */
2559 		fepriv->tune_mode_flags &= ~FE_TUNE_MODE_ONESHOT;
2560 		fepriv->tone = -1;
2561 		fepriv->voltage = -1;
2562 
2563 #ifdef CONFIG_MEDIA_CONTROLLER_DVB
2564 		if (fe->dvb->mdev) {
2565 			mutex_lock(&fe->dvb->mdev->graph_mutex);
2566 			if (fe->dvb->mdev->enable_source)
2567 				ret = fe->dvb->mdev->enable_source(
2568 							   dvbdev->entity,
2569 							   &fepriv->pipe);
2570 			mutex_unlock(&fe->dvb->mdev->graph_mutex);
2571 			if (ret) {
2572 				dev_err(fe->dvb->device,
2573 					"Tuner is busy. Error %d\n", ret);
2574 				goto err2;
2575 			}
2576 		}
2577 #endif
2578 		ret = dvb_frontend_start (fe);
2579 		if (ret)
2580 			goto err3;
2581 
2582 		/*  empty event queue */
2583 		fepriv->events.eventr = fepriv->events.eventw = 0;
2584 	}
2585 
2586 	dvb_frontend_get(fe);
2587 
2588 	if (adapter->mfe_shared)
2589 		mutex_unlock (&adapter->mfe_lock);
2590 	return ret;
2591 
2592 err3:
2593 #ifdef CONFIG_MEDIA_CONTROLLER_DVB
2594 	if (fe->dvb->mdev) {
2595 		mutex_lock(&fe->dvb->mdev->graph_mutex);
2596 		if (fe->dvb->mdev->disable_source)
2597 			fe->dvb->mdev->disable_source(dvbdev->entity);
2598 		mutex_unlock(&fe->dvb->mdev->graph_mutex);
2599 	}
2600 err2:
2601 #endif
2602 	dvb_generic_release(inode, file);
2603 err1:
2604 	if (dvbdev->users == -1 && fe->ops.ts_bus_ctrl)
2605 		fe->ops.ts_bus_ctrl(fe, 0);
2606 err0:
2607 	if (adapter->mfe_shared)
2608 		mutex_unlock (&adapter->mfe_lock);
2609 	return ret;
2610 }
2611 
2612 static int dvb_frontend_release(struct inode *inode, struct file *file)
2613 {
2614 	struct dvb_device *dvbdev = file->private_data;
2615 	struct dvb_frontend *fe = dvbdev->priv;
2616 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2617 	int ret;
2618 
2619 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
2620 
2621 	if ((file->f_flags & O_ACCMODE) != O_RDONLY) {
2622 		fepriv->release_jiffies = jiffies;
2623 		mb();
2624 	}
2625 
2626 	ret = dvb_generic_release (inode, file);
2627 
2628 	if (dvbdev->users == -1) {
2629 		wake_up(&fepriv->wait_queue);
2630 #ifdef CONFIG_MEDIA_CONTROLLER_DVB
2631 		if (fe->dvb->mdev) {
2632 			mutex_lock(&fe->dvb->mdev->graph_mutex);
2633 			if (fe->dvb->mdev->disable_source)
2634 				fe->dvb->mdev->disable_source(dvbdev->entity);
2635 			mutex_unlock(&fe->dvb->mdev->graph_mutex);
2636 		}
2637 #endif
2638 		if (fe->exit != DVB_FE_NO_EXIT)
2639 			wake_up(&dvbdev->wait_queue);
2640 		if (fe->ops.ts_bus_ctrl)
2641 			fe->ops.ts_bus_ctrl(fe, 0);
2642 	}
2643 
2644 	dvb_frontend_put(fe);
2645 
2646 	return ret;
2647 }
2648 
2649 static const struct file_operations dvb_frontend_fops = {
2650 	.owner		= THIS_MODULE,
2651 	.unlocked_ioctl	= dvb_generic_ioctl,
2652 	.poll		= dvb_frontend_poll,
2653 	.open		= dvb_frontend_open,
2654 	.release	= dvb_frontend_release,
2655 	.llseek		= noop_llseek,
2656 };
2657 
2658 int dvb_frontend_suspend(struct dvb_frontend *fe)
2659 {
2660 	int ret = 0;
2661 
2662 	dev_dbg(fe->dvb->device, "%s: adap=%d fe=%d\n", __func__, fe->dvb->num,
2663 			fe->id);
2664 
2665 	if (fe->ops.tuner_ops.suspend)
2666 		ret = fe->ops.tuner_ops.suspend(fe);
2667 	else if (fe->ops.tuner_ops.sleep)
2668 		ret = fe->ops.tuner_ops.sleep(fe);
2669 
2670 	if (fe->ops.sleep)
2671 		ret = fe->ops.sleep(fe);
2672 
2673 	return ret;
2674 }
2675 EXPORT_SYMBOL(dvb_frontend_suspend);
2676 
2677 int dvb_frontend_resume(struct dvb_frontend *fe)
2678 {
2679 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2680 	int ret = 0;
2681 
2682 	dev_dbg(fe->dvb->device, "%s: adap=%d fe=%d\n", __func__, fe->dvb->num,
2683 			fe->id);
2684 
2685 	fe->exit = DVB_FE_DEVICE_RESUME;
2686 	if (fe->ops.init)
2687 		ret = fe->ops.init(fe);
2688 
2689 	if (fe->ops.tuner_ops.resume)
2690 		ret = fe->ops.tuner_ops.resume(fe);
2691 	else if (fe->ops.tuner_ops.init)
2692 		ret = fe->ops.tuner_ops.init(fe);
2693 
2694 	if (fe->ops.set_tone && fepriv->tone != -1)
2695 		fe->ops.set_tone(fe, fepriv->tone);
2696 	if (fe->ops.set_voltage && fepriv->voltage != -1)
2697 		fe->ops.set_voltage(fe, fepriv->voltage);
2698 
2699 	fe->exit = DVB_FE_NO_EXIT;
2700 	fepriv->state = FESTATE_RETUNE;
2701 	dvb_frontend_wakeup(fe);
2702 
2703 	return ret;
2704 }
2705 EXPORT_SYMBOL(dvb_frontend_resume);
2706 
2707 int dvb_register_frontend(struct dvb_adapter* dvb,
2708 			  struct dvb_frontend* fe)
2709 {
2710 	struct dvb_frontend_private *fepriv;
2711 	const struct dvb_device dvbdev_template = {
2712 		.users = ~0,
2713 		.writers = 1,
2714 		.readers = (~0)-1,
2715 		.fops = &dvb_frontend_fops,
2716 #if defined(CONFIG_MEDIA_CONTROLLER_DVB)
2717 		.name = fe->ops.info.name,
2718 #endif
2719 		.kernel_ioctl = dvb_frontend_ioctl
2720 	};
2721 
2722 	dev_dbg(dvb->device, "%s:\n", __func__);
2723 
2724 	if (mutex_lock_interruptible(&frontend_mutex))
2725 		return -ERESTARTSYS;
2726 
2727 	fe->frontend_priv = kzalloc(sizeof(struct dvb_frontend_private), GFP_KERNEL);
2728 	if (fe->frontend_priv == NULL) {
2729 		mutex_unlock(&frontend_mutex);
2730 		return -ENOMEM;
2731 	}
2732 	fepriv = fe->frontend_priv;
2733 
2734 	kref_init(&fe->refcount);
2735 
2736 	/*
2737 	 * After initialization, there need to be two references: one
2738 	 * for dvb_unregister_frontend(), and another one for
2739 	 * dvb_frontend_detach().
2740 	 */
2741 	dvb_frontend_get(fe);
2742 
2743 	sema_init(&fepriv->sem, 1);
2744 	init_waitqueue_head (&fepriv->wait_queue);
2745 	init_waitqueue_head (&fepriv->events.wait_queue);
2746 	mutex_init(&fepriv->events.mtx);
2747 	fe->dvb = dvb;
2748 	fepriv->inversion = INVERSION_OFF;
2749 
2750 	dev_info(fe->dvb->device,
2751 			"DVB: registering adapter %i frontend %i (%s)...\n",
2752 			fe->dvb->num, fe->id, fe->ops.info.name);
2753 
2754 	dvb_register_device (fe->dvb, &fepriv->dvbdev, &dvbdev_template,
2755 			     fe, DVB_DEVICE_FRONTEND, 0);
2756 
2757 	/*
2758 	 * Initialize the cache to the proper values according with the
2759 	 * first supported delivery system (ops->delsys[0])
2760 	 */
2761 
2762 	fe->dtv_property_cache.delivery_system = fe->ops.delsys[0];
2763 	dvb_frontend_clear_cache(fe);
2764 
2765 	mutex_unlock(&frontend_mutex);
2766 	return 0;
2767 }
2768 EXPORT_SYMBOL(dvb_register_frontend);
2769 
2770 int dvb_unregister_frontend(struct dvb_frontend* fe)
2771 {
2772 	struct dvb_frontend_private *fepriv = fe->frontend_priv;
2773 	dev_dbg(fe->dvb->device, "%s:\n", __func__);
2774 
2775 	mutex_lock(&frontend_mutex);
2776 	dvb_frontend_stop(fe);
2777 	dvb_remove_device(fepriv->dvbdev);
2778 
2779 	/* fe is invalid now */
2780 	mutex_unlock(&frontend_mutex);
2781 	dvb_frontend_put(fe);
2782 	return 0;
2783 }
2784 EXPORT_SYMBOL(dvb_unregister_frontend);
2785 
2786 static void dvb_frontend_invoke_release(struct dvb_frontend *fe,
2787 					void (*release)(struct dvb_frontend *fe))
2788 {
2789 	if (release) {
2790 		release(fe);
2791 #ifdef CONFIG_MEDIA_ATTACH
2792 		dvb_detach(release);
2793 #endif
2794 	}
2795 }
2796 
2797 void dvb_frontend_detach(struct dvb_frontend* fe)
2798 {
2799 	dvb_frontend_invoke_release(fe, fe->ops.release_sec);
2800 	dvb_frontend_invoke_release(fe, fe->ops.tuner_ops.release);
2801 	dvb_frontend_invoke_release(fe, fe->ops.analog_ops.release);
2802 	dvb_frontend_invoke_release(fe, fe->ops.detach);
2803 	dvb_frontend_put(fe);
2804 }
2805 EXPORT_SYMBOL(dvb_frontend_detach);
2806