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