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>
7 * This is free software. You are permitted to use,
8 * redistribute, and modify it as specified in the file "COPYING".
12 #include <geekos/io.h>
13 #include <geekos/int.h>
14 #include <geekos/irq.h>
15 #include <geekos/kthread.h>
16 #include <geekos/timer.h>
18 #include <geekos/serial.h>
19 #include <geekos/debug.h>
21 #include <geekos/io_defs.h>
23 /* PAD this currently is in nvram.c */
24 extern void deliver_timer_interrupt_to_vmm(uint_t period_us);
26 /* JRL Add a cpu frequency measurement */
40 #define rdtscll(val) \
41 __asm__ __volatile__("rdtsc" : "=A" (val))
43 #elif defined(__x86_64__)
45 #define rdtscll(val) do { \
47 asm volatile("rdtsc" : "=a" (a), "=d" (d)); \
48 (val) = ((unsigned long)a) | (((unsigned long)d)<<32); \
53 #define do_div(n,base) ({ \
54 unsigned long __upper, __low, __high, __mod, __base; \
56 asm("":"=a" (__low), "=d" (__high):"A" (n)); \
59 __upper = __high % (__base); \
60 __high = __high / (__base); \
62 asm("divl %2":"=a" (__low), "=d" (__mod):"rm" (__base), "0" (__low), "1" (__upper)); \
63 asm("":"=A" (n):"a" (__low),"d" (__high)); \
69 * This uses the Programmable Interval Timer that is standard on all
70 * PC-compatible systems to determine the time stamp counter frequency.
72 * This uses the speaker output (channel 2) of the PIT. This is better than
73 * using the timer interrupt output because we can read the value of the
74 * speaker with just one inb(), where we need three i/o operations for the
75 * interrupt channel. We count how many ticks the TSC does in 50 ms.
77 * Returns the detected time stamp counter frequency in KHz.
82 pit_calibrate_tsc(void)
86 // unsigned long flags;
87 unsigned long pit_tick_rate = 1193182UL; /* 1.193182 MHz */
89 // spin_lock_irqsave(&pit_lock, flags);
91 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
94 outb((pit_tick_rate / (1000 / 50)) & 0xff, 0x42);
95 outb((pit_tick_rate / (1000 / 50)) >> 8, 0x42);
96 // start = get_cycles_sync();
98 while ((inb(0x61) & 0x20) == 0);
100 // end = get_cycles_sync();
102 // spin_unlock_irqrestore(&pit_lock, flags);
105 // return (end - start) / 50;
118 #define MAX_TIMER_EVENTS 100
120 static int timerDebug = 0;
121 static int timeEventCount;
122 static int nextEventID;
123 timerEvent pendingTimerEvents[MAX_TIMER_EVENTS];
128 * Global tick counter
130 volatile ulong_t g_numTicks;
132 ulong_t clock_time(void){
138 * Number of times the spin loop can execute during one timer tick
140 static int s_spinCountPerTick;
143 * Number of ticks to wait before calibrating the delay loop.
145 #define CALIBRATE_NUM_TICKS 3
148 * The default quantum; maximum number of ticks a thread can use before
149 * we suspend it and choose another.
151 #define DEFAULT_MAX_TICKS 4
156 int g_Quantum = DEFAULT_MAX_TICKS;
160 * FIXME: should set this to something more reasonable, like 100.
163 //#define TICKS_PER_SEC 18
165 /*#define DEBUG_TIMER */
167 # define Debug(args...) Print(args)
169 # define Debug(args...)
172 /* ----------------------------------------------------------------------
174 * ---------------------------------------------------------------------- */
176 static void Timer_Interrupt_Handler(struct Interrupt_State* state)
179 struct Kernel_Thread* current = g_currentThread;
183 /* Update global and per-thread number of ticks */
188 /* update timer events */
189 for (i=0; i < timeEventCount; i++) {
190 if (pendingTimerEvents[i].ticks == 0) {
191 if (timerDebug) Print("timer: event %d expired (%d ticks)\n",
192 pendingTimerEvents[i].id, pendingTimerEvents[i].origTicks);
193 (pendingTimerEvents[i].callBack)(pendingTimerEvents[i].id);
194 pendingTimerEvents[i].ticks = pendingTimerEvents[i].origTicks;
196 pendingTimerEvents[i].ticks--;
201 * If thread has been running for an entire quantum,
202 * inform the interrupt return code that we want
203 * to choose a new thread.
205 if (current->numTicks >= g_Quantum) {
206 g_needReschedule = true;
208 * The current process is moved to a lower priority queue,
209 * since it consumed a full quantum.
211 //if (current->currentReadyQueue < (MAX_QUEUE_LEVEL - 1)) {
212 /*Print("process %d moved to ready queue %d\n", current->pid, current->currentReadyQueue); */
213 //current->currentReadyQueue++;
219 deliver_timer_interrupt_to_vmm(1000000/HZ);
225 * Temporary timer interrupt handler used to calibrate
228 static void Timer_Calibrate(struct Interrupt_State* state)
231 if (g_numTicks < CALIBRATE_NUM_TICKS)
235 * Now we can look at EAX, which reflects how many times
236 * the loop has executed
238 /*Print("Timer_Calibrate: eax==%d\n", state->eax);*/
239 s_spinCountPerTick = INT_MAX - state->eax;
240 state->eax = 0; /* make the loop terminate */
246 * Delay loop; spins for given number of iterations.
248 static void Spin(int count)
251 * The assembly code is the logical equivalent of
252 * while (count-- > 0) { // waste some time }
253 * We rely on EAX being used as the counter
258 __asm__ __volatile__ (
261 "nop; nop; nop; nop; nop; nop\n\t"
262 "nop; nop; nop; nop; nop; nop\n\t"
270 * Calibrate the delay loop.
271 * This will initialize s_spinCountPerTick, which indicates
272 * how many iterations of the loop are executed per timer tick.
274 static void Calibrate_Delay(void)
276 Disable_Interrupts();
278 /* Install temporarily interrupt handler */
279 Install_IRQ(TIMER_IRQ, &Timer_Calibrate);
280 Enable_IRQ(TIMER_IRQ);
284 /* Wait a few ticks */
285 while (g_numTicks < CALIBRATE_NUM_TICKS)
289 * Execute the spin loop.xs
290 * The temporary interrupt handler will overwrite the
291 * loop counter when the next tick occurs.
299 Disable_Interrupts();
302 * Mask out the timer IRQ again,
303 * since we will be installing a real timer interrupt handler.
305 Disable_IRQ(TIMER_IRQ);
309 /* ----------------------------------------------------------------------
311 * ---------------------------------------------------------------------- */
313 void Init_Timer(void)
315 ushort_t foo = 1193182L / HZ;
317 cpu_khz_freq = pit_calibrate_tsc();
318 PrintBoth("CPU KHZ=%lu\n", (ulong_t)cpu_khz_freq);
320 PrintBoth("Initializing timer and setting to %d Hz...\n",HZ);
322 /* Calibrate for delay loop */
324 PrintBoth("Delay loop: %d iterations per tick\n", s_spinCountPerTick);
328 Out_Byte(0x43,0x36); // channel 0, LSB/MSB, mode 3, binary
329 Out_Byte(0x40, foo & 0xff); // LSB
330 Out_Byte(0x40, foo >>8); // MSB
332 /* Install an interrupt handler for the timer IRQ */
334 Install_IRQ(TIMER_IRQ, &Timer_Interrupt_Handler);
335 Enable_IRQ(TIMER_IRQ);
339 int Start_Timer(int ticks, timerCallback cb)
343 KASSERT(!Interrupts_Enabled());
345 if (timeEventCount == MAX_TIMER_EVENTS) {
349 pendingTimerEvents[timeEventCount].id = ret;
350 pendingTimerEvents[timeEventCount].callBack = cb;
351 pendingTimerEvents[timeEventCount].ticks = ticks;
352 pendingTimerEvents[timeEventCount].origTicks = ticks;
359 int Get_Remaing_Timer_Ticks(int id)
363 KASSERT(!Interrupts_Enabled());
364 for (i=0; i < timeEventCount; i++) {
365 if (pendingTimerEvents[i].id == id) {
366 return pendingTimerEvents[i].ticks;
373 int Cancel_Timer(int id)
376 KASSERT(!Interrupts_Enabled());
377 for (i=0; i < timeEventCount; i++) {
378 if (pendingTimerEvents[i].id == id) {
379 pendingTimerEvents[i] = pendingTimerEvents[timeEventCount-1];
385 Print("timer: unable to find timer id %d to cancel it\n", id);
390 #define US_PER_TICK (HZ * 1000000)
393 * Spin for at least given number of microseconds.
394 * FIXME: I'm sure this implementation leaves a lot to
397 void Micro_Delay(int us)
399 int num = us * s_spinCountPerTick;
400 int denom = US_PER_TICK;
402 int numSpins = num / denom;
403 int rem = num % denom;
408 Debug("Micro_Delay(): num=%d, denom=%d, spin count = %d\n", num, denom, numSpins);