1 #include "devices/timer.h"
6 #include "threads/interrupt.h"
7 #include "threads/io.h"
8 #include "threads/thread.h"
11 #error 8254 timer requires TIMER_FREQ >= 19
14 #error TIMER_FREQ <= 1000 recommended
17 /* Number of timer ticks that a process gets before being
21 /* Number of timer ticks since OS booted. */
22 static volatile int64_t ticks;
24 static intr_handler_func timer_interrupt;
26 /* Sets up the 8254 Programmable Interval Timer (PIT) to
27 interrupt PIT_FREQ times per second, and registers the
28 corresponding interrupt. */
32 /* 8254 input frequency divided by TIMER_FREQ, rounded to
34 uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
36 outb (0x43, 0x34); /* CW: counter 0, LSB then MSB, mode 2, binary. */
37 outb (0x40, count & 0xff);
38 outb (0x40, count >> 8);
40 intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
43 /* Returns the number of timer ticks since the OS booted. */
47 enum intr_level old_level = intr_disable ();
49 intr_set_level (old_level);
53 /* Returns the number of timer ticks elapsed since THEN, which
54 should be a value once returned by timer_ticks(). */
56 timer_elapsed (int64_t then)
58 return timer_ticks () - then;
61 /* Suspends execution for approximately TICKS timer ticks. */
63 timer_sleep (int64_t ticks)
65 int64_t start = timer_ticks ();
67 while (timer_elapsed (start) < ticks)
68 if (intr_get_level () == INTR_ON)
72 /* Returns MS milliseconds in timer ticks, rounding up. */
74 timer_ms2ticks (int64_t ms)
77 ------------------------ = MS * TIMER_FREQ / 1000 ticks.
78 (1 / TIMER_FREQ) ticks/s
80 return DIV_ROUND_UP (ms * TIMER_FREQ, 1000);
83 /* Returns US microseconds in timer ticks, rounding up. */
85 timer_us2ticks (int64_t us)
87 return DIV_ROUND_UP (us * TIMER_FREQ, 1000000);
90 /* Returns NS nanoseconds in timer ticks, rounding up. */
92 timer_ns2ticks (int64_t ns)
94 return DIV_ROUND_UP (ns * TIMER_FREQ, 1000000000);
97 /* Prints timer statistics. */
99 timer_print_stats (void)
101 printf ("Timer: %"PRId64" ticks.\n", ticks);
104 /* Timer interrupt handler. */
106 timer_interrupt (struct intr_frame *args UNUSED)
110 if (ticks % TIME_SLICE == 0)
111 intr_yield_on_return ();