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