V4L/DVB (5935): dvb_frontend: Range check of frequency and symbol rate
[linux-2.6] / drivers / media / dvb / dvb-core / dvb_frontend.c
1 /*
2  * dvb_frontend.c: DVB frontend tuning interface/thread
3  *
4  *
5  * Copyright (C) 1999-2001 Ralph  Metzler
6  *                         Marcus Metzler
7  *                         Holger Waechtler
8  *                                    for convergence integrated media GmbH
9  *
10  * Copyright (C) 2004 Andrew de Quincey (tuning thread cleanup)
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
26  */
27
28 #include <linux/string.h>
29 #include <linux/kernel.h>
30 #include <linux/sched.h>
31 #include <linux/wait.h>
32 #include <linux/slab.h>
33 #include <linux/poll.h>
34 #include <linux/module.h>
35 #include <linux/moduleparam.h>
36 #include <linux/list.h>
37 #include <linux/freezer.h>
38 #include <linux/jiffies.h>
39 #include <linux/kthread.h>
40 #include <asm/processor.h>
41
42 #include "dvb_frontend.h"
43 #include "dvbdev.h"
44
45 static int dvb_frontend_debug;
46 static int dvb_shutdown_timeout = 5;
47 static int dvb_force_auto_inversion;
48 static int dvb_override_tune_delay;
49 static int dvb_powerdown_on_sleep = 1;
50
51 module_param_named(frontend_debug, dvb_frontend_debug, int, 0644);
52 MODULE_PARM_DESC(frontend_debug, "Turn on/off frontend core debugging (default:off).");
53 module_param(dvb_shutdown_timeout, int, 0644);
54 MODULE_PARM_DESC(dvb_shutdown_timeout, "wait <shutdown_timeout> seconds after close() before suspending hardware");
55 module_param(dvb_force_auto_inversion, int, 0644);
56 MODULE_PARM_DESC(dvb_force_auto_inversion, "0: normal (default), 1: INVERSION_AUTO forced always");
57 module_param(dvb_override_tune_delay, int, 0644);
58 MODULE_PARM_DESC(dvb_override_tune_delay, "0: normal (default), >0 => delay in milliseconds to wait for lock after a tune attempt");
59 module_param(dvb_powerdown_on_sleep, int, 0644);
60 MODULE_PARM_DESC(dvb_powerdown_on_sleep, "0: do not power down, 1: turn LNB voltage off on sleep (default)");
61
62 #define dprintk if (dvb_frontend_debug) printk
63
64 #define FESTATE_IDLE 1
65 #define FESTATE_RETUNE 2
66 #define FESTATE_TUNING_FAST 4
67 #define FESTATE_TUNING_SLOW 8
68 #define FESTATE_TUNED 16
69 #define FESTATE_ZIGZAG_FAST 32
70 #define FESTATE_ZIGZAG_SLOW 64
71 #define FESTATE_DISEQC 128
72 #define FESTATE_WAITFORLOCK (FESTATE_TUNING_FAST | FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW | FESTATE_DISEQC)
73 #define FESTATE_SEARCHING_FAST (FESTATE_TUNING_FAST | FESTATE_ZIGZAG_FAST)
74 #define FESTATE_SEARCHING_SLOW (FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_SLOW)
75 #define FESTATE_LOSTLOCK (FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW)
76
77 #define FE_ALGO_HW              1
78 /*
79  * FESTATE_IDLE. No tuning parameters have been supplied and the loop is idling.
80  * FESTATE_RETUNE. Parameters have been supplied, but we have not yet performed the first tune.
81  * FESTATE_TUNING_FAST. Tuning parameters have been supplied and fast zigzag scan is in progress.
82  * FESTATE_TUNING_SLOW. Tuning parameters have been supplied. Fast zigzag failed, so we're trying again, but slower.
83  * FESTATE_TUNED. The frontend has successfully locked on.
84  * FESTATE_ZIGZAG_FAST. The lock has been lost, and a fast zigzag has been initiated to try and regain it.
85  * FESTATE_ZIGZAG_SLOW. The lock has been lost. Fast zigzag has been failed, so we're trying again, but slower.
86  * FESTATE_DISEQC. A DISEQC command has just been issued.
87  * FESTATE_WAITFORLOCK. When we're waiting for a lock.
88  * FESTATE_SEARCHING_FAST. When we're searching for a signal using a fast zigzag scan.
89  * FESTATE_SEARCHING_SLOW. When we're searching for a signal using a slow zigzag scan.
90  * FESTATE_LOSTLOCK. When the lock has been lost, and we're searching it again.
91  */
92
93 static DEFINE_MUTEX(frontend_mutex);
94
95 struct dvb_frontend_private {
96
97         /* thread/frontend values */
98         struct dvb_device *dvbdev;
99         struct dvb_frontend_parameters parameters;
100         struct dvb_fe_events events;
101         struct semaphore sem;
102         struct list_head list_head;
103         wait_queue_head_t wait_queue;
104         struct task_struct *thread;
105         unsigned long release_jiffies;
106         unsigned int exit;
107         unsigned int wakeup;
108         fe_status_t status;
109         unsigned long tune_mode_flags;
110         unsigned int delay;
111         unsigned int reinitialise;
112         int tone;
113         int voltage;
114
115         /* swzigzag values */
116         unsigned int state;
117         unsigned int bending;
118         int lnb_drift;
119         unsigned int inversion;
120         unsigned int auto_step;
121         unsigned int auto_sub_step;
122         unsigned int started_auto_step;
123         unsigned int min_delay;
124         unsigned int max_drift;
125         unsigned int step_size;
126         int quality;
127         unsigned int check_wrapped;
128 };
129
130 static void dvb_frontend_wakeup(struct dvb_frontend *fe);
131
132 static void dvb_frontend_add_event(struct dvb_frontend *fe, fe_status_t status)
133 {
134         struct dvb_frontend_private *fepriv = fe->frontend_priv;
135         struct dvb_fe_events *events = &fepriv->events;
136         struct dvb_frontend_event *e;
137         int wp;
138
139         dprintk ("%s\n", __FUNCTION__);
140
141         if (down_interruptible (&events->sem))
142                 return;
143
144         wp = (events->eventw + 1) % MAX_EVENT;
145
146         if (wp == events->eventr) {
147                 events->overflow = 1;
148                 events->eventr = (events->eventr + 1) % MAX_EVENT;
149         }
150
151         e = &events->events[events->eventw];
152
153         memcpy (&e->parameters, &fepriv->parameters,
154                 sizeof (struct dvb_frontend_parameters));
155
156         if (status & FE_HAS_LOCK)
157                 if (fe->ops.get_frontend)
158                         fe->ops.get_frontend(fe, &e->parameters);
159
160         events->eventw = wp;
161
162         up (&events->sem);
163
164         e->status = status;
165
166         wake_up_interruptible (&events->wait_queue);
167 }
168
169 static int dvb_frontend_get_event(struct dvb_frontend *fe,
170                             struct dvb_frontend_event *event, int flags)
171 {
172         struct dvb_frontend_private *fepriv = fe->frontend_priv;
173         struct dvb_fe_events *events = &fepriv->events;
174
175         dprintk ("%s\n", __FUNCTION__);
176
177         if (events->overflow) {
178                 events->overflow = 0;
179                 return -EOVERFLOW;
180         }
181
182         if (events->eventw == events->eventr) {
183                 int ret;
184
185                 if (flags & O_NONBLOCK)
186                         return -EWOULDBLOCK;
187
188                 up(&fepriv->sem);
189
190                 ret = wait_event_interruptible (events->wait_queue,
191                                                 events->eventw != events->eventr);
192
193                 if (down_interruptible (&fepriv->sem))
194                         return -ERESTARTSYS;
195
196                 if (ret < 0)
197                         return ret;
198         }
199
200         if (down_interruptible (&events->sem))
201                 return -ERESTARTSYS;
202
203         memcpy (event, &events->events[events->eventr],
204                 sizeof(struct dvb_frontend_event));
205
206         events->eventr = (events->eventr + 1) % MAX_EVENT;
207
208         up (&events->sem);
209
210         return 0;
211 }
212
213 static void dvb_frontend_init(struct dvb_frontend *fe)
214 {
215         dprintk ("DVB: initialising frontend %i (%s)...\n",
216                  fe->dvb->num,
217                  fe->ops.info.name);
218
219         if (fe->ops.init)
220                 fe->ops.init(fe);
221         if (fe->ops.tuner_ops.init) {
222                 fe->ops.tuner_ops.init(fe);
223                 if (fe->ops.i2c_gate_ctrl)
224                         fe->ops.i2c_gate_ctrl(fe, 0);
225         }
226 }
227
228 void dvb_frontend_reinitialise(struct dvb_frontend *fe)
229 {
230         struct dvb_frontend_private *fepriv = fe->frontend_priv;
231
232         fepriv->reinitialise = 1;
233         dvb_frontend_wakeup(fe);
234 }
235 EXPORT_SYMBOL(dvb_frontend_reinitialise);
236
237 static void dvb_frontend_swzigzag_update_delay(struct dvb_frontend_private *fepriv, int locked)
238 {
239         int q2;
240
241         dprintk ("%s\n", __FUNCTION__);
242
243         if (locked)
244                 (fepriv->quality) = (fepriv->quality * 220 + 36*256) / 256;
245         else
246                 (fepriv->quality) = (fepriv->quality * 220 + 0) / 256;
247
248         q2 = fepriv->quality - 128;
249         q2 *= q2;
250
251         fepriv->delay = fepriv->min_delay + q2 * HZ / (128*128);
252 }
253
254 /**
255  * Performs automatic twiddling of frontend parameters.
256  *
257  * @param fe The frontend concerned.
258  * @param check_wrapped Checks if an iteration has completed. DO NOT SET ON THE FIRST ATTEMPT
259  * @returns Number of complete iterations that have been performed.
260  */
261 static int dvb_frontend_swzigzag_autotune(struct dvb_frontend *fe, int check_wrapped)
262 {
263         int autoinversion;
264         int ready = 0;
265         struct dvb_frontend_private *fepriv = fe->frontend_priv;
266         int original_inversion = fepriv->parameters.inversion;
267         u32 original_frequency = fepriv->parameters.frequency;
268
269         /* are we using autoinversion? */
270         autoinversion = ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) &&
271                          (fepriv->parameters.inversion == INVERSION_AUTO));
272
273         /* setup parameters correctly */
274         while(!ready) {
275                 /* calculate the lnb_drift */
276                 fepriv->lnb_drift = fepriv->auto_step * fepriv->step_size;
277
278                 /* wrap the auto_step if we've exceeded the maximum drift */
279                 if (fepriv->lnb_drift > fepriv->max_drift) {
280                         fepriv->auto_step = 0;
281                         fepriv->auto_sub_step = 0;
282                         fepriv->lnb_drift = 0;
283                 }
284
285                 /* perform inversion and +/- zigzag */
286                 switch(fepriv->auto_sub_step) {
287                 case 0:
288                         /* try with the current inversion and current drift setting */
289                         ready = 1;
290                         break;
291
292                 case 1:
293                         if (!autoinversion) break;
294
295                         fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF;
296                         ready = 1;
297                         break;
298
299                 case 2:
300                         if (fepriv->lnb_drift == 0) break;
301
302                         fepriv->lnb_drift = -fepriv->lnb_drift;
303                         ready = 1;
304                         break;
305
306                 case 3:
307                         if (fepriv->lnb_drift == 0) break;
308                         if (!autoinversion) break;
309
310                         fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF;
311                         fepriv->lnb_drift = -fepriv->lnb_drift;
312                         ready = 1;
313                         break;
314
315                 default:
316                         fepriv->auto_step++;
317                         fepriv->auto_sub_step = -1; /* it'll be incremented to 0 in a moment */
318                         break;
319                 }
320
321                 if (!ready) fepriv->auto_sub_step++;
322         }
323
324         /* if this attempt would hit where we started, indicate a complete
325          * iteration has occurred */
326         if ((fepriv->auto_step == fepriv->started_auto_step) &&
327             (fepriv->auto_sub_step == 0) && check_wrapped) {
328                 return 1;
329         }
330
331         dprintk("%s: drift:%i inversion:%i auto_step:%i "
332                 "auto_sub_step:%i started_auto_step:%i\n",
333                 __FUNCTION__, fepriv->lnb_drift, fepriv->inversion,
334                 fepriv->auto_step, fepriv->auto_sub_step, fepriv->started_auto_step);
335
336         /* set the frontend itself */
337         fepriv->parameters.frequency += fepriv->lnb_drift;
338         if (autoinversion)
339                 fepriv->parameters.inversion = fepriv->inversion;
340         if (fe->ops.set_frontend)
341                 fe->ops.set_frontend(fe, &fepriv->parameters);
342
343         fepriv->parameters.frequency = original_frequency;
344         fepriv->parameters.inversion = original_inversion;
345
346         fepriv->auto_sub_step++;
347         return 0;
348 }
349
350 static void dvb_frontend_swzigzag(struct dvb_frontend *fe)
351 {
352         fe_status_t s = 0;
353         struct dvb_frontend_private *fepriv = fe->frontend_priv;
354
355         /* if we've got no parameters, just keep idling */
356         if (fepriv->state & FESTATE_IDLE) {
357                 fepriv->delay = 3*HZ;
358                 fepriv->quality = 0;
359                 return;
360         }
361
362         /* in SCAN mode, we just set the frontend when asked and leave it alone */
363         if (fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT) {
364                 if (fepriv->state & FESTATE_RETUNE) {
365                         if (fe->ops.set_frontend)
366                                 fe->ops.set_frontend(fe, &fepriv->parameters);
367                         fepriv->state = FESTATE_TUNED;
368                 }
369                 fepriv->delay = 3*HZ;
370                 fepriv->quality = 0;
371                 return;
372         }
373
374         /* get the frontend status */
375         if (fepriv->state & FESTATE_RETUNE) {
376                 s = 0;
377         } else {
378                 if (fe->ops.read_status)
379                         fe->ops.read_status(fe, &s);
380                 if (s != fepriv->status) {
381                         dvb_frontend_add_event(fe, s);
382                         fepriv->status = s;
383                 }
384         }
385
386         /* if we're not tuned, and we have a lock, move to the TUNED state */
387         if ((fepriv->state & FESTATE_WAITFORLOCK) && (s & FE_HAS_LOCK)) {
388                 dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
389                 fepriv->state = FESTATE_TUNED;
390
391                 /* if we're tuned, then we have determined the correct inversion */
392                 if ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) &&
393                     (fepriv->parameters.inversion == INVERSION_AUTO)) {
394                         fepriv->parameters.inversion = fepriv->inversion;
395                 }
396                 return;
397         }
398
399         /* if we are tuned already, check we're still locked */
400         if (fepriv->state & FESTATE_TUNED) {
401                 dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
402
403                 /* we're tuned, and the lock is still good... */
404                 if (s & FE_HAS_LOCK) {
405                         return;
406                 } else { /* if we _WERE_ tuned, but now don't have a lock */
407                         fepriv->state = FESTATE_ZIGZAG_FAST;
408                         fepriv->started_auto_step = fepriv->auto_step;
409                         fepriv->check_wrapped = 0;
410                 }
411         }
412
413         /* don't actually do anything if we're in the LOSTLOCK state,
414          * the frontend is set to FE_CAN_RECOVER, and the max_drift is 0 */
415         if ((fepriv->state & FESTATE_LOSTLOCK) &&
416             (fe->ops.info.caps & FE_CAN_RECOVER) && (fepriv->max_drift == 0)) {
417                 dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
418                 return;
419         }
420
421         /* don't do anything if we're in the DISEQC state, since this
422          * might be someone with a motorized dish controlled by DISEQC.
423          * If its actually a re-tune, there will be a SET_FRONTEND soon enough. */
424         if (fepriv->state & FESTATE_DISEQC) {
425                 dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
426                 return;
427         }
428
429         /* if we're in the RETUNE state, set everything up for a brand
430          * new scan, keeping the current inversion setting, as the next
431          * tune is _very_ likely to require the same */
432         if (fepriv->state & FESTATE_RETUNE) {
433                 fepriv->lnb_drift = 0;
434                 fepriv->auto_step = 0;
435                 fepriv->auto_sub_step = 0;
436                 fepriv->started_auto_step = 0;
437                 fepriv->check_wrapped = 0;
438         }
439
440         /* fast zigzag. */
441         if ((fepriv->state & FESTATE_SEARCHING_FAST) || (fepriv->state & FESTATE_RETUNE)) {
442                 fepriv->delay = fepriv->min_delay;
443
444                 /* peform a tune */
445                 if (dvb_frontend_swzigzag_autotune(fe, fepriv->check_wrapped)) {
446                         /* OK, if we've run out of trials at the fast speed.
447                          * Drop back to slow for the _next_ attempt */
448                         fepriv->state = FESTATE_SEARCHING_SLOW;
449                         fepriv->started_auto_step = fepriv->auto_step;
450                         return;
451                 }
452                 fepriv->check_wrapped = 1;
453
454                 /* if we've just retuned, enter the ZIGZAG_FAST state.
455                  * This ensures we cannot return from an
456                  * FE_SET_FRONTEND ioctl before the first frontend tune
457                  * occurs */
458                 if (fepriv->state & FESTATE_RETUNE) {
459                         fepriv->state = FESTATE_TUNING_FAST;
460                 }
461         }
462
463         /* slow zigzag */
464         if (fepriv->state & FESTATE_SEARCHING_SLOW) {
465                 dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK);
466
467                 /* Note: don't bother checking for wrapping; we stay in this
468                  * state until we get a lock */
469                 dvb_frontend_swzigzag_autotune(fe, 0);
470         }
471 }
472
473 static int dvb_frontend_is_exiting(struct dvb_frontend *fe)
474 {
475         struct dvb_frontend_private *fepriv = fe->frontend_priv;
476
477         if (fepriv->exit)
478                 return 1;
479
480         if (fepriv->dvbdev->writers == 1)
481                 if (time_after(jiffies, fepriv->release_jiffies +
482                                   dvb_shutdown_timeout * HZ))
483                         return 1;
484
485         return 0;
486 }
487
488 static int dvb_frontend_should_wakeup(struct dvb_frontend *fe)
489 {
490         struct dvb_frontend_private *fepriv = fe->frontend_priv;
491
492         if (fepriv->wakeup) {
493                 fepriv->wakeup = 0;
494                 return 1;
495         }
496         return dvb_frontend_is_exiting(fe);
497 }
498
499 static void dvb_frontend_wakeup(struct dvb_frontend *fe)
500 {
501         struct dvb_frontend_private *fepriv = fe->frontend_priv;
502
503         fepriv->wakeup = 1;
504         wake_up_interruptible(&fepriv->wait_queue);
505 }
506
507 static int dvb_frontend_thread(void *data)
508 {
509         struct dvb_frontend *fe = data;
510         struct dvb_frontend_private *fepriv = fe->frontend_priv;
511         unsigned long timeout;
512         fe_status_t s;
513         struct dvb_frontend_parameters *params;
514
515         dprintk("%s\n", __FUNCTION__);
516
517         fepriv->check_wrapped = 0;
518         fepriv->quality = 0;
519         fepriv->delay = 3*HZ;
520         fepriv->status = 0;
521         fepriv->wakeup = 0;
522         fepriv->reinitialise = 0;
523
524         dvb_frontend_init(fe);
525
526         set_freezable();
527         while (1) {
528                 up(&fepriv->sem);           /* is locked when we enter the thread... */
529 restart:
530                 timeout = wait_event_interruptible_timeout(fepriv->wait_queue,
531                         dvb_frontend_should_wakeup(fe) || kthread_should_stop(),
532                         fepriv->delay);
533
534                 if (kthread_should_stop() || dvb_frontend_is_exiting(fe)) {
535                         /* got signal or quitting */
536                         break;
537                 }
538
539                 if (try_to_freeze())
540                         goto restart;
541
542                 if (down_interruptible(&fepriv->sem))
543                         break;
544
545                 if (fepriv->reinitialise) {
546                         dvb_frontend_init(fe);
547                         if (fepriv->tone != -1) {
548                                 fe->ops.set_tone(fe, fepriv->tone);
549                         }
550                         if (fepriv->voltage != -1) {
551                                 fe->ops.set_voltage(fe, fepriv->voltage);
552                         }
553                         fepriv->reinitialise = 0;
554                 }
555
556                 /* do an iteration of the tuning loop */
557                 if (fe->ops.get_frontend_algo) {
558                         if (fe->ops.get_frontend_algo(fe) == FE_ALGO_HW) {
559                                 /* have we been asked to retune? */
560                                 params = NULL;
561                                 if (fepriv->state & FESTATE_RETUNE) {
562                                         params = &fepriv->parameters;
563                                         fepriv->state = FESTATE_TUNED;
564                                 }
565
566                                 fe->ops.tune(fe, params, fepriv->tune_mode_flags, &fepriv->delay, &s);
567                                 if (s != fepriv->status) {
568                                         dvb_frontend_add_event(fe, s);
569                                         fepriv->status = s;
570                                 }
571                         } else
572                                 dvb_frontend_swzigzag(fe);
573                 } else
574                         dvb_frontend_swzigzag(fe);
575         }
576
577         if (dvb_shutdown_timeout) {
578                 if (dvb_powerdown_on_sleep)
579                         if (fe->ops.set_voltage)
580                                 fe->ops.set_voltage(fe, SEC_VOLTAGE_OFF);
581                 if (fe->ops.tuner_ops.sleep) {
582                         fe->ops.tuner_ops.sleep(fe);
583                         if (fe->ops.i2c_gate_ctrl)
584                                 fe->ops.i2c_gate_ctrl(fe, 0);
585                 }
586                 if (fe->ops.sleep)
587                         fe->ops.sleep(fe);
588         }
589
590         fepriv->thread = NULL;
591         mb();
592
593         dvb_frontend_wakeup(fe);
594         return 0;
595 }
596
597 static void dvb_frontend_stop(struct dvb_frontend *fe)
598 {
599         struct dvb_frontend_private *fepriv = fe->frontend_priv;
600
601         dprintk ("%s\n", __FUNCTION__);
602
603         fepriv->exit = 1;
604         mb();
605
606         if (!fepriv->thread)
607                 return;
608
609         kthread_stop(fepriv->thread);
610
611         init_MUTEX (&fepriv->sem);
612         fepriv->state = FESTATE_IDLE;
613
614         /* paranoia check in case a signal arrived */
615         if (fepriv->thread)
616                 printk("dvb_frontend_stop: warning: thread %p won't exit\n",
617                                 fepriv->thread);
618 }
619
620 s32 timeval_usec_diff(struct timeval lasttime, struct timeval curtime)
621 {
622         return ((curtime.tv_usec < lasttime.tv_usec) ?
623                 1000000 - lasttime.tv_usec + curtime.tv_usec :
624                 curtime.tv_usec - lasttime.tv_usec);
625 }
626 EXPORT_SYMBOL(timeval_usec_diff);
627
628 static inline void timeval_usec_add(struct timeval *curtime, u32 add_usec)
629 {
630         curtime->tv_usec += add_usec;
631         if (curtime->tv_usec >= 1000000) {
632                 curtime->tv_usec -= 1000000;
633                 curtime->tv_sec++;
634         }
635 }
636
637 /*
638  * Sleep until gettimeofday() > waketime + add_usec
639  * This needs to be as precise as possible, but as the delay is
640  * usually between 2ms and 32ms, it is done using a scheduled msleep
641  * followed by usleep (normally a busy-wait loop) for the remainder
642  */
643 void dvb_frontend_sleep_until(struct timeval *waketime, u32 add_usec)
644 {
645         struct timeval lasttime;
646         s32 delta, newdelta;
647
648         timeval_usec_add(waketime, add_usec);
649
650         do_gettimeofday(&lasttime);
651         delta = timeval_usec_diff(lasttime, *waketime);
652         if (delta > 2500) {
653                 msleep((delta - 1500) / 1000);
654                 do_gettimeofday(&lasttime);
655                 newdelta = timeval_usec_diff(lasttime, *waketime);
656                 delta = (newdelta > delta) ? 0 : newdelta;
657         }
658         if (delta > 0)
659                 udelay(delta);
660 }
661 EXPORT_SYMBOL(dvb_frontend_sleep_until);
662
663 static int dvb_frontend_start(struct dvb_frontend *fe)
664 {
665         int ret;
666         struct dvb_frontend_private *fepriv = fe->frontend_priv;
667         struct task_struct *fe_thread;
668
669         dprintk ("%s\n", __FUNCTION__);
670
671         if (fepriv->thread) {
672                 if (!fepriv->exit)
673                         return 0;
674                 else
675                         dvb_frontend_stop (fe);
676         }
677
678         if (signal_pending(current))
679                 return -EINTR;
680         if (down_interruptible (&fepriv->sem))
681                 return -EINTR;
682
683         fepriv->state = FESTATE_IDLE;
684         fepriv->exit = 0;
685         fepriv->thread = NULL;
686         mb();
687
688         fe_thread = kthread_run(dvb_frontend_thread, fe,
689                 "kdvb-fe-%i", fe->dvb->num);
690         if (IS_ERR(fe_thread)) {
691                 ret = PTR_ERR(fe_thread);
692                 printk("dvb_frontend_start: failed to start kthread (%d)\n", ret);
693                 up(&fepriv->sem);
694                 return ret;
695         }
696         fepriv->thread = fe_thread;
697         return 0;
698 }
699
700 static int dvb_frontend_check_parameters(struct dvb_frontend *fe,
701                                 struct dvb_frontend_parameters *parms)
702 {
703         /* range check: frequency */
704         if ((fe->ops.info.frequency_min &&
705              parms->frequency < fe->ops.info.frequency_min) ||
706             (fe->ops.info.frequency_max &&
707              parms->frequency > fe->ops.info.frequency_max)) {
708                 printk(KERN_WARNING "DVB: frontend %u frequency %u out of range (%u..%u)\n",
709                        fe->dvb->num, parms->frequency,
710                        fe->ops.info.frequency_min, fe->ops.info.frequency_max);
711                 return -EINVAL;
712         }
713
714         /* range check: symbol rate */
715         if (fe->ops.info.type == FE_QPSK) {
716                 if ((fe->ops.info.symbol_rate_min &&
717                      parms->u.qpsk.symbol_rate < fe->ops.info.symbol_rate_min) ||
718                     (fe->ops.info.symbol_rate_max &&
719                      parms->u.qpsk.symbol_rate > fe->ops.info.symbol_rate_max)) {
720                         printk(KERN_WARNING "DVB: frontend %u symbol rate %u out of range (%u..%u)\n",
721                                fe->dvb->num, parms->u.qpsk.symbol_rate,
722                                fe->ops.info.symbol_rate_min, fe->ops.info.symbol_rate_max);
723                         return -EINVAL;
724                 }
725
726         } else if (fe->ops.info.type == FE_QAM) {
727                 if ((fe->ops.info.symbol_rate_min &&
728                      parms->u.qam.symbol_rate < fe->ops.info.symbol_rate_min) ||
729                     (fe->ops.info.symbol_rate_max &&
730                      parms->u.qam.symbol_rate > fe->ops.info.symbol_rate_max)) {
731                         printk(KERN_WARNING "DVB: frontend %u symbol rate %u out of range (%u..%u)\n",
732                                fe->dvb->num, parms->u.qam.symbol_rate,
733                                fe->ops.info.symbol_rate_min, fe->ops.info.symbol_rate_max);
734                         return -EINVAL;
735                 }
736         }
737
738         return 0;
739 }
740
741 static int dvb_frontend_ioctl(struct inode *inode, struct file *file,
742                         unsigned int cmd, void *parg)
743 {
744         struct dvb_device *dvbdev = file->private_data;
745         struct dvb_frontend *fe = dvbdev->priv;
746         struct dvb_frontend_private *fepriv = fe->frontend_priv;
747         int err = -EOPNOTSUPP;
748
749         dprintk ("%s\n", __FUNCTION__);
750
751         if (!fe || fepriv->exit)
752                 return -ENODEV;
753
754         if ((file->f_flags & O_ACCMODE) == O_RDONLY &&
755             (_IOC_DIR(cmd) != _IOC_READ || cmd == FE_GET_EVENT ||
756              cmd == FE_DISEQC_RECV_SLAVE_REPLY))
757                 return -EPERM;
758
759         if (down_interruptible (&fepriv->sem))
760                 return -ERESTARTSYS;
761
762         switch (cmd) {
763         case FE_GET_INFO: {
764                 struct dvb_frontend_info* info = parg;
765                 memcpy(info, &fe->ops.info, sizeof(struct dvb_frontend_info));
766
767                 /* Force the CAN_INVERSION_AUTO bit on. If the frontend doesn't
768                  * do it, it is done for it. */
769                 info->caps |= FE_CAN_INVERSION_AUTO;
770                 err = 0;
771                 break;
772         }
773
774         case FE_READ_STATUS: {
775                 fe_status_t* status = parg;
776
777                 /* if retune was requested but hasn't occured yet, prevent
778                  * that user get signal state from previous tuning */
779                 if(fepriv->state == FESTATE_RETUNE) {
780                         err=0;
781                         *status = 0;
782                         break;
783                 }
784
785                 if (fe->ops.read_status)
786                         err = fe->ops.read_status(fe, status);
787                 break;
788         }
789         case FE_READ_BER:
790                 if (fe->ops.read_ber)
791                         err = fe->ops.read_ber(fe, (__u32*) parg);
792                 break;
793
794         case FE_READ_SIGNAL_STRENGTH:
795                 if (fe->ops.read_signal_strength)
796                         err = fe->ops.read_signal_strength(fe, (__u16*) parg);
797                 break;
798
799         case FE_READ_SNR:
800                 if (fe->ops.read_snr)
801                         err = fe->ops.read_snr(fe, (__u16*) parg);
802                 break;
803
804         case FE_READ_UNCORRECTED_BLOCKS:
805                 if (fe->ops.read_ucblocks)
806                         err = fe->ops.read_ucblocks(fe, (__u32*) parg);
807                 break;
808
809
810         case FE_DISEQC_RESET_OVERLOAD:
811                 if (fe->ops.diseqc_reset_overload) {
812                         err = fe->ops.diseqc_reset_overload(fe);
813                         fepriv->state = FESTATE_DISEQC;
814                         fepriv->status = 0;
815                 }
816                 break;
817
818         case FE_DISEQC_SEND_MASTER_CMD:
819                 if (fe->ops.diseqc_send_master_cmd) {
820                         err = fe->ops.diseqc_send_master_cmd(fe, (struct dvb_diseqc_master_cmd*) parg);
821                         fepriv->state = FESTATE_DISEQC;
822                         fepriv->status = 0;
823                 }
824                 break;
825
826         case FE_DISEQC_SEND_BURST:
827                 if (fe->ops.diseqc_send_burst) {
828                         err = fe->ops.diseqc_send_burst(fe, (fe_sec_mini_cmd_t) parg);
829                         fepriv->state = FESTATE_DISEQC;
830                         fepriv->status = 0;
831                 }
832                 break;
833
834         case FE_SET_TONE:
835                 if (fe->ops.set_tone) {
836                         err = fe->ops.set_tone(fe, (fe_sec_tone_mode_t) parg);
837                         fepriv->tone = (fe_sec_tone_mode_t) parg;
838                         fepriv->state = FESTATE_DISEQC;
839                         fepriv->status = 0;
840                 }
841                 break;
842
843         case FE_SET_VOLTAGE:
844                 if (fe->ops.set_voltage) {
845                         err = fe->ops.set_voltage(fe, (fe_sec_voltage_t) parg);
846                         fepriv->voltage = (fe_sec_voltage_t) parg;
847                         fepriv->state = FESTATE_DISEQC;
848                         fepriv->status = 0;
849                 }
850                 break;
851
852         case FE_DISHNETWORK_SEND_LEGACY_CMD:
853                 if (fe->ops.dishnetwork_send_legacy_command) {
854                         err = fe->ops.dishnetwork_send_legacy_command(fe, (unsigned long) parg);
855                         fepriv->state = FESTATE_DISEQC;
856                         fepriv->status = 0;
857                 } else if (fe->ops.set_voltage) {
858                         /*
859                          * NOTE: This is a fallback condition.  Some frontends
860                          * (stv0299 for instance) take longer than 8msec to
861                          * respond to a set_voltage command.  Those switches
862                          * need custom routines to switch properly.  For all
863                          * other frontends, the following shoule work ok.
864                          * Dish network legacy switches (as used by Dish500)
865                          * are controlled by sending 9-bit command words
866                          * spaced 8msec apart.
867                          * the actual command word is switch/port dependant
868                          * so it is up to the userspace application to send
869                          * the right command.
870                          * The command must always start with a '0' after
871                          * initialization, so parg is 8 bits and does not
872                          * include the initialization or start bit
873                          */
874                         unsigned long cmd = ((unsigned long) parg) << 1;
875                         struct timeval nexttime;
876                         struct timeval tv[10];
877                         int i;
878                         u8 last = 1;
879                         if (dvb_frontend_debug)
880                                 printk("%s switch command: 0x%04lx\n", __FUNCTION__, cmd);
881                         do_gettimeofday(&nexttime);
882                         if (dvb_frontend_debug)
883                                 memcpy(&tv[0], &nexttime, sizeof(struct timeval));
884                         /* before sending a command, initialize by sending
885                          * a 32ms 18V to the switch
886                          */
887                         fe->ops.set_voltage(fe, SEC_VOLTAGE_18);
888                         dvb_frontend_sleep_until(&nexttime, 32000);
889
890                         for (i = 0; i < 9; i++) {
891                                 if (dvb_frontend_debug)
892                                         do_gettimeofday(&tv[i + 1]);
893                                 if ((cmd & 0x01) != last) {
894                                         /* set voltage to (last ? 13V : 18V) */
895                                         fe->ops.set_voltage(fe, (last) ? SEC_VOLTAGE_13 : SEC_VOLTAGE_18);
896                                         last = (last) ? 0 : 1;
897                                 }
898                                 cmd = cmd >> 1;
899                                 if (i != 8)
900                                         dvb_frontend_sleep_until(&nexttime, 8000);
901                         }
902                         if (dvb_frontend_debug) {
903                                 printk("%s(%d): switch delay (should be 32k followed by all 8k\n",
904                                         __FUNCTION__, fe->dvb->num);
905                                 for (i = 1; i < 10; i++)
906                                         printk("%d: %d\n", i, timeval_usec_diff(tv[i-1] , tv[i]));
907                         }
908                         err = 0;
909                         fepriv->state = FESTATE_DISEQC;
910                         fepriv->status = 0;
911                 }
912                 break;
913
914         case FE_DISEQC_RECV_SLAVE_REPLY:
915                 if (fe->ops.diseqc_recv_slave_reply)
916                         err = fe->ops.diseqc_recv_slave_reply(fe, (struct dvb_diseqc_slave_reply*) parg);
917                 break;
918
919         case FE_ENABLE_HIGH_LNB_VOLTAGE:
920                 if (fe->ops.enable_high_lnb_voltage)
921                         err = fe->ops.enable_high_lnb_voltage(fe, (long) parg);
922                 break;
923
924         case FE_SET_FRONTEND: {
925                 struct dvb_frontend_tune_settings fetunesettings;
926
927                 if (dvb_frontend_check_parameters(fe, parg) < 0) {
928                         err = -EINVAL;
929                         break;
930                 }
931
932                 memcpy (&fepriv->parameters, parg,
933                         sizeof (struct dvb_frontend_parameters));
934
935                 memset(&fetunesettings, 0, sizeof(struct dvb_frontend_tune_settings));
936                 memcpy(&fetunesettings.parameters, parg,
937                        sizeof (struct dvb_frontend_parameters));
938
939                 /* force auto frequency inversion if requested */
940                 if (dvb_force_auto_inversion) {
941                         fepriv->parameters.inversion = INVERSION_AUTO;
942                         fetunesettings.parameters.inversion = INVERSION_AUTO;
943                 }
944                 if (fe->ops.info.type == FE_OFDM) {
945                         /* without hierarchical coding code_rate_LP is irrelevant,
946                          * so we tolerate the otherwise invalid FEC_NONE setting */
947                         if (fepriv->parameters.u.ofdm.hierarchy_information == HIERARCHY_NONE &&
948                             fepriv->parameters.u.ofdm.code_rate_LP == FEC_NONE)
949                                 fepriv->parameters.u.ofdm.code_rate_LP = FEC_AUTO;
950                 }
951
952                 /* get frontend-specific tuning settings */
953                 if (fe->ops.get_tune_settings && (fe->ops.get_tune_settings(fe, &fetunesettings) == 0)) {
954                         fepriv->min_delay = (fetunesettings.min_delay_ms * HZ) / 1000;
955                         fepriv->max_drift = fetunesettings.max_drift;
956                         fepriv->step_size = fetunesettings.step_size;
957                 } else {
958                         /* default values */
959                         switch(fe->ops.info.type) {
960                         case FE_QPSK:
961                                 fepriv->min_delay = HZ/20;
962                                 fepriv->step_size = fepriv->parameters.u.qpsk.symbol_rate / 16000;
963                                 fepriv->max_drift = fepriv->parameters.u.qpsk.symbol_rate / 2000;
964                                 break;
965
966                         case FE_QAM:
967                                 fepriv->min_delay = HZ/20;
968                                 fepriv->step_size = 0; /* no zigzag */
969                                 fepriv->max_drift = 0;
970                                 break;
971
972                         case FE_OFDM:
973                                 fepriv->min_delay = HZ/20;
974                                 fepriv->step_size = fe->ops.info.frequency_stepsize * 2;
975                                 fepriv->max_drift = (fe->ops.info.frequency_stepsize * 2) + 1;
976                                 break;
977                         case FE_ATSC:
978                                 fepriv->min_delay = HZ/20;
979                                 fepriv->step_size = 0;
980                                 fepriv->max_drift = 0;
981                                 break;
982                         }
983                 }
984                 if (dvb_override_tune_delay > 0)
985                         fepriv->min_delay = (dvb_override_tune_delay * HZ) / 1000;
986
987                 fepriv->state = FESTATE_RETUNE;
988                 dvb_frontend_wakeup(fe);
989                 dvb_frontend_add_event(fe, 0);
990                 fepriv->status = 0;
991                 err = 0;
992                 break;
993         }
994
995         case FE_GET_EVENT:
996                 err = dvb_frontend_get_event (fe, parg, file->f_flags);
997                 break;
998
999         case FE_GET_FRONTEND:
1000                 if (fe->ops.get_frontend) {
1001                         memcpy (parg, &fepriv->parameters, sizeof (struct dvb_frontend_parameters));
1002                         err = fe->ops.get_frontend(fe, (struct dvb_frontend_parameters*) parg);
1003                 }
1004                 break;
1005
1006         case FE_SET_FRONTEND_TUNE_MODE:
1007                 fepriv->tune_mode_flags = (unsigned long) parg;
1008                 err = 0;
1009                 break;
1010         };
1011
1012         up (&fepriv->sem);
1013         return err;
1014 }
1015
1016 static unsigned int dvb_frontend_poll(struct file *file, struct poll_table_struct *wait)
1017 {
1018         struct dvb_device *dvbdev = file->private_data;
1019         struct dvb_frontend *fe = dvbdev->priv;
1020         struct dvb_frontend_private *fepriv = fe->frontend_priv;
1021
1022         dprintk ("%s\n", __FUNCTION__);
1023
1024         poll_wait (file, &fepriv->events.wait_queue, wait);
1025
1026         if (fepriv->events.eventw != fepriv->events.eventr)
1027                 return (POLLIN | POLLRDNORM | POLLPRI);
1028
1029         return 0;
1030 }
1031
1032 static int dvb_frontend_open(struct inode *inode, struct file *file)
1033 {
1034         struct dvb_device *dvbdev = file->private_data;
1035         struct dvb_frontend *fe = dvbdev->priv;
1036         struct dvb_frontend_private *fepriv = fe->frontend_priv;
1037         int ret;
1038
1039         dprintk ("%s\n", __FUNCTION__);
1040
1041         if ((ret = dvb_generic_open (inode, file)) < 0)
1042                 return ret;
1043
1044         if (fe->ops.ts_bus_ctrl) {
1045                 if ((ret = fe->ops.ts_bus_ctrl (fe, 1)) < 0) {
1046                         dvb_generic_release (inode, file);
1047                         return ret;
1048                 }
1049         }
1050
1051         if ((file->f_flags & O_ACCMODE) != O_RDONLY) {
1052
1053                 /* normal tune mode when opened R/W */
1054                 fepriv->tune_mode_flags &= ~FE_TUNE_MODE_ONESHOT;
1055                 fepriv->tone = -1;
1056                 fepriv->voltage = -1;
1057
1058                 ret = dvb_frontend_start (fe);
1059                 if (ret)
1060                         dvb_generic_release (inode, file);
1061
1062                 /*  empty event queue */
1063                 fepriv->events.eventr = fepriv->events.eventw = 0;
1064         }
1065
1066         return ret;
1067 }
1068
1069 static int dvb_frontend_release(struct inode *inode, struct file *file)
1070 {
1071         struct dvb_device *dvbdev = file->private_data;
1072         struct dvb_frontend *fe = dvbdev->priv;
1073         struct dvb_frontend_private *fepriv = fe->frontend_priv;
1074         int ret;
1075
1076         dprintk ("%s\n", __FUNCTION__);
1077
1078         if ((file->f_flags & O_ACCMODE) != O_RDONLY)
1079                 fepriv->release_jiffies = jiffies;
1080
1081         if (fe->ops.ts_bus_ctrl)
1082                 fe->ops.ts_bus_ctrl (fe, 0);
1083
1084         ret = dvb_generic_release (inode, file);
1085
1086         if (dvbdev->users==-1 && fepriv->exit==1) {
1087                 fops_put(file->f_op);
1088                 file->f_op = NULL;
1089                 wake_up(&dvbdev->wait_queue);
1090         }
1091         return ret;
1092 }
1093
1094 static struct file_operations dvb_frontend_fops = {
1095         .owner          = THIS_MODULE,
1096         .ioctl          = dvb_generic_ioctl,
1097         .poll           = dvb_frontend_poll,
1098         .open           = dvb_frontend_open,
1099         .release        = dvb_frontend_release
1100 };
1101
1102 int dvb_register_frontend(struct dvb_adapter* dvb,
1103                           struct dvb_frontend* fe)
1104 {
1105         struct dvb_frontend_private *fepriv;
1106         static const struct dvb_device dvbdev_template = {
1107                 .users = ~0,
1108                 .writers = 1,
1109                 .readers = (~0)-1,
1110                 .fops = &dvb_frontend_fops,
1111                 .kernel_ioctl = dvb_frontend_ioctl
1112         };
1113
1114         dprintk ("%s\n", __FUNCTION__);
1115
1116         if (mutex_lock_interruptible(&frontend_mutex))
1117                 return -ERESTARTSYS;
1118
1119         fe->frontend_priv = kzalloc(sizeof(struct dvb_frontend_private), GFP_KERNEL);
1120         if (fe->frontend_priv == NULL) {
1121                 mutex_unlock(&frontend_mutex);
1122                 return -ENOMEM;
1123         }
1124         fepriv = fe->frontend_priv;
1125
1126         init_MUTEX (&fepriv->sem);
1127         init_waitqueue_head (&fepriv->wait_queue);
1128         init_waitqueue_head (&fepriv->events.wait_queue);
1129         init_MUTEX (&fepriv->events.sem);
1130         fe->dvb = dvb;
1131         fepriv->inversion = INVERSION_OFF;
1132
1133         printk ("DVB: registering frontend %i (%s)...\n",
1134                 fe->dvb->num,
1135                 fe->ops.info.name);
1136
1137         dvb_register_device (fe->dvb, &fepriv->dvbdev, &dvbdev_template,
1138                              fe, DVB_DEVICE_FRONTEND);
1139
1140         mutex_unlock(&frontend_mutex);
1141         return 0;
1142 }
1143 EXPORT_SYMBOL(dvb_register_frontend);
1144
1145 int dvb_unregister_frontend(struct dvb_frontend* fe)
1146 {
1147         struct dvb_frontend_private *fepriv = fe->frontend_priv;
1148         dprintk ("%s\n", __FUNCTION__);
1149
1150         mutex_lock(&frontend_mutex);
1151         dvb_frontend_stop (fe);
1152         mutex_unlock(&frontend_mutex);
1153
1154         if (fepriv->dvbdev->users < -1)
1155                 wait_event(fepriv->dvbdev->wait_queue,
1156                                 fepriv->dvbdev->users==-1);
1157
1158         mutex_lock(&frontend_mutex);
1159         dvb_unregister_device (fepriv->dvbdev);
1160
1161         /* fe is invalid now */
1162         kfree(fepriv);
1163         mutex_unlock(&frontend_mutex);
1164         return 0;
1165 }
1166 EXPORT_SYMBOL(dvb_unregister_frontend);
1167
1168 #ifdef CONFIG_DVB_CORE_ATTACH
1169 void dvb_frontend_detach(struct dvb_frontend* fe)
1170 {
1171         void *ptr;
1172
1173         if (fe->ops.release_sec) {
1174                 fe->ops.release_sec(fe);
1175                 symbol_put_addr(fe->ops.release_sec);
1176         }
1177         if (fe->ops.tuner_ops.release) {
1178                 fe->ops.tuner_ops.release(fe);
1179                 symbol_put_addr(fe->ops.tuner_ops.release);
1180         }
1181         ptr = (void*)fe->ops.release;
1182         if (ptr) {
1183                 fe->ops.release(fe);
1184                 symbol_put_addr(ptr);
1185         }
1186 }
1187 #else
1188 void dvb_frontend_detach(struct dvb_frontend* fe)
1189 {
1190         if (fe->ops.release_sec)
1191                 fe->ops.release_sec(fe);
1192         if (fe->ops.tuner_ops.release)
1193                 fe->ops.tuner_ops.release(fe);
1194         if (fe->ops.release)
1195                 fe->ops.release(fe);
1196 }
1197 #endif
1198 EXPORT_SYMBOL(dvb_frontend_detach);