2 * GeekOS timer interrupt support
3 * Copyright (c) 2001,2003 David H. Hovemeyer <daveho@cs.umd.edu>
4 * Copyright (c) 2003, Jeffrey K. Hollingsworth <hollings@cs.umd.edu>
5 * (c) 2008, Jack Lange <jarusl@cs.northwestern.edu>
6 * (c) 2008, The V3VEE Project <http://www.v3vee.org>
9 * This is free software. You are permitted to use,
10 * redistribute, and modify it as specified in the file "COPYING".
14 #include <geekos/io.h>
15 #include <geekos/int.h>
16 #include <geekos/irq.h>
17 #include <geekos/kthread.h>
18 #include <geekos/timer.h>
20 #include <geekos/serial.h>
21 #include <geekos/debug.h>
23 #include <geekos/io_defs.h>
25 /* PAD this currently is in nvram.c */
26 extern void deliver_timer_interrupt_to_vmm(uint_t period_us);
28 /* JRL Add a cpu frequency measurement */
42 #define rdtscll(val) \
43 __asm__ __volatile__("rdtsc" : "=A" (val))
45 #elif defined(__x86_64__)
47 #define rdtscll(val) do { \
49 asm volatile("rdtsc" : "=a" (a), "=d" (d)); \
50 (val) = ((unsigned long)a) | (((unsigned long)d)<<32); \
55 #define do_div(n,base) ({ \
56 unsigned long __upper, __low, __high, __mod, __base; \
58 asm("":"=a" (__low), "=d" (__high):"A" (n)); \
61 __upper = __high % (__base); \
62 __high = __high / (__base); \
64 asm("divl %2":"=a" (__low), "=d" (__mod):"rm" (__base), "0" (__low), "1" (__upper)); \
65 asm("":"=A" (n):"a" (__low),"d" (__high)); \
71 * This uses the Programmable Interval Timer that is standard on all
72 * PC-compatible systems to determine the time stamp counter frequency.
74 * This uses the speaker output (channel 2) of the PIT. This is better than
75 * using the timer interrupt output because we can read the value of the
76 * speaker with just one inb(), where we need three i/o operations for the
77 * interrupt channel. We count how many ticks the TSC does in 50 ms.
79 * Returns the detected time stamp counter frequency in KHz.
84 pit_calibrate_tsc(void)
88 // unsigned long flags;
89 unsigned long pit_tick_rate = 1193182UL; /* 1.193182 MHz */
91 // spin_lock_irqsave(&pit_lock, flags);
93 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
96 outb((pit_tick_rate / (1000 / 50)) & 0xff, 0x42);
97 outb((pit_tick_rate / (1000 / 50)) >> 8, 0x42);
98 // start = get_cycles_sync();
100 while ((inb(0x61) & 0x20) == 0);
102 // end = get_cycles_sync();
104 // spin_unlock_irqrestore(&pit_lock, flags);
107 // return (end - start) / 50;
120 #define MAX_TIMER_EVENTS 100
122 static int timerDebug = 0;
123 static int timeEventCount;
124 static int nextEventID;
125 timerEvent pendingTimerEvents[MAX_TIMER_EVENTS];
130 * Global tick counter
132 volatile ulong_t g_numTicks;
135 * Number of times the spin loop can execute during one timer tick
137 static int s_spinCountPerTick;
140 * Number of ticks to wait before calibrating the delay loop.
142 #define CALIBRATE_NUM_TICKS 3
145 * The default quantum; maximum number of ticks a thread can use before
146 * we suspend it and choose another.
148 #define DEFAULT_MAX_TICKS 4
153 int g_Quantum = DEFAULT_MAX_TICKS;
157 * FIXME: should set this to something more reasonable, like 100.
160 //#define TICKS_PER_SEC 18
162 /*#define DEBUG_TIMER */
164 # define Debug(args...) Print(args)
166 # define Debug(args...)
169 ulong_t clock_time(void){//in millisec
170 return g_numTicks * (1000/HZ);
173 /* ----------------------------------------------------------------------
175 * ---------------------------------------------------------------------- */
177 static void Timer_Interrupt_Handler(struct Interrupt_State* state)
180 struct Kernel_Thread* current = g_currentThread;
184 /* Update global and per-thread number of ticks */
189 /* update timer events */
190 for (i=0; i < timeEventCount; i++) {
191 if (pendingTimerEvents[i].ticks == 0) {
192 if (timerDebug) Print("timer: event %d expired (%d ticks)\n",
193 pendingTimerEvents[i].id, pendingTimerEvents[i].origTicks);
194 (pendingTimerEvents[i].callBack)(pendingTimerEvents[i].id, pendingTimerEvents[i].cb_arg);
195 pendingTimerEvents[i].ticks = pendingTimerEvents[i].origTicks;
197 pendingTimerEvents[i].ticks--;
202 * If thread has been running for an entire quantum,
203 * inform the interrupt return code that we want
204 * to choose a new thread.
206 if (current->numTicks >= g_Quantum) {
207 g_needReschedule = true;
209 * The current process is moved to a lower priority queue,
210 * since it consumed a full quantum.
212 //if (current->currentReadyQueue < (MAX_QUEUE_LEVEL - 1)) {
213 /*Print("process %d moved to ready queue %d\n", current->pid, current->currentReadyQueue); */
214 //current->currentReadyQueue++;
220 deliver_timer_interrupt_to_vmm(1000000/HZ);
226 * Temporary timer interrupt handler used to calibrate
229 static void Timer_Calibrate(struct Interrupt_State* state)
232 if (g_numTicks < CALIBRATE_NUM_TICKS)
236 * Now we can look at EAX, which reflects how many times
237 * the loop has executed
239 /*Print("Timer_Calibrate: eax==%d\n", state->eax);*/
240 s_spinCountPerTick = INT_MAX - state->eax;
241 state->eax = 0; /* make the loop terminate */
247 * Delay loop; spins for given number of iterations.
249 static void Spin(int count)
252 * The assembly code is the logical equivalent of
253 * while (count-- > 0) { // waste some time }
254 * We rely on EAX being used as the counter
259 __asm__ __volatile__ (
262 "nop; nop; nop; nop; nop; nop\n\t"
263 "nop; nop; nop; nop; nop; nop\n\t"
271 * Calibrate the delay loop.
272 * This will initialize s_spinCountPerTick, which indicates
273 * how many iterations of the loop are executed per timer tick.
275 static void Calibrate_Delay(void)
277 Disable_Interrupts();
279 /* Install temporarily interrupt handler */
280 Install_IRQ(TIMER_IRQ, &Timer_Calibrate);
281 Enable_IRQ(TIMER_IRQ);
285 /* Wait a few ticks */
286 while (g_numTicks < CALIBRATE_NUM_TICKS)
290 * Execute the spin loop.xs
291 * The temporary interrupt handler will overwrite the
292 * loop counter when the next tick occurs.
300 Disable_Interrupts();
303 * Mask out the timer IRQ again,
304 * since we will be installing a real timer interrupt handler.
306 Disable_IRQ(TIMER_IRQ);
310 /* ----------------------------------------------------------------------
312 * ---------------------------------------------------------------------- */
314 void Init_Timer(void)
316 ushort_t foo = 1193182L / HZ;
318 cpu_khz_freq = pit_calibrate_tsc();
319 PrintBoth("CPU KHZ=%lu\n", (ulong_t)cpu_khz_freq);
321 PrintBoth("Initializing timer and setting to %d Hz...\n",HZ);
323 /* Calibrate for delay loop */
325 PrintBoth("Delay loop: %d iterations per tick\n", s_spinCountPerTick);
329 Out_Byte(0x43,0x36); // channel 0, LSB/MSB, mode 3, binary
330 Out_Byte(0x40, foo & 0xff); // LSB
331 Out_Byte(0x40, foo >>8); // MSB
333 /* Install an interrupt handler for the timer IRQ */
335 Install_IRQ(TIMER_IRQ, &Timer_Interrupt_Handler);
336 Enable_IRQ(TIMER_IRQ);
340 int Start_Timer_Secs(int seconds, timerCallback cb, void * arg) {
341 return Start_Timer(seconds * HZ, cb, arg);
345 int Start_Timer_MSecs(int msecs, timerCallback cb, void * arg) {
346 msecs += 10 - (msecs % 10);
348 return Start_Timer(msecs * (HZ / 1000), cb, arg);
353 int Start_Timer(int ticks, timerCallback cb, void * arg)
357 KASSERT(!Interrupts_Enabled());
359 if (timeEventCount == MAX_TIMER_EVENTS) {
363 pendingTimerEvents[timeEventCount].id = ret;
364 pendingTimerEvents[timeEventCount].callBack = cb;
365 pendingTimerEvents[timeEventCount].cb_arg = arg;
366 pendingTimerEvents[timeEventCount].ticks = ticks;
367 pendingTimerEvents[timeEventCount].origTicks = ticks;
375 int Get_Remaining_Timer_Ticks(int id)
379 KASSERT(!Interrupts_Enabled());
380 for (i=0; i < timeEventCount; i++) {
381 if (pendingTimerEvents[i].id == id) {
382 return pendingTimerEvents[i].ticks;
391 double Get_Remaining_Timer_Secs(int id) {
392 return (Get_Remaining_Timer_Ticks(id) / HZ);
396 int Get_Remaining_Timer_MSecs(int id) {
397 return ((Get_Remaining_Timer_Ticks(id) * 1000) / HZ);
402 int Cancel_Timer(int id)
405 KASSERT(!Interrupts_Enabled());
406 for (i=0; i < timeEventCount; i++) {
407 if (pendingTimerEvents[i].id == id) {
408 pendingTimerEvents[i] = pendingTimerEvents[timeEventCount-1];
414 Print("timer: unable to find timer id %d to cancel it\n", id);
419 #define US_PER_TICK (HZ * 1000000)
422 * Spin for at least given number of microseconds.
423 * FIXME: I'm sure this implementation leaves a lot to
426 void Micro_Delay(int us)
428 int num = us * s_spinCountPerTick;
429 int denom = US_PER_TICK;
431 int numSpins = num / denom;
432 int rem = num % denom;
437 Debug("Micro_Delay(): num=%d, denom=%d, spin count = %d\n", num, denom, numSpins);