1 #include "devices/timer.h"
6 #include "threads/interrupt.h"
7 #include "threads/io.h"
8 #include "threads/thread.h"
10 /* See [8254] for hardware details of the 8254 timer chip. */
13 #error 8254 timer requires TIMER_FREQ >= 19
16 #error TIMER_FREQ <= 1000 recommended
19 /* Number of timer ticks that a process gets before being
23 /* Number of timer ticks since OS booted. */
24 static volatile int64_t ticks;
26 static intr_handler_func timer_interrupt;
28 /* Sets up the 8254 Programmable Interval Timer (PIT) to
29 interrupt PIT_FREQ times per second, and registers the
30 corresponding interrupt. */
34 /* 8254 input frequency divided by TIMER_FREQ, rounded to
36 uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
38 outb (0x43, 0x34); /* CW: counter 0, LSB then MSB, mode 2, binary. */
39 outb (0x40, count & 0xff);
40 outb (0x40, count >> 8);
42 intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
45 /* Returns the number of timer ticks since the OS booted. */
49 enum intr_level old_level = intr_disable ();
51 intr_set_level (old_level);
55 /* Returns the number of timer ticks elapsed since THEN, which
56 should be a value once returned by timer_ticks(). */
58 timer_elapsed (int64_t then)
60 return timer_ticks () - then;
63 /* Suspends execution for approximately TICKS timer ticks. */
65 timer_sleep (int64_t ticks)
67 int64_t start = timer_ticks ();
69 ASSERT (intr_get_level () == INTR_ON);
70 while (timer_elapsed (start) < ticks)
74 /* Returns MS milliseconds in timer ticks, rounding up. */
76 timer_ms2ticks (int64_t ms)
79 ------------------------ = MS * TIMER_FREQ / 1000 ticks.
80 (1 / TIMER_FREQ) ticks/s
82 return DIV_ROUND_UP (ms * TIMER_FREQ, 1000);
85 /* Returns US microseconds in timer ticks, rounding up. */
87 timer_us2ticks (int64_t us)
89 return DIV_ROUND_UP (us * TIMER_FREQ, 1000000);
92 /* Returns NS nanoseconds in timer ticks, rounding up. */
94 timer_ns2ticks (int64_t ns)
96 return DIV_ROUND_UP (ns * TIMER_FREQ, 1000000000);
99 /* Prints timer statistics. */
101 timer_print_stats (void)
103 printf ("Timer: %"PRId64" ticks\n", ticks);
106 /* Timer interrupt handler. */
108 timer_interrupt (struct intr_frame *args UNUSED)
112 if (ticks % TIME_SLICE == 0)
113 intr_yield_on_return ();