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