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