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 /* JRL: This is completely broken
27 extern void deliver_timer_interrupt_to_vmm(uint_t period_us);
30 /* JRL Add a cpu frequency measurement */
44 #define rdtscll(val) \
45 __asm__ __volatile__("rdtsc" : "=A" (val))
47 #elif defined(__x86_64__)
49 #define rdtscll(val) do { \
51 asm volatile("rdtsc" : "=a" (a), "=d" (d)); \
52 (val) = ((unsigned long)a) | (((unsigned long)d)<<32); \
57 #define do_div(n,base) ({ \
58 unsigned long __upper, __low, __high, __mod, __base; \
60 asm("":"=a" (__low), "=d" (__high):"A" (n)); \
63 __upper = __high % (__base); \
64 __high = __high / (__base); \
66 asm("divl %2":"=a" (__low), "=d" (__mod):"rm" (__base), "0" (__low), "1" (__upper)); \
67 asm("":"=A" (n):"a" (__low),"d" (__high)); \
73 * This uses the Programmable Interval Timer that is standard on all
74 * PC-compatible systems to determine the time stamp counter frequency.
76 * This uses the speaker output (channel 2) of the PIT. This is better than
77 * using the timer interrupt output because we can read the value of the
78 * speaker with just one inb(), where we need three i/o operations for the
79 * interrupt channel. We count how many ticks the TSC does in 50 ms.
81 * Returns the detected time stamp counter frequency in KHz.
86 pit_calibrate_tsc(void)
90 // unsigned long flags;
91 unsigned long pit_tick_rate = 1193182UL; /* 1.193182 MHz */
93 // spin_lock_irqsave(&pit_lock, flags);
95 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
98 outb((pit_tick_rate / (1000 / 50)) & 0xff, 0x42);
99 outb((pit_tick_rate / (1000 / 50)) >> 8, 0x42);
100 // start = get_cycles_sync();
102 while ((inb(0x61) & 0x20) == 0);
104 // end = get_cycles_sync();
106 // spin_unlock_irqrestore(&pit_lock, flags);
109 // return (end - start) / 50;
122 #define MAX_TIMER_EVENTS 100
124 static int timerDebug = 0;
125 static int timeEventCount;
126 static int nextEventID;
127 timerEvent pendingTimerEvents[MAX_TIMER_EVENTS];
132 * Global tick counter
134 volatile ulong_t g_numTicks;
137 * Number of times the spin loop can execute during one timer tick
139 static int s_spinCountPerTick;
142 * Number of ticks to wait before calibrating the delay loop.
144 #define CALIBRATE_NUM_TICKS 3
147 * The default quantum; maximum number of ticks a thread can use before
148 * we suspend it and choose another.
150 #define DEFAULT_MAX_TICKS 4
155 int g_Quantum = DEFAULT_MAX_TICKS;
159 * FIXME: should set this to something more reasonable, like 100.
162 //#define TICKS_PER_SEC 18
164 /*#define DEBUG_TIMER */
166 # define Debug(args...) Print(args)
168 # define Debug(args...)
171 ulong_t clock_time(void){//in millisec
172 return g_numTicks * (1000/HZ);
175 /* ----------------------------------------------------------------------
177 * ---------------------------------------------------------------------- */
179 static void Timer_Interrupt_Handler(struct Interrupt_State* state)
182 struct Kernel_Thread* current = g_currentThread;
186 /* Update global and per-thread number of ticks */
191 /* update timer events */
192 for (i=0; i < timeEventCount; i++) {
193 if (pendingTimerEvents[i].ticks == 0) {
194 if (timerDebug) Print("timer: event %d expired (%d ticks)\n",
195 pendingTimerEvents[i].id, pendingTimerEvents[i].origTicks);
196 (pendingTimerEvents[i].callBack)(pendingTimerEvents[i].id, pendingTimerEvents[i].cb_arg);
197 pendingTimerEvents[i].ticks = pendingTimerEvents[i].origTicks;
199 pendingTimerEvents[i].ticks--;
204 * If thread has been running for an entire quantum,
205 * inform the interrupt return code that we want
206 * to choose a new thread.
208 if (current->numTicks >= g_Quantum) {
209 g_needReschedule = true;
211 * The current process is moved to a lower priority queue,
212 * since it consumed a full quantum.
214 //if (current->currentReadyQueue < (MAX_QUEUE_LEVEL - 1)) {
215 /*Print("process %d moved to ready queue %d\n", current->pid, current->currentReadyQueue); */
216 //current->currentReadyQueue++;
222 deliver_timer_interrupt_to_vmm(1000000/HZ);
228 * Temporary timer interrupt handler used to calibrate
231 static void Timer_Calibrate(struct Interrupt_State* state)
234 if (g_numTicks < CALIBRATE_NUM_TICKS)
238 * Now we can look at EAX, which reflects how many times
239 * the loop has executed
241 /*Print("Timer_Calibrate: eax==%d\n", state->eax);*/
242 s_spinCountPerTick = INT_MAX - state->eax;
243 state->eax = 0; /* make the loop terminate */
249 * Delay loop; spins for given number of iterations.
251 static void Spin(int count)
254 * The assembly code is the logical equivalent of
255 * while (count-- > 0) { // waste some time }
256 * We rely on EAX being used as the counter
261 __asm__ __volatile__ (
264 "nop; nop; nop; nop; nop; nop\n\t"
265 "nop; nop; nop; nop; nop; nop\n\t"
273 * Calibrate the delay loop.
274 * This will initialize s_spinCountPerTick, which indicates
275 * how many iterations of the loop are executed per timer tick.
277 static void Calibrate_Delay(void)
279 Disable_Interrupts();
281 /* Install temporarily interrupt handler */
282 Install_IRQ(TIMER_IRQ, &Timer_Calibrate);
283 Enable_IRQ(TIMER_IRQ);
287 /* Wait a few ticks */
288 while (g_numTicks < CALIBRATE_NUM_TICKS)
292 * Execute the spin loop.xs
293 * The temporary interrupt handler will overwrite the
294 * loop counter when the next tick occurs.
302 Disable_Interrupts();
305 * Mask out the timer IRQ again,
306 * since we will be installing a real timer interrupt handler.
308 Disable_IRQ(TIMER_IRQ);
312 /* ----------------------------------------------------------------------
314 * ---------------------------------------------------------------------- */
316 void Init_Timer(void)
318 ushort_t foo = 1193182L / HZ;
320 cpu_khz_freq = pit_calibrate_tsc();
321 PrintBoth("CPU KHZ=%lu\n", (ulong_t)cpu_khz_freq);
323 PrintBoth("Initializing timer and setting to %d Hz...\n",HZ);
325 /* Calibrate for delay loop */
327 PrintBoth("Delay loop: %d iterations per tick\n", s_spinCountPerTick);
331 Out_Byte(0x43,0x36); // channel 0, LSB/MSB, mode 3, binary
332 Out_Byte(0x40, foo & 0xff); // LSB
333 Out_Byte(0x40, foo >>8); // MSB
335 /* Install an interrupt handler for the timer IRQ */
337 Install_IRQ(TIMER_IRQ, &Timer_Interrupt_Handler);
338 Enable_IRQ(TIMER_IRQ);
342 int Start_Timer_Secs(int seconds, timerCallback cb, void * arg) {
343 return Start_Timer(seconds * HZ, cb, arg);
347 int Start_Timer_MSecs(int msecs, timerCallback cb, void * arg) {
348 msecs += 10 - (msecs % 10);
350 return Start_Timer(msecs * (HZ / 1000), cb, arg);
355 int Start_Timer(int ticks, timerCallback cb, void * arg)
359 KASSERT(!Interrupts_Enabled());
361 PrintBoth ("there\n");
363 if (timeEventCount == MAX_TIMER_EVENTS) {
367 pendingTimerEvents[timeEventCount].id = ret;
368 pendingTimerEvents[timeEventCount].callBack = cb;
369 pendingTimerEvents[timeEventCount].cb_arg = arg;
370 pendingTimerEvents[timeEventCount].ticks = ticks;
371 pendingTimerEvents[timeEventCount].origTicks = ticks;
379 int Get_Remaining_Timer_Ticks(int id)
383 KASSERT(!Interrupts_Enabled());
384 for (i=0; i < timeEventCount; i++) {
385 if (pendingTimerEvents[i].id == id) {
386 return pendingTimerEvents[i].ticks;
395 double Get_Remaining_Timer_Secs(int id) {
396 return (Get_Remaining_Timer_Ticks(id) / HZ);
400 int Get_Remaining_Timer_MSecs(int id) {
401 return ((Get_Remaining_Timer_Ticks(id) * 1000) / HZ);
406 int Cancel_Timer(int id)
409 KASSERT(!Interrupts_Enabled());
410 for (i=0; i < timeEventCount; i++) {
411 if (pendingTimerEvents[i].id == id) {
412 pendingTimerEvents[i] = pendingTimerEvents[timeEventCount-1];
418 Print("timer: unable to find timer id %d to cancel it\n", id);
423 #define US_PER_TICK (HZ * 1000000)
426 * Spin for at least given number of microseconds.
427 * FIXME: I'm sure this implementation leaves a lot to
430 void Micro_Delay(int us)
432 int num = us * s_spinCountPerTick;
433 int denom = US_PER_TICK;
435 int numSpins = num / denom;
436 int rem = num % denom;
441 Debug("Micro_Delay(): num=%d, denom=%d, spin count = %d\n", num, denom, numSpins);