Merge branch 'master' into iso-9660
[lunaix-os.git] / lunaix-os / kernel / time / timer.c
1 /**
2  * @file timer.c
3  * @author Lunaixsky
4  * @brief A simple timer implementation based on APIC with adjustable frequency
5  * and subscribable "timerlets"
6  * @version 0.1
7  * @date 2022-03-12
8  *
9  * @copyright Copyright (c) 2022
10  *
11  */
12 #include <arch/x86/interrupts.h>
13 #include <hal/apic.h>
14 #include <hal/rtc.h>
15
16 #include <lunaix/isrm.h>
17 #include <lunaix/mm/cake.h>
18 #include <lunaix/mm/valloc.h>
19 #include <lunaix/sched.h>
20 #include <lunaix/spike.h>
21 #include <lunaix/syslog.h>
22 #include <lunaix/timer.h>
23
24 #include <hal/acpi/acpi.h>
25
26 #define LVT_ENTRY_TIMER(vector, mode) (LVT_DELIVERY_FIXED | mode | vector)
27
28 LOG_MODULE("TIMER");
29
30 static void
31 temp_intr_routine_rtc_tick(const isr_param* param);
32
33 static void
34 temp_intr_routine_apic_timer(const isr_param* param);
35
36 static void
37 timer_update(const isr_param* param);
38
39 static volatile struct lx_timer_context* timer_ctx = NULL;
40
41 // Don't optimize them! Took me an half hour to figure that out...
42
43 static volatile uint32_t rtc_counter = 0;
44 static volatile uint8_t apic_timer_done = 0;
45
46 static volatile uint32_t sched_ticks = 0;
47 static volatile uint32_t sched_ticks_counter = 0;
48
49 static struct cake_pile* timer_pile;
50
51 #define APIC_CALIBRATION_CONST 0x100000
52
53 void
54 timer_init_context()
55 {
56     timer_pile = cake_new_pile("timer", sizeof(struct lx_timer), 1, 0);
57     timer_ctx =
58       (struct lx_timer_context*)valloc(sizeof(struct lx_timer_context));
59
60     assert_msg(timer_ctx, "Fail to initialize timer contex");
61
62     timer_ctx->active_timers = (struct lx_timer*)cake_grab(timer_pile);
63     llist_init_head(&timer_ctx->active_timers->link);
64 }
65
66 void
67 timer_init(uint32_t frequency)
68 {
69     timer_init_context();
70
71     cpu_disable_interrupt();
72
73     // Setup APIC timer
74
75     // Remap the IRQ 8 (rtc timer's vector) to RTC_TIMER_IV in ioapic
76     //       (Remarks IRQ 8 is pin INTIN8)
77     //       See IBM PC/AT Technical Reference 1-10 for old RTC IRQ
78     //       See Intel's Multiprocessor Specification for IRQ - IOAPIC INTIN
79     //       mapping config.
80
81     // grab ourselves these irq numbers
82     uint32_t iv_rtc = isrm_bindirq(PC_AT_IRQ_RTC, temp_intr_routine_rtc_tick);
83     uint32_t iv_timer = isrm_ivexalloc(temp_intr_routine_apic_timer);
84
85     // Setup a one-shot timer, we will use this to measure the bus speed. So we
86     // can then calibrate apic timer to work at *nearly* accurate hz
87     apic_write_reg(APIC_TIMER_LVT,
88                    LVT_ENTRY_TIMER(iv_timer, LVT_TIMER_ONESHOT));
89
90     // Set divider to 64
91     apic_write_reg(APIC_TIMER_DCR, APIC_TIMER_DIV64);
92
93     /*
94         Timer calibration process - measure the APIC timer base frequency
95
96          step 1: setup a temporary isr for RTC timer which trigger at each tick
97                  (1024Hz)
98          step 2: setup a temporary isr for #APIC_TIMER_IV
99          step 3: setup the divider, APIC_TIMER_DCR
100          step 4: Startup RTC timer
101          step 5: Write a large value, v, to APIC_TIMER_ICR to start APIC timer
102        (this must be followed immediately after step 4) step 6: issue a write to
103        EOI and clean up.
104
105         When the APIC ICR counting down to 0 #APIC_TIMER_IV triggered, save the
106        rtc timer's counter, k, and disable RTC timer immediately (although the
107        RTC interrupts should be blocked by local APIC as we are currently busy
108        on handling #APIC_TIMER_IV)
109
110         So the apic timer frequency F_apic in Hz can be calculate as
111             v / F_apic = k / 1024
112             =>  F_apic = v / k * 1024
113
114     */
115
116 #ifdef __LUNAIXOS_DEBUG__
117     if (frequency < 1000) {
118         kprintf(KWARN "Frequency too low. Millisecond timer might be dodgy.");
119     }
120 #endif
121
122     timer_ctx->base_frequency = 0;
123     rtc_counter = 0;
124     apic_timer_done = 0;
125
126     rtc_enable_timer();                                     // start RTC timer
127     apic_write_reg(APIC_TIMER_ICR, APIC_CALIBRATION_CONST); // start APIC timer
128
129     // enable interrupt, just for our RTC start ticking!
130     cpu_enable_interrupt();
131
132     wait_until(apic_timer_done);
133
134     assert_msg(timer_ctx->base_frequency, "Fail to initialize timer (NOFREQ)");
135
136     kprintf(KINFO "Base frequency: %u Hz\n", timer_ctx->base_frequency);
137
138     timer_ctx->running_frequency = frequency;
139     timer_ctx->tphz = timer_ctx->base_frequency / frequency;
140
141     // cleanup
142     isrm_ivfree(iv_timer);
143     isrm_ivfree(iv_rtc);
144
145     apic_write_reg(
146       APIC_TIMER_LVT,
147       LVT_ENTRY_TIMER(isrm_ivexalloc(timer_update), LVT_TIMER_PERIODIC));
148
149     apic_write_reg(APIC_TIMER_ICR, timer_ctx->tphz);
150
151     sched_ticks = timer_ctx->running_frequency / 1000 * SCHED_TIME_SLICE;
152     sched_ticks_counter = 0;
153 }
154
155 struct lx_timer*
156 timer_run_second(uint32_t second,
157                  void (*callback)(void*),
158                  void* payload,
159                  uint8_t flags)
160 {
161     return timer_run(
162       second * timer_ctx->running_frequency, callback, payload, flags);
163 }
164
165 struct lx_timer*
166 timer_run_ms(uint32_t millisecond,
167              void (*callback)(void*),
168              void* payload,
169              uint8_t flags)
170 {
171     return timer_run(timer_ctx->running_frequency / 1000 * millisecond,
172                      callback,
173                      payload,
174                      flags);
175 }
176
177 struct lx_timer*
178 timer_run(ticks_t ticks, void (*callback)(void*), void* payload, uint8_t flags)
179 {
180     struct lx_timer* timer = (struct lx_timer*)cake_grab(timer_pile);
181
182     if (!timer)
183         return NULL;
184
185     timer->callback = callback;
186     timer->counter = ticks;
187     timer->deadline = ticks;
188     timer->payload = payload;
189     timer->flags = flags;
190
191     llist_append(&timer_ctx->active_timers->link, &timer->link);
192
193     return timer;
194 }
195
196 static void
197 timer_update(const isr_param* param)
198 {
199     struct lx_timer *pos, *n;
200     struct lx_timer* timer_list_head = timer_ctx->active_timers;
201
202     llist_for_each(pos, n, &timer_list_head->link, link)
203     {
204         if (--(pos->counter)) {
205             continue;
206         }
207
208         pos->callback ? pos->callback(pos->payload) : 1;
209
210         if ((pos->flags & TIMER_MODE_PERIODIC)) {
211             pos->counter = pos->deadline;
212         } else {
213             llist_delete(&pos->link);
214             cake_release(timer_pile, pos);
215         }
216     }
217
218     sched_ticks_counter++;
219
220     if (sched_ticks_counter >= sched_ticks) {
221         sched_ticks_counter = 0;
222         schedule();
223     }
224 }
225
226 static void
227 temp_intr_routine_rtc_tick(const isr_param* param)
228 {
229     rtc_counter++;
230
231     // dummy read on register C so RTC can send anther interrupt
232     //  This strange behaviour observed in virtual box & bochs
233     (void)rtc_read_reg(RTC_REG_C);
234 }
235
236 static void
237 temp_intr_routine_apic_timer(const isr_param* param)
238 {
239     timer_ctx->base_frequency =
240       APIC_CALIBRATION_CONST / rtc_counter * RTC_TIMER_BASE_FREQUENCY;
241     apic_timer_done = 1;
242
243     rtc_disable_timer();
244 }
245
246 struct lx_timer_context*
247 timer_context()
248 {
249     return timer_ctx;
250 }