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