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