Linux Audio

Check our new training course

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