Support accurate short delays in the timer code, to speed up disk
[pintos-anon] / src / devices / timer.c
1 #include "devices/timer.h"
2 #include <debug.h>
3 #include <inttypes.h>
4 #include <round.h>
5 #include <stdio.h>
6 #include "threads/interrupt.h"
7 #include "threads/io.h"
8 #include "threads/thread.h"
9   
10 /* See [8254] for hardware details of the 8254 timer chip. */
11
12 #if TIMER_FREQ < 19
13 #error 8254 timer requires TIMER_FREQ >= 19
14 #endif
15 #if TIMER_FREQ > 1000
16 #error TIMER_FREQ <= 1000 recommended
17 #endif
18
19 /* Number of timer ticks that a process gets before being
20    preempted. */
21 #define TIME_SLICE 1
22
23 /* Number of timer ticks since OS booted. */
24 static volatile int64_t ticks;
25
26 /* Number of loops per timer tick.
27    Initialized by timer_calibrate(). */
28 static unsigned loops_per_tick;
29
30 static intr_handler_func timer_interrupt;
31 static bool too_many_loops (unsigned loops);
32 static void busy_wait (int64_t loops);
33 static void real_time_sleep (int64_t num, int32_t denom);
34
35 /* Sets up the 8254 Programmable Interval Timer (PIT) to
36    interrupt PIT_FREQ times per second, and registers the
37    corresponding interrupt. */
38 void
39 timer_init (void) 
40 {
41   /* 8254 input frequency divided by TIMER_FREQ, rounded to
42      nearest. */
43   uint16_t count = (1193180 + TIMER_FREQ / 2) / TIMER_FREQ;
44
45   outb (0x43, 0x34);    /* CW: counter 0, LSB then MSB, mode 2, binary. */
46   outb (0x40, count & 0xff);
47   outb (0x40, count >> 8);
48
49   intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
50 }
51
52 /* Calibrates loops_per_tick, used to implement brief delays. */
53 void
54 timer_calibrate (void) 
55 {
56   unsigned high_bit, test_bit;
57
58   ASSERT (intr_get_level () == INTR_ON);
59   printf ("Calibrating timer...  ");
60
61   /* Approximate loops_per_tick as the largest power-of-two
62      still less than one timer tick. */
63   loops_per_tick = 1u << 10;
64   while (!too_many_loops (loops_per_tick << 1))
65     loops_per_tick <<= 1;
66
67   /* Refine the next 8 bits of loops_per_tick. */
68   high_bit = loops_per_tick;
69   for (test_bit = high_bit >> 1; test_bit != high_bit >> 10; test_bit >>= 1)
70     if (!too_many_loops (high_bit | test_bit))
71       loops_per_tick |= test_bit;
72
73   printf ("%'"PRIu64" loops/s.\n", (uint64_t) loops_per_tick * TIMER_FREQ);
74 }
75
76 /* Returns the number of timer ticks since the OS booted. */
77 int64_t
78 timer_ticks (void) 
79 {
80   enum intr_level old_level = intr_disable ();
81   int64_t t = ticks;
82   intr_set_level (old_level);
83   return t;
84 }
85
86 /* Returns the number of timer ticks elapsed since THEN, which
87    should be a value once returned by timer_ticks(). */
88 int64_t
89 timer_elapsed (int64_t then) 
90 {
91   return timer_ticks () - then;
92 }
93
94 /* Suspends execution for approximately TICKS timer ticks. */
95 void
96 timer_sleep (int64_t ticks) 
97 {
98   int64_t start = timer_ticks ();
99
100   ASSERT (intr_get_level () == INTR_ON);
101   while (timer_elapsed (start) < ticks) 
102     thread_yield ();
103 }
104
105 /* Suspends execution for approximately MS milliseconds. */
106 void
107 timer_msleep (int64_t ms) 
108 {
109   real_time_sleep (ms, 1000);
110 }
111
112 /* Suspends execution for approximately US microseconds. */
113 void
114 timer_usleep (int64_t us) 
115 {
116   real_time_sleep (us, 1000 * 1000);
117 }
118
119 /* Suspends execution for approximately NS nanoseconds. */
120 void
121 timer_nsleep (int64_t ns) 
122 {
123   real_time_sleep (ns, 1000 * 1000 * 1000);
124 }
125
126 /* Prints timer statistics. */
127 void
128 timer_print_stats (void) 
129 {
130   printf ("Timer: %"PRId64" ticks\n", ticks);
131 }
132 \f
133 /* Timer interrupt handler. */
134 static void
135 timer_interrupt (struct intr_frame *args UNUSED)
136 {
137   ticks++;
138   thread_tick ();
139   if (ticks % TIME_SLICE == 0)
140     intr_yield_on_return ();
141 }
142
143 /* Returns true if LOOPS iterations waits for more than one timer
144    tick, otherwise false. */
145 static bool
146 too_many_loops (unsigned loops) 
147 {
148   int64_t start;
149
150   /* Wait for a timer tick. */
151   start = ticks;
152   while (ticks == start)
153     continue;
154
155   /* Run LOOPS loops. */
156   start = ticks;
157   busy_wait (loops);
158
159   /* If the tick count changed, we iterated too long. */
160   return start != ticks;
161 }
162
163 /* Iterates through a simple loop LOOPS times, for implementing
164    brief delays.
165
166    Marked NO_INLINE because code alignment can significantly
167    affect timings, so that if this function was inlined
168    differently in different places the results would be difficult
169    to predict. */
170 static void NO_INLINE
171 busy_wait (int64_t loops) 
172 {
173   while (loops-- > 0)
174     continue;
175 }
176
177 /* Sleep for approximately NUM/DENOM seconds. */
178 static void
179 real_time_sleep (int64_t num, int32_t denom) 
180 {
181   /* Convert NUM/DENOM seconds into timer ticks, rounding down.
182           
183         (NUM / DENOM) s          
184      ---------------------- = NUM * TIMER_FREQ / DENOM ticks. 
185      1 s / TIMER_FREQ ticks
186   */
187   int64_t ticks = num * TIMER_FREQ / denom;
188
189   ASSERT (intr_get_level () == INTR_ON);
190   if (ticks > 0)
191     {
192       /* We're waiting for at least one full timer tick.  Use
193          timer_sleep() because it will yield the CPU to other
194          processes. */                
195       timer_sleep (ticks); 
196     }
197   else 
198     {
199       /* Otherwise, use a busy-wait loop for more accurate
200          sub-tick timing.  We scale the numerator and denominator
201          down by 1000 to avoid the possibility of overflow. */
202       ASSERT (denom % 1000 == 0);
203       busy_wait (loops_per_tick * num / 1000 * TIMER_FREQ / (denom / 1000)); 
204     }
205 }
206