Redo makefiles.
[pintos-anon] / src / devices / timer.c
1 #include "timer.h"
2 #include "lib/debug.h"
3 #include "threads/interrupt.h"
4 #include "threads/io.h"
5   
6 #if TIMER_FREQ < 19
7 #error 8254 timer requires TIMER_FREQ >= 19
8 #endif
9
10 /* Number of timer ticks since OS booted. */
11 static volatile int64_t ticks;
12
13 static intr_handler_func timer_interrupt;
14
15 /* Sets up the 8254 Programmable Interrupt Timer (PIT) to
16    interrupt PIT_FREQ times per second, and registers the
17    corresponding interrupt. */
18 void
19 timer_init (void) 
20 {
21   /* 8254 input frequency divided by TIMER_FREQ, rounded to
22      nearest. */
23   uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
24
25   outb (0x43, 0x34);    /* CW: counter 0, LSB then MSB, mode 2, binary. */
26   outb (0x40, count & 0xff);
27   outb (0x40, count >> 8);
28
29   intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
30 }
31
32 /* Returns the number of timer ticks since the OS booted. */
33 int64_t
34 timer_ticks (void) 
35 {
36   enum intr_level old_level = intr_disable ();
37   int64_t t = ticks;
38   intr_set_level (old_level);
39   return t;
40 }
41
42 /* Returns the number of timer ticks elapsed since THEN, which
43    should be a value once returned by timer_ticks(). */
44 int64_t
45 timer_elapsed (int64_t then) 
46 {
47   return timer_ticks () - then;
48 }
49
50 /* Suspends execution for approximately MS milliseconds. */
51 void
52 timer_msleep (int64_t ms) 
53 {
54   int64_t ticks = (int64_t) ms * TIMER_FREQ / 1000;
55   int64_t start = timer_ticks ();
56
57   while (timer_elapsed (start) < ticks) 
58     continue;
59 }
60
61 /* Suspends execution for approximately US microseconds.
62    Note: this is ridiculously inaccurate. */
63 void
64 timer_usleep (int64_t us) 
65 {
66   timer_msleep (us / 1000 + 1);
67 }
68
69 /* Suspends execution for approximately NS nanoseconds.
70    Note: this is ridiculously inaccurate. */
71 void
72 timer_nsleep (int64_t ns) 
73 {
74   timer_msleep (ns / 1000000 + 1);
75 }
76 \f
77 /* Timer interrupt handler. */
78 static void
79 timer_interrupt (struct intr_frame *args UNUSED)
80 {
81   ticks++;
82   intr_yield_on_return ();
83 }