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