blob: e4b6596f22310bd8c51063035223277057674e6e [file] [log] [blame]
Travis Geiselbrecht1d0df692008-09-01 02:26:09 -07001/*
2 * Copyright (c) 2008 Travis Geiselbrecht
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23#include <err.h>
24#include <sys/types.h>
25
26#include <kernel/thread.h>
27#include <platform/timer.h>
28#include <platform/interrupts.h>
29#include <platform/debug.h>
30#include <platform/at91sam7.h>
31
32#define FIXED_1KHZ_TIMER 0
33
34static platform_timer_callback timer_func;
35
36static volatile time_t ticks = 0;
37
38#if FIXED_1KHZ_TIMER
39static volatile int timer_interval;
40static volatile int timer_downcount;
41#else
42static int timer_ms_per_tick;
43#endif
44
45time_t current_time(void)
46{
47 return ticks;
48}
49
50static enum handler_return pit_irq_handler(void *arg)
51{
52 AT91PIT *pit = AT91PIT_ADDR;
53 unsigned n = PIT_PICNT(pit->PIVR);
54
55#if FIXED_1KHZ_TIMER
56 ticks += n;
57 timer_downcount -= n;
58
59 if(timer_downcount <= 0) {
60 timer_downcount = timer_interval;
61 return timer_func(0, ticks);
62 } else {
63 return INT_NO_RESCHEDULE;
64 }
65#else
66 ticks += (n * timer_ms_per_tick);
67 return timer_func(0, ticks);
68#endif
69}
70
71status_t platform_set_periodic_timer(platform_timer_callback callback,
72 void *arg, time_t interval)
73{
74 unsigned n;
75
76 AT91PIT *pit = AT91PIT_ADDR;
77
78 n = AT91_MCK_MHZ / 16 / 1000;
79 dprintf("timer: MCK=%dKHz, n=%d\n", AT91_MCK_MHZ / 1000, n);
80
81 enter_critical_section();
82
83 timer_func = callback;
84
85#if FIXED_1KHZ_TIMER
86 timer_interval = interval;
87 timer_downcount = interval;
88#else
89 timer_ms_per_tick = interval;
90 n *= interval;
91#endif
92
93 pit->MR = PIT_PITEN | PIT_PITIEN | (n & 0xfffff);
94
95 register_int_handler(PID_SYSIRQ, pit_irq_handler, 0);
96 unmask_interrupt(PID_SYSIRQ, 0);
97
98 exit_critical_section();
99
100 return NO_ERROR;
101}
102