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