Split cpu/cpu.h in 3 files: irq, types and attr.
[bertos.git] / 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_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 #endif
83
84
85 /**
86  * \def CONFIG_TIMER_STROBE
87  *
88  * This is a debug facility that can be used to
89  * monitor timer interrupt activity on an external pin.
90  *
91  * To use strobes, redefine the macros TIMER_STROBE_ON,
92  * TIMER_STROBE_OFF and TIMER_STROBE_INIT and set
93  * CONFIG_TIMER_STROBE to 1.
94  */
95 #if !defined(CONFIG_TIMER_STROBE) || !CONFIG_TIMER_STROBE
96         #define TIMER_STROBE_ON    do {/*nop*/} while(0)
97         #define TIMER_STROBE_OFF   do {/*nop*/} while(0)
98         #define TIMER_STROBE_INIT  do {/*nop*/} while(0)
99 #endif
100
101
102 /// Master system clock (1 tick accuracy)
103 volatile ticks_t _clock;
104
105
106 #ifndef CONFIG_TIMER_DISABLE_EVENTS
107
108 /**
109  * List of active asynchronous timers.
110  */
111 REGISTER static List timers_queue;
112
113
114 /**
115  * Add the specified timer to the software timer service queue.
116  * When the delay indicated by the timer expires, the timer
117  * device will execute the event associated with it.
118  *
119  * \note Interrupt safe
120  */
121 void timer_add(Timer *timer)
122 {
123         Timer *node;
124         cpuflags_t flags;
125
126
127         /* Inserting timers twice causes mayhem. */
128         ASSERT(timer->magic != TIMER_MAGIC_ACTIVE);
129         DB(timer->magic = TIMER_MAGIC_ACTIVE;)
130
131         IRQ_SAVE_DISABLE(flags);
132
133         /* Calculate expiration time for this timer */
134         timer->tick = _clock + timer->_delay;
135
136         /*
137          * Search for the first node whose expiration time is
138          * greater than the timer we want to add.
139          */
140         node = (Timer *)LIST_HEAD(&timers_queue);
141         while (node->link.succ)
142         {
143                 /*
144                  * Stop just after the insertion point.
145                  * (this fancy compare takes care of wrap-arounds).
146                  */
147                 if (node->tick - timer->tick > 0)
148                         break;
149
150                 /* Go to next node */
151                 node = (Timer *)node->link.succ;
152         }
153
154         /* Enqueue timer request into the list */
155         INSERT_BEFORE(&timer->link, &node->link);
156
157         IRQ_RESTORE(flags);
158 }
159
160
161 /**
162  * Remove a timer from the timer queue before it has expired.
163  */
164 Timer *timer_abort(Timer *timer)
165 {
166         ATOMIC(REMOVE(&timer->link));
167         DB(timer->magic = TIMER_MAGIC_INACTIVE;)
168
169         return timer;
170 }
171
172 #endif /* CONFIG_TIMER_DISABLE_EVENTS */
173
174
175 /**
176  * Wait for the specified amount of timer ticks.
177  */
178 void timer_delayTicks(ticks_t delay)
179 {
180 #if defined(IRQ_ENABLED)
181         /* We shouldn't sleep with interrupts disabled */
182         ASSERT(IRQ_ENABLED());
183 #endif
184
185 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
186         Timer t;
187
188         ASSERT(!sig_check(SIG_SINGLE));
189         timer_set_event_signal(&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         {
201 #if CONFIG_WATCHDOG
202                 wdt_reset();
203 #endif
204         }
205
206 #endif /* !CONFIG_KERN_SIGNALS */
207 }
208
209
210 #ifndef CONFIG_TIMER_DISABLE_UDELAY
211
212 /**
213  * Busy wait until the specified amount of high-precision ticks have elapsed.
214  *
215  * \note This function is interrupt safe, the only
216  *       requirement is a running hardware timer.
217  */
218 void timer_busyWait(hptime_t delay)
219 {
220         hptime_t now, prev = timer_hw_hpread();
221         hptime_t delta;
222
223         for(;;)
224         {
225                 now = timer_hw_hpread();
226                 /*
227                  * We rely on hptime_t being unsigned here to
228                  * reduce the modulo to an AND in the common
229                  * case of TIMER_HW_CNT.
230                  */
231                 delta = (now - prev) % TIMER_HW_CNT;
232                 if (delta >= delay)
233                         break;
234                 delay -= delta;
235                 prev = now;
236         }
237 }
238
239 /**
240  * Wait for the specified amount of time (expressed in microseconds).
241  *
242  * \bug In AVR arch the maximum amount of time that can be used as
243  *      delay could be very limited, depending on the hardware timer
244  *      used. Check timer_avr.h, and what register is used as hptime_t.
245  */
246 void timer_delayHp(hptime_t delay)
247 {
248         if (UNLIKELY(delay > us_to_hptime(1000)))
249         {
250                 timer_delayTicks(delay / (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC));
251                 delay %= (TIMER_HW_HPTICKS_PER_SEC / TIMER_TICKS_PER_SEC);
252         }
253
254         timer_busyWait(delay);
255 }
256 #endif /* CONFIG_TIMER_DISABLE_UDELAY */
257
258
259 /**
260  * Timer interrupt handler. Find soft timers expired and
261  * trigger corresponding events.
262  */
263 DEFINE_TIMER_ISR
264 {
265         /*
266          * With the Metrowerks compiler, the only way to force the compiler generate
267          * an interrupt service routine is to put a pragma directive within the function
268          * body.
269          */
270         #ifdef __MWERKS__
271         #pragma interrupt saveall
272         #endif
273
274 #ifndef CONFIG_TIMER_DISABLE_EVENTS
275         Timer *timer;
276 #endif
277         /*
278          * On systems sharing IRQ line and vector, this check is needed
279          * to ensure that IRQ is generated by timer source.
280          */
281         if (!timer_hw_triggered())
282                 return;
283
284         TIMER_STROBE_ON;
285
286         /* Perform hw IRQ handling */
287         timer_hw_irq();
288
289         /* Update the master ms counter */
290         ++_clock;
291
292 #ifndef CONFIG_TIMER_DISABLE_EVENTS
293         /*
294          * Check the first timer request in the list and process
295          * it when it has expired. Repeat this check until the
296          * first node has not yet expired. Since the list is sorted
297          * by expiry time, all the following requests are guaranteed
298          * to expire later.
299          */
300         while ((timer = (Timer *)LIST_HEAD(&timers_queue))->link.succ)
301         {
302                 /* This request in list has not yet expired? */
303                 if (_clock - timer->tick < 0)
304                         break;
305
306                 /* Retreat the expired timer */
307                 REMOVE(&timer->link);
308                 DB(timer->magic = TIMER_MAGIC_INACTIVE;)
309
310                 /* Execute the associated event */
311                 event_do(&timer->expire);
312         }
313 #endif /* CONFIG_TIMER_DISABLE_EVENTS */
314
315         TIMER_STROBE_OFF;
316 }
317
318 MOD_DEFINE(timer)
319
320 /**
321  * Initialize timer
322  */
323 void timer_init(void)
324 {
325         TIMER_STROBE_INIT;
326
327 #ifndef CONFIG_TIMER_DISABLE_EVENTS
328         LIST_INIT(&timers_queue);
329 #endif
330
331         _clock = 0;
332
333         timer_hw_init();
334
335         MOD_INIT(timer);
336 }