Add timer_msleep, timer_usleep, timer_nsleep().
[pintos-anon] / src / devices / timer.c
1 #include "timer.h"
2 #include "debug.h"
3 #include "interrupt.h"
4 #include "io.h"
5   
6 #if TIMER_FREQ < 19
7 #error 8254 timer requires TIMER_FREQ >= 19
8 #endif
9
10 static volatile int64_t ticks;
11
12 static void
13 irq20_timer (struct intr_frame *args UNUSED)
14 {
15   ticks++;
16   intr_yield_on_return ();
17 }
18
19 /* Sets up the 8254 Programmable Interrupt Timer (PIT) to
20    interrupt PIT_FREQ times per second, and registers the
21    corresponding interrupt. */
22 void
23 timer_init (void) 
24 {
25   /* 8254 input frequency divided by TIMER_FREQ, rounded to
26      nearest. */
27   uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
28
29   outb (0x43, 0x34);    /* CW: counter 0, LSB then MSB, mode 2, binary. */
30   outb (0x40, count & 0xff);
31   outb (0x40, count >> 8);
32
33   intr_register (0x20, 0, IF_OFF, irq20_timer, "8254 Timer");
34 }
35
36 int64_t
37 timer_ticks (void) 
38 {
39   enum if_level old_level = intr_disable ();
40   int64_t t = ticks;
41   intr_set_level (old_level);
42   return t;
43 }
44
45 int64_t
46 timer_elapsed (int64_t then) 
47 {
48   return timer_ticks () - then;
49 }
50
51 /* Suspends execution for approximately DURATION milliseconds. */
52 void
53 timer_msleep (int64_t ms) 
54 {
55   int64_t ticks = (int64_t) ms * TIMER_FREQ / 1000;
56   int64_t start = timer_ticks ();
57
58   while (timer_elapsed (start) < ticks) 
59     continue;
60 }
61
62 void
63 timer_usleep (int64_t us) 
64 {
65   timer_msleep (us / 1000 + 1);
66 }
67
68 void
69 timer_nsleep (int64_t ns) 
70 {
71   timer_msleep (ns / 1000000 + 1);
72 }