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