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