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