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