Add synchronous timer scheduler.
[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 /*
56  * Include platform-specific binding code if we're hosted.
57  * Try the CPU specific one for bare-metal environments.
58  */
59 #if OS_HOSTED
60         //#include OS_CSOURCE(timer)
61         #include <emul/timer_posix.c>
62 #else
63         #ifndef WIZ_AUTOGEN
64                 #warning Deprecated: now you should include timer_<cpu> directly in the makefile. Remove this line and the following once done.
65                 #include CPU_CSOURCE(timer)
66         #endif
67 #endif
68
69 /*
70  * Sanity check for config parameters required by this module.
71  */
72 #if !defined(CONFIG_KERN) || ((CONFIG_KERN != 0) && CONFIG_KERN != 1)
73         #error CONFIG_KERN must be set to either 0 or 1 in config.h
74 #endif
75 #if !defined(CONFIG_WATCHDOG) || ((CONFIG_WATCHDOG != 0) && CONFIG_WATCHDOG != 1)
76         #error CONFIG_WATCHDOG must be set to either 0 or 1 in config.h
77 #endif
78
79 #if CONFIG_WATCHDOG
80         #include <drv/wdt.h>
81 #endif
82
83 #if defined (CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
84         #include <kern/signal.h> /* sig_wait(), sig_check() */
85         #include <kern/proc.h>   /* proc_current() */
86         #include <cfg/macros.h>  /* BV() */
87 #endif
88
89
90 /**
91  * \def CONFIG_TIMER_STROBE
92  *
93  * This is a debug facility that can be used to
94  * monitor timer interrupt activity on an external pin.
95  *
96  * To use strobes, redefine the macros TIMER_STROBE_ON,
97  * TIMER_STROBE_OFF and TIMER_STROBE_INIT and set
98  * CONFIG_TIMER_STROBE to 1.
99  */
100 #if !defined(CONFIG_TIMER_STROBE) || !CONFIG_TIMER_STROBE
101         #define TIMER_STROBE_ON    do {/*nop*/} while(0)
102         #define TIMER_STROBE_OFF   do {/*nop*/} while(0)
103         #define TIMER_STROBE_INIT  do {/*nop*/} while(0)
104 #endif
105
106
107 /// Master system clock (1 tick accuracy)
108 volatile ticks_t _clock;
109
110
111 #if CONFIG_TIMER_EVENTS
112
113 /**
114  * List of active asynchronous timers.
115  */
116 REGISTER static List timers_queue;
117
118 /**
119  * This function really does the job. It adds \a timer to \a queue.
120  * \see timer_add for details.
121  */
122 INLINE void timer_addToList(Timer *timer, List *queue)
123 {
124         /* Inserting timers twice causes mayhem. */
125         ASSERT(timer->magic != TIMER_MAGIC_ACTIVE);
126         DB(timer->magic = TIMER_MAGIC_ACTIVE;)
127
128
129         /* Calculate expiration time for this timer */
130         timer->tick = _clock + timer->_delay;
131
132         /*
133          * Search for the first node whose expiration time is
134          * greater than the timer we want to add.
135          */
136         Timer *node = (Timer *)LIST_HEAD(queue);
137         while (node->link.succ)
138         {
139                 /*
140                  * Stop just after the insertion point.
141                  * (this fancy compare takes care of wrap-arounds).
142                  */
143                 if (node->tick - timer->tick > 0)
144                         break;
145
146                 /* Go to next node */
147                 node = (Timer *)node->link.succ;
148         }
149
150         /* Enqueue timer request into the list */
151         INSERT_BEFORE(&timer->link, &node->link);
152 }
153
154 /**
155  * Add the specified timer to the software timer service queue.
156  * When the delay indicated by the timer expires, the timer
157  * device will execute the event associated with it.
158  *
159  * \note Interrupt safe
160  */
161 void timer_add(Timer *timer)
162 {
163         ATOMIC(timer_addToList(timer, &timers_queue));
164 }
165
166 /**
167  * Remove a timer from the timers queue before it has expired.
168  *
169  * \note Attempting to remove a timer already expired cause
170  *       undefined behaviour.
171  */
172 Timer *timer_abort(Timer *timer)
173 {
174         ATOMIC(REMOVE(&timer->link));
175         DB(timer->magic = TIMER_MAGIC_INACTIVE;)
176
177         return timer;
178 }
179
180
181 INLINE void timer_poll(List *queue)
182 {
183         Timer *timer;
184
185         /*
186          * Check the first timer request in the list and process
187          * it when it has expired. Repeat this check until the
188          * first node has not yet expired. Since the list is sorted
189          * by expiry time, all the following requests are guaranteed
190          * to expire later.
191          */
192         while ((timer = (Timer *)LIST_HEAD(queue))->link.succ)
193         {
194                 /* This request in list has not yet expired? */
195                 if (timer_clock() - timer->tick < 0)
196                         break;
197
198                 /* Retreat the expired timer */
199                 REMOVE(&timer->link);
200                 DB(timer->magic = TIMER_MAGIC_INACTIVE;)
201
202                 /* Execute the associated event */
203                 event_do(&timer->expire);
204         }
205 }
206
207 /**
208  * Add \a timer to \a queue.
209  * \see synctimer_poll() for details.
210  */
211 void synctimer_add(Timer *timer, List *queue)
212 {
213         timer_addToList(timer, queue);
214 }
215
216 /**
217  * Simple synchronous timer based scheduler polling routine.
218  *
219  * Sometimes you would like to have a proper scheduler,
220  * but you can't afford it due to memory constraints.
221  *
222  * This is a simple replacement: you can create events and call
223  * them periodically at specific time intervals.
224  * All you have to do is to set up normal timers, and call synctimer_add()
225  * instead of timer_add() to add the events to your specific queue.
226  * Then, in the main loop or wherever you want, you can call
227  * synctimer_poll() to process expired events. The associated callbacks will be
228  * executed.
229  * As this is done synchronously you don't have to worry about race conditions.
230  * You can kill an event by simply calling synctimer_abort().
231  *
232  */
233 void synctimer_poll(List *queue)
234 {
235         timer_poll(queue);
236 }
237
238 #endif /* CONFIG_TIMER_EVENTS */
239
240
241 /**
242  * Wait for the specified amount of timer ticks.
243  */
244 void timer_delayTicks(ticks_t delay)
245 {
246         /* We shouldn't sleep with interrupts disabled */
247         IRQ_ASSERT_ENABLED();
248
249 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
250         Timer t;
251
252         ASSERT(!sig_check(SIG_SINGLE));
253         timer_setSignal(&t, proc_current(), SIG_SINGLE);
254         timer_setDelay(&t, delay);
255         timer_add(&t);
256         sig_wait(SIG_SINGLE);
257
258 #else /* !CONFIG_KERN_SIGNALS */
259
260         ticks_t start = timer_clock();
261
262         /* Busy wait */
263         while (timer_clock() - start < delay)
264                 cpu_relax();
265
266 #endif /* !CONFIG_KERN_SIGNALS */
267 }
268
269
270 #if CONFIG_TIMER_UDELAY
271
272 /**
273  * Busy wait until the specified amount of high-precision ticks have elapsed.
274  *
275  * \note This function is interrupt safe, the only
276  *       requirement is a running hardware timer.
277  */
278 void timer_busyWait(hptime_t delay)
279 {
280         hptime_t now, prev = timer_hw_hpread();
281         hptime_t delta;
282
283         for(;;)
284         {
285                 now = timer_hw_hpread();
286                 /*
287                  * We rely on hptime_t being unsigned here to
288                  * reduce the modulo to an AND in the common
289                  * case of TIMER_HW_CNT.
290                  */
291                 delta = (now - prev) % TIMER_HW_CNT;
292                 if (delta >= delay)
293                         break;
294                 delay -= delta;
295                 prev = now;
296         }
297 }
298
299 /**
300  * Wait for the specified amount of time (expressed in microseconds).
301  *
302  * \bug In AVR arch the maximum amount of time that can be used as
303  *      delay could be very limited, depending on the hardware timer
304  *      used. Check timer_avr.h, and what register is used as hptime_t.
305  */
306 void timer_delayHp(hptime_t delay)
307 {
308         if (UNLIKELY(delay > us_to_hptime(1000)))
309         {
310                 timer_delayTicks(delay / (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC));
311                 delay %= (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC);
312         }
313
314         timer_busyWait(delay);
315 }
316 #endif /* CONFIG_TIMER_UDELAY */
317
318
319 /**
320  * Timer interrupt handler. Find soft timers expired and
321  * trigger corresponding events.
322  */
323 DEFINE_TIMER_ISR
324 {
325         /*
326          * With the Metrowerks compiler, the only way to force the compiler generate
327          * an interrupt service routine is to put a pragma directive within the function
328          * body.
329          */
330         #ifdef __MWERKS__
331         #pragma interrupt saveall
332         #endif
333
334         /*
335          * On systems sharing IRQ line and vector, this check is needed
336          * to ensure that IRQ is generated by timer source.
337          */
338         if (!timer_hw_triggered())
339                 return;
340
341         TIMER_STROBE_ON;
342
343         /* Perform hw IRQ handling */
344         timer_hw_irq();
345
346         /* Update the master ms counter */
347         ++_clock;
348
349         #if CONFIG_TIMER_EVENTS
350                 timer_poll(&timers_queue);
351         #endif
352
353         TIMER_STROBE_OFF;
354 }
355
356 MOD_DEFINE(timer)
357
358 /**
359  * Initialize timer
360  */
361 void timer_init(void)
362 {
363         #if CONFIG_KERN_IRQ
364                 MOD_CHECK(irq);
365         #endif
366
367         #if CONFIG_TIMER_EVENTS
368                 LIST_INIT(&timers_queue);
369         #endif
370
371         TIMER_STROBE_INIT;
372
373         _clock = 0;
374
375         timer_hw_init();
376
377         MOD_INIT(timer);
378 }
379
380
381 #if (ARCH & ARCH_EMUL)
382 /**
383  * Stop timer (only used by emulator)
384  */
385 void timer_cleanup(void)
386 {
387         MOD_CLEANUP(timer);
388
389         timer_hw_cleanup();
390
391         // Hmmm... apparently, the demo app does not cleanup properly
392         //ASSERT(LIST_EMPTY(&timers_queue));
393 }
394 #endif /* ARCH_EMUL */