Add handy functions for handling non recurrent timeouts.
[bertos.git] / bertos / drv / timer.h
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 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000, 2008 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \defgroup drv_timers Timer module
34  * \ingroup core
35  * \{
36  *
37  * \brief Hardware independent timer driver.
38  *
39  * All timer related functions are implemented in this module. You have several options to use timers:
40  * \li simple delay: just use timer_delay() if you want to wait for a few milliseconds;
41  * \li delay with callback: create a timer structure and use timer_setDelay() and timer_setSoftint() to set the callback;
42  * \li delay with signal: same as above but use timer_setSignal() to set specify which signal to send.
43  * \li simple synchronous timer based scheduler: use synctimer_add() to schedule an event in a user provided queue.
44  *
45  * Whenever a timer expires you need to explicitly arm it again with timer_add(). If you want to abort a timer, use timer_abort().
46  * You can use conversion macros when using msecs to specify the delay.
47  *
48  * \author Bernie Innocenti <bernie@codewiz.org>
49  *
50  * $WIZ$ module_name = "timer"
51  * $WIZ$ module_configuration = "bertos/cfg/cfg_timer.h"
52  * $WIZ$ module_depends = "event", "sysirq"
53  * $WIZ$ module_supports = "not atmega103 and not atmega8"
54  */
55
56 #ifndef DRV_TIMER_H
57 #define DRV_TIMER_H
58
59 #include <cfg/os.h>
60 #include <cfg/macros.h>
61
62 #include <cpu/attr.h>
63 #include <cpu/irq.h>
64
65 #include <string.h>
66
67 /*
68  * Include platform-specific binding header if we're hosted.
69  * Try the CPU specific one for bare-metal environments.
70  */
71 #if OS_HOSTED
72         //#include OS_HEADER(timer)
73         #include <emul/timer_posix.h>
74 #else
75         #include CPU_HEADER(timer)
76 #endif
77
78 STATIC_ASSERT(sizeof(hptime_t) == SIZEOF_HPTIME_T);
79
80 #include "cfg/cfg_timer.h"
81 #include <cfg/debug.h>
82 #include <cfg/compiler.h>
83
84 #include <struct/list.h>
85
86 /*
87  * Sanity check for config parameters required by this module.
88  */
89 #if !defined(CONFIG_TIMER_EVENTS) || ((CONFIG_TIMER_EVENTS != 0) && CONFIG_TIMER_EVENTS != 1)
90         #error CONFIG_TIMER_EVENTS must be set to either 0 or 1 in cfg_timer.h
91 #endif
92 #if !defined(CONFIG_TIMER_UDELAY) || ((CONFIG_TIMER_UDELAY != 0) && CONFIG_TIMER_EVENTS != 1)
93         #error CONFIG_TIMER_UDELAY must be set to either 0 or 1 in cfg_timer.h
94 #endif
95 #if defined(CONFIG_TIMER_DISABLE_UDELAY)
96         #error Obosolete config option CONFIG_TIMER_DISABLE_UDELAY.  Use CONFIG_TIMER_UDELAY
97 #endif
98 #if defined(CONFIG_TIMER_DISABLE_EVENTS)
99         #error Obosolete config option CONFIG_TIMER_DISABLE_EVENTS.  Use CONFIG_TIMER_EVENTS
100 #endif
101
102 extern volatile ticks_t _clock;
103
104 #define TIMER_AFTER(x, y) ((long)(y) - (long)(x) < 0)
105 #define TIMER_BEFORE(x, y) TIMER_AFTER(y, x)
106
107 /**
108  * \brief Return the system tick counter (expressed in ticks)
109  *
110  * The result is guaranteed to increment monotonically,
111  * but client code must be tolerant with respect to overflows.
112  *
113  * The following code is safe:
114  *
115  * \code
116  *   drop_teabag();
117  *   ticks_t tea_start_time = timer_clock();
118  *
119  *   for (;;)
120  *   {
121  *       if (timer_clock() - tea_start_time > TEAPOT_DELAY)
122  *       {
123  *           printf("Your tea, Sir.\n");
124  *           break;
125  *       }
126  *       patience();
127  *   }
128  * \endcode
129  *
130  * \note This function must disable interrupts on 8/16bit CPUs because the
131  * clock variable is larger than the processor word size and can't
132  * be copied atomically.
133  * \sa timer_delay()
134  */
135 INLINE ticks_t timer_clock(void)
136 {
137         ticks_t result;
138
139         ATOMIC(result = _clock);
140
141         return result;
142 }
143
144 /**
145  * Faster version of timer_clock(), to be called only when the timer
146  * interrupt is disabled (DISABLE_INTS) or overridden by a
147  * higher-priority or non-nesting interrupt.
148  *
149  * \sa timer_clock
150  */
151 INLINE ticks_t timer_clock_unlocked(void)
152 {
153         return _clock;
154 }
155
156
157 /** Convert \a ms [ms] to ticks. */
158 INLINE ticks_t ms_to_ticks(mtime_t ms)
159 {
160 #if TIMER_TICKS_PER_SEC < 1000
161         /* Slow timer: avoid rounding down too much. */
162         return (ms * TIMER_TICKS_PER_SEC) / 1000;
163 #else
164         /* Fast timer: don't overflow ticks_t. */
165         return ms * DIV_ROUND(TIMER_TICKS_PER_SEC, 1000);
166 #endif
167 }
168
169 /** Convert \a us [us] to ticks. */
170 INLINE ticks_t us_to_ticks(utime_t us)
171 {
172 #if TIMER_TICKS_PER_SEC < 1000
173         /* Slow timer: avoid rounding down too much. */
174         return ((us / 1000) * TIMER_TICKS_PER_SEC) / 1000;
175 #else
176         /* Fast timer: don't overflow ticks_t. */
177         return (us * DIV_ROUND(TIMER_TICKS_PER_SEC, 1000)) / 1000;
178 #endif
179 }
180
181 /** Convert \a ticks [ticks] to ms. */
182 INLINE mtime_t ticks_to_ms(ticks_t ticks)
183 {
184 #if TIMER_TICKS_PER_SEC < 1000
185         /* Slow timer: avoid rounding down too much. */
186         return (ticks * 1000) / TIMER_TICKS_PER_SEC;
187 #else
188         /* Fast timer: avoid overflowing ticks_t. */
189         return ticks / (TIMER_TICKS_PER_SEC / 1000);
190 #endif
191 }
192
193 /** Convert \a ticks [ticks] to us. */
194 INLINE utime_t ticks_to_us(ticks_t ticks)
195 {
196 #if TIMER_TICKS_PER_SEC < 1000
197         /* Slow timer: avoid rounding down too much. */
198         return ((ticks * 1000) / TIMER_TICKS_PER_SEC) * 1000;
199 #else
200         /* Fast timer: avoid overflowing ticks_t. */
201         return (ticks / (TIMER_TICKS_PER_SEC / 1000)) * 1000;
202 #endif
203 }
204
205 /** Convert \a us [us] to hpticks */
206 INLINE hptime_t us_to_hptime(utime_t us)
207 {
208 #if TIMER_HW_HPTICKS_PER_SEC > 10000000UL
209         return us * DIV_ROUND(TIMER_HW_HPTICKS_PER_SEC, 1000000UL);
210 #else
211         return (us * ((TIMER_HW_HPTICKS_PER_SEC + 500) / 1000UL) + 500) / 1000UL;
212 #endif
213 }
214
215 /** Convert \a hpticks [hptime] to usec */
216 INLINE utime_t hptime_to_us(hptime_t hpticks)
217 {
218 #if TIMER_HW_HPTICKS_PER_SEC < 100000UL
219         return hpticks * DIV_ROUND(1000000UL, TIMER_HW_HPTICKS_PER_SEC);
220 #else
221         return (hpticks * 1000UL) / DIV_ROUND(TIMER_HW_HPTICKS_PER_SEC, 1000UL);
222 #endif /* TIMER_HW_HPTICKS_PER_SEC < 100000UL */
223 }
224
225 void timer_delayTicks(ticks_t delay);
226 /**
227  * Wait some time [ms].
228  *
229  * \note CPU is released while waiting so you don't have to call cpu_relax() explicitly.
230  * \param delay Time to wait [ms].
231  */
232 INLINE void timer_delay(mtime_t delay)
233 {
234         timer_delayTicks(ms_to_ticks(delay));
235 }
236
237 void timer_init(void);
238 void timer_cleanup(void);
239
240 int timer_testSetup(void);
241 int timer_testRun(void);
242 int timer_testTearDown(void);
243
244 #if CONFIG_TIMER_UDELAY
245 void timer_busyWait(hptime_t delay);
246 void timer_delayHp(hptime_t delay);
247 INLINE void timer_udelay(utime_t delay)
248 {
249         timer_delayHp(us_to_hptime(delay));
250 }
251 #endif
252
253 #if CONFIG_TIMER_EVENTS
254
255 #include <mware/event.h>
256
257 /**
258  * The timer driver supports multiple synchronous timers
259  * that can trigger an event when they expire.
260  *
261  * \sa timer_add()
262  * \sa timer_abort()
263  */
264 typedef struct Timer
265 {
266         Node    link;     /**< Link into timers queue */
267         ticks_t _delay;   /**< [ticks] Timer delay */
268         ticks_t tick;     /**< [ticks] When this timer will expire */
269         Event   expire;   /**< Event to execute when the timer expires */
270         DB(uint16_t magic;)
271 } Timer;
272
273 /* Timer is active when Timer.magic contains this value (for debugging purposes). */
274 #define TIMER_MAGIC_ACTIVE    0xABBA
275 #define TIMER_MAGIC_INACTIVE  0xBAAB
276
277 void timer_add(Timer *timer);
278 Timer *timer_abort(Timer *timer);
279
280 /**
281  * Set the timer so that it calls an user hook when it expires
282  *
283  * Sometimes you may want to use the same callback for different events, so you must have
284  * different data to operate on. The user_data parameter is such data.
285  *
286  * \param timer Timer struct to set the callback to
287  * \param func  Function that will be called when the timer expires
288  * \param user_data Additional data you may want to pass to the callback
289  */
290 INLINE void timer_setSoftint(Timer *timer, Hook func, iptr_t user_data)
291 {
292         event_initSoftint(&timer->expire, func, user_data);
293 }
294
295 /**
296  * Set the timer delay (the time before the event will be triggered)
297  *
298  * \note It's illegal to change the delay of the timer when it's
299  * still running.
300  */
301 INLINE void timer_setDelay(Timer *timer, ticks_t delay)
302 {
303         timer->_delay = delay;
304 }
305
306
307 void synctimer_add(Timer *timer, List* q);
308
309 /** \sa timer_abort */
310 #define synctimer_abort(t) timer_abort(t)
311
312 void synctimer_poll(List* q);
313
314 /**
315  * Extract the timeout for the next event.
316  *
317  * \return Timeout of the next event (may be 0), or -1 on errors.
318  */
319 INLINE ticks_t synctimer_nextTimeout(List *q)
320 {
321         ticks_t timeout = -1;
322
323         if (!LIST_EMPTY(q))
324         {
325                 Timer *expiring_timer = (Timer *)LIST_HEAD(q);
326                 timeout = MAX(expiring_timer->tick - timer_clock(), (ticks_t)0);
327         }
328         return timeout;
329 }
330
331 /*
332  * Explicitly mark a timer as executed.
333  *
334  * When a timer is marked as executed, it is inactive until the next
335  * call to synctimer_add().
336  * Normally you shouldn't need to call this function explicitly, as all
337  * timers in this module are designed to stop themselves after a while
338  * (eg. retransmission timer will stop after a few retransmissions).
339  * The only exception is at startup, where you should mark all timers
340  * as executed to avoid spurious events.
341  *
342  * \note We can't rely on REMOVE() of synctimer_poll() since in release mode
343  * it is empty.
344  */
345 INLINE void synctimer_executed(Timer *t)
346 {
347         memset(&t->link, 0, sizeof(Node));
348 }
349
350 /*
351  * Test if a timer is active.
352  *
353  * In the general case it should be ATOMIC() and timer.link should always
354  * be memset() to 0.
355  */
356 INLINE bool synctimer_active(Timer *t)
357 {
358         return !(t->link.pred == NULL && t->link.succ == NULL);
359 }
360
361
362 INLINE void synctimer_stop(Timer *timer)
363 {
364         if (synctimer_active(timer))
365         {
366                 timer_abort(timer);
367                 synctimer_executed(timer);
368         }
369 }
370
371 INLINE void synctimer_restart(Timer *timer, List *list, mtime_t timeout)
372 {
373         synctimer_stop(timer);
374
375         timer_setDelay(timer, ms_to_ticks(timeout));
376         synctimer_add(timer, list);
377 }
378
379 void synctimer_readd(Timer *timer, List *queue);
380
381 #endif /* CONFIG_TIMER_EVENTS */
382
383 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
384
385 /** Set the timer so that it sends a signal when it expires */
386 INLINE void timer_setSignal(Timer *timer, struct Process *proc, sigmask_t sigs)
387 {
388         event_initSignal(&timer->expire, proc, sigs);
389 }
390
391 #define timer_set_event_signal timer_setSignal
392
393 #endif /* CONFIG_KERN_SIGNALS */
394
395 /** \} */ //defgroup drv_timers
396
397 #endif /* DRV_TIMER_H */