1 #include "devices/timer.h"
4 #include "threads/interrupt.h"
5 #include "threads/io.h"
6 #include "threads/thread.h"
9 #error 8254 timer requires TIMER_FREQ >= 19
12 #error TIMER_FREQ <= 1000 recommended
15 /* Number of timer ticks that a process gets before being
19 /* Number of timer ticks since OS booted. */
20 static volatile int64_t ticks;
22 static intr_handler_func timer_interrupt;
24 /* Sets up the 8254 Programmable Interrupt Timer (PIT) to
25 interrupt PIT_FREQ times per second, and registers the
26 corresponding interrupt. */
30 /* 8254 input frequency divided by TIMER_FREQ, rounded to
32 uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
34 outb (0x43, 0x34); /* CW: counter 0, LSB then MSB, mode 2, binary. */
35 outb (0x40, count & 0xff);
36 outb (0x40, count >> 8);
38 intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
41 /* Returns the number of timer ticks since the OS booted. */
45 enum intr_level old_level = intr_disable ();
47 intr_set_level (old_level);
51 /* Returns the number of timer ticks elapsed since THEN, which
52 should be a value once returned by timer_ticks(). */
54 timer_elapsed (int64_t then)
56 return timer_ticks () - then;
59 /* Suspends execution for approximately TICKS timer ticks. */
61 timer_sleep (int64_t ticks)
63 int64_t start = timer_ticks ();
65 while (timer_elapsed (start) < ticks)
66 if (intr_get_level () == INTR_ON)
70 /* Returns MS milliseconds in timer ticks, rounding up. */
72 timer_ms2ticks (int64_t ms)
75 ------------------------ = MS * TIMER_FREQ / 1000 ticks.
76 (1 / TIMER_FREQ) ticks/s
78 return DIV_ROUND_UP (ms * TIMER_FREQ, 1000);
81 /* Returns US microseconds in timer ticks, rounding up. */
83 timer_us2ticks (int64_t us)
85 return DIV_ROUND_UP (us * TIMER_FREQ, 1000000);
88 /* Returns NS nanoseconds in timer ticks, rounding up. */
90 timer_ns2ticks (int64_t ns)
92 return DIV_ROUND_UP (ns * TIMER_FREQ, 1000000000);
95 /* Timer interrupt handler. */
97 timer_interrupt (struct intr_frame *args UNUSED)
100 if (ticks % TIME_SLICE == 0)
101 intr_yield_on_return ();