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