Add handy functions for handling non recurrent timeouts.
[bertos.git] / bertos / drv / timer.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2005, 2006 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000, 2008 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \brief Hardware independent timer driver (implementation)
34  *
35  * \author Bernie Innocenti <bernie@codewiz.org>
36  * \author Francesco Sacchi <batt@develer.com>
37  */
38
39 #include "timer.h"
40 #include "hw/hw_timer.h"
41
42 #include "cfg/cfg_timer.h"
43 #include "cfg/cfg_wdt.h"
44 #include "cfg/cfg_proc.h"
45 #include "cfg/cfg_signal.h"
46 #include <cfg/os.h>
47 #include <cfg/debug.h>
48 #include <cfg/module.h>
49
50 #include <cpu/attr.h>
51 #include <cpu/types.h>
52 #include <cpu/irq.h>
53 #include <cpu/power.h> // cpu_relax()
54
55 #include <kern/proc_p.h> // proc_decQuantun()
56
57 /*
58  * Include platform-specific binding code if we're hosted.
59  * Try the CPU specific one for bare-metal environments.
60  */
61 #if OS_HOSTED
62         //#include OS_CSOURCE(timer)
63         #include <emul/timer_posix.c>
64 #else
65         #ifndef WIZ_AUTOGEN
66                 #warning Deprecated: now you should include timer_<cpu> directly in the makefile. Remove this line and the following once done.
67                 #include CPU_CSOURCE(timer)
68         #endif
69 #endif
70
71 /*
72  * Sanity check for config parameters required by this module.
73  */
74 #if !defined(CONFIG_KERN) || ((CONFIG_KERN != 0) && CONFIG_KERN != 1)
75         #error CONFIG_KERN must be set to either 0 or 1 in config.h
76 #endif
77 #if !defined(CONFIG_WATCHDOG) || ((CONFIG_WATCHDOG != 0) && CONFIG_WATCHDOG != 1)
78         #error CONFIG_WATCHDOG must be set to either 0 or 1 in config.h
79 #endif
80
81 #if CONFIG_WATCHDOG
82         #include <drv/wdt.h>
83 #endif
84
85 #if defined (CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
86         #include <kern/signal.h> /* sig_wait(), sig_check() */
87         #include <kern/proc.h>   /* proc_current() */
88         #include <cfg/macros.h>  /* BV() */
89 #endif
90
91
92 /**
93  * \def CONFIG_TIMER_STROBE
94  *
95  * This is a debug facility that can be used to
96  * monitor timer interrupt activity on an external pin.
97  *
98  * To use strobes, redefine the macros TIMER_STROBE_ON,
99  * TIMER_STROBE_OFF and TIMER_STROBE_INIT and set
100  * CONFIG_TIMER_STROBE to 1.
101  */
102 #if !defined(CONFIG_TIMER_STROBE) || !CONFIG_TIMER_STROBE
103         #define TIMER_STROBE_ON    do {/*nop*/} while(0)
104         #define TIMER_STROBE_OFF   do {/*nop*/} while(0)
105         #define TIMER_STROBE_INIT  do {/*nop*/} while(0)
106 #endif
107
108
109 /// Master system clock (1 tick accuracy)
110 volatile ticks_t _clock;
111
112
113 #if CONFIG_TIMER_EVENTS
114
115 /**
116  * List of active asynchronous timers.
117  */
118 REGISTER static List timers_queue;
119
120 /**
121  * This function really does the job. It adds \a timer to \a queue.
122  * \see timer_add for details.
123  */
124 INLINE void timer_addToList(Timer *timer, List *queue)
125 {
126         /* Inserting timers twice causes mayhem. */
127         ASSERT(timer->magic != TIMER_MAGIC_ACTIVE);
128         DB(timer->magic = TIMER_MAGIC_ACTIVE;)
129
130         /*
131          * Search for the first node whose expiration time is
132          * greater than the timer we want to add.
133          */
134         Timer *node = (Timer *)LIST_HEAD(queue);
135         while (node->link.succ)
136         {
137                 /*
138                  * Stop just after the insertion point.
139                  * (this fancy compare takes care of wrap-arounds).
140                  */
141                 if (node->tick - timer->tick > 0)
142                         break;
143
144                 /* Go to next node */
145                 node = (Timer *)node->link.succ;
146         }
147
148         /* Enqueue timer request into the list */
149         INSERT_BEFORE(&timer->link, &node->link);
150 }
151
152 /**
153  * Add the specified timer to the software timer service queue.
154  * When the delay indicated by the timer expires, the timer
155  * device will execute the event associated with it.
156  *
157  * \note Interrupt safe
158  */
159 void timer_add(Timer *timer)
160 {
161         ATOMIC(
162                 /* Calculate expiration time for this timer */
163                 timer->tick = _clock + timer->_delay;
164
165                 timer_addToList(timer, &timers_queue);
166         );
167 }
168
169 /**
170  * Remove a timer from the timers queue before it has expired.
171  *
172  * \note Attempting to remove a timer already expired cause
173  *       undefined behaviour.
174  */
175 Timer *timer_abort(Timer *timer)
176 {
177         ATOMIC(REMOVE(&timer->link));
178         DB(timer->magic = TIMER_MAGIC_INACTIVE;)
179
180         return timer;
181 }
182
183
184 INLINE void timer_poll(List *queue)
185 {
186         Timer *timer;
187
188         /*
189          * Check the first timer request in the list and process
190          * it when it has expired. Repeat this check until the
191          * first node has not yet expired. Since the list is sorted
192          * by expiry time, all the following requests are guaranteed
193          * to expire later.
194          */
195         while ((timer = (Timer *)LIST_HEAD(queue))->link.succ)
196         {
197                 /* This request in list has not yet expired? */
198                 if (timer_clock() - timer->tick < 0)
199                         break;
200
201                 /* Retreat the expired timer */
202                 REMOVE(&timer->link);
203                 DB(timer->magic = TIMER_MAGIC_INACTIVE;)
204
205                 /* Execute the associated event */
206                 event_do(&timer->expire);
207         }
208 }
209
210 /**
211  * Add \a timer to \a queue.
212  * \see synctimer_poll() for details.
213  */
214 void synctimer_add(Timer *timer, List *queue)
215 {
216         timer->tick = timer_clock() + timer->_delay;
217
218         timer_addToList(timer, queue);
219 }
220
221 void synctimer_readd(Timer *timer, List *queue)
222 {
223         timer->tick += timer->_delay;
224         timer_addToList(timer, queue);
225 }
226
227
228 /**
229  * Simple synchronous timer based scheduler polling routine.
230  *
231  * Sometimes you would like to have a proper scheduler,
232  * but you can't afford it due to memory constraints.
233  *
234  * This is a simple replacement: you can create events and call
235  * them periodically at specific time intervals.
236  * All you have to do is to set up normal timers, and call synctimer_add()
237  * instead of timer_add() to add the events to your specific queue.
238  * Then, in the main loop or wherever you want, you can call
239  * synctimer_poll() to process expired events. The associated callbacks will be
240  * executed.
241  * As this is done synchronously you don't have to worry about race conditions.
242  * You can kill an event by simply calling synctimer_abort().
243  *
244  */
245 void synctimer_poll(List *queue)
246 {
247         timer_poll(queue);
248 }
249
250 #endif /* CONFIG_TIMER_EVENTS */
251
252
253 /**
254  * Wait for the specified amount of timer ticks.
255  *
256  * \note Sleeping while preemption is disabled fallbacks to a busy wait sleep.
257  */
258 void timer_delayTicks(ticks_t delay)
259 {
260         /* We shouldn't sleep with interrupts disabled */
261         IRQ_ASSERT_ENABLED();
262
263 #if CONFIG_KERN_SIGNALS
264         Timer t;
265         DB(t.magic = TIMER_MAGIC_INACTIVE;)
266         if (proc_preemptAllowed())
267         {
268                 ASSERT(!sig_check(SIG_SINGLE));
269                 timer_setSignal(&t, proc_current(), SIG_SINGLE);
270                 timer_setDelay(&t, delay);
271                 timer_add(&t);
272                 sig_wait(SIG_SINGLE);
273         }
274         else
275 #endif /* !CONFIG_KERN_SIGNALS */
276         {
277                 ticks_t start = timer_clock();
278
279                 /* Busy wait */
280                 while (timer_clock() - start < delay)
281                         cpu_relax();
282         }
283 }
284
285
286 #if CONFIG_TIMER_UDELAY
287
288 /**
289  * Busy wait until the specified amount of high-precision ticks have elapsed.
290  *
291  * \note This function is interrupt safe, the only
292  *       requirement is a running hardware timer.
293  */
294 void timer_busyWait(hptime_t delay)
295 {
296         hptime_t now, prev = timer_hw_hpread();
297         hptime_t delta;
298
299         for (;;)
300         {
301                 now = timer_hw_hpread();
302                 /*
303                  * The timer counter may wrap here and "prev" can become
304                  * greater than "now". So, be sure to always evaluate a
305                  * coherent timer difference:
306                  *
307                  * 0     prev            now   TIMER_HW_CNT
308                  * |_____|_______________|_____|
309                  *        ^^^^^^^^^^^^^^^
310                  * delta = now - prev
311                  *
312                  * 0     now             prev  TIMER_HW_CNT
313                  * |_____|_______________|_____|
314                  *  ^^^^^                 ^^^^^
315                  * delta = (TIMER_HW_CNT - prev) + now
316                  *
317                  * NOTE: TIMER_HW_CNT can be any value, not necessarily a power
318                  * of 2. For this reason the "%" operator is not suitable for
319                  * the generic case.
320                  */
321                 delta = (now < prev) ? ((hptime_t)TIMER_HW_CNT - prev + now) :
322                                                 (now - prev);
323                 if (delta >= delay)
324                         break;
325                 delay -= delta;
326                 prev = now;
327         }
328 }
329
330 /**
331  * Wait for the specified amount of time (expressed in microseconds).
332  *
333  * \bug In AVR arch the maximum amount of time that can be used as
334  *      delay could be very limited, depending on the hardware timer
335  *      used. Check timer_avr.h, and what register is used as hptime_t.
336  */
337 void timer_delayHp(hptime_t delay)
338 {
339         if (UNLIKELY(delay > us_to_hptime(1000)))
340         {
341                 timer_delayTicks(delay / (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC));
342                 delay %= (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC);
343         }
344
345         timer_busyWait(delay);
346 }
347 #endif /* CONFIG_TIMER_UDELAY */
348
349 /**
350  * Timer interrupt handler. Find soft timers expired and
351  * trigger corresponding events.
352  */
353 DEFINE_TIMER_ISR
354 {
355         /*
356          * With the Metrowerks compiler, the only way to force the compiler generate
357          * an interrupt service routine is to put a pragma directive within the function
358          * body.
359          */
360         #ifdef __MWERKS__
361         #pragma interrupt saveall
362         #endif
363
364         /*
365          * On systems sharing IRQ line and vector, this check is needed
366          * to ensure that IRQ is generated by timer source.
367          */
368         if (!timer_hw_triggered())
369                 return;
370
371         TIMER_STROBE_ON;
372
373         /* Update the master ms counter */
374         ++_clock;
375
376         /* Update the current task's quantum (if enabled). */
377         proc_decQuantum();
378
379         #if CONFIG_TIMER_EVENTS
380                 timer_poll(&timers_queue);
381         #endif
382
383         /* Perform hw IRQ handling */
384         timer_hw_irq();
385
386         TIMER_STROBE_OFF;
387 }
388
389 MOD_DEFINE(timer)
390
391 /**
392  * Initialize timer
393  */
394 void timer_init(void)
395 {
396         #if CONFIG_KERN_IRQ
397                 MOD_CHECK(irq);
398         #endif
399
400         #if CONFIG_TIMER_EVENTS
401                 LIST_INIT(&timers_queue);
402         #endif
403
404         TIMER_STROBE_INIT;
405
406         _clock = 0;
407
408         timer_hw_init();
409
410         MOD_INIT(timer);
411 }
412
413
414 #if (ARCH & ARCH_EMUL) || (CPU_ARM_AT91)
415 /**
416  * Stop timer
417  */
418 void timer_cleanup(void)
419 {
420         MOD_CLEANUP(timer);
421
422         timer_hw_cleanup();
423 }
424 #endif