Add timer_sleep() that takes an argument in timer ticks.
[pintos-anon] / src / devices / timer.c
index 4271c7354a86b6bf153045cad2666c5e2855faa5..8f4838f048e04ec80d0060fc10cd1a3d77da3216 100644 (file)
@@ -1,20 +1,24 @@
-#include "timer.h"
-#include "debug.h"
-#include "interrupt.h"
-#include "io.h"
+#include "devices/timer.h"
+#include <debug.h>
+#include <round.h>
+#include "threads/interrupt.h"
+#include "threads/io.h"
   
 #if TIMER_FREQ < 19
 #error 8254 timer requires TIMER_FREQ >= 19
 #endif
+#if TIMER_FREQ > 1000
+#error TIMER_FREQ <= 1000 recommended
+#endif
+
+/* Number of timer ticks that a process gets before being
+   preempted. */
+#define TIME_SLICE 1
 
+/* Number of timer ticks since OS booted. */
 static volatile int64_t ticks;
 
-static void
-irq20_timer (struct intr_frame *args UNUSED)
-{
-  ticks++;
-  intr_yield_on_return ();
-}
+static intr_handler_func timer_interrupt;
 
 /* Sets up the 8254 Programmable Interrupt Timer (PIT) to
    interrupt PIT_FREQ times per second, and registers the
@@ -30,9 +34,10 @@ timer_init (void)
   outb (0x40, count & 0xff);
   outb (0x40, count >> 8);
 
-  intr_register (0x20, 0, INTR_OFF, irq20_timer, "8254 Timer");
+  intr_register (0x20, 0, INTR_OFF, timer_interrupt, "8254 Timer");
 }
 
+/* Returns the number of timer ticks since the OS booted. */
 int64_t
 timer_ticks (void) 
 {
@@ -42,31 +47,54 @@ timer_ticks (void)
   return t;
 }
 
+/* Returns the number of timer ticks elapsed since THEN, which
+   should be a value once returned by timer_ticks(). */
 int64_t
 timer_elapsed (int64_t then) 
 {
   return timer_ticks () - then;
 }
 
-/* Suspends execution for approximately DURATION milliseconds. */
+/* Suspends executions for approximately TICKS timer ticks. */
 void
-timer_msleep (int64_t ms) 
+timer_sleep (int64_t ticks) 
 {
-  int64_t ticks = (int64_t) ms * TIMER_FREQ / 1000;
   int64_t start = timer_ticks ();
 
   while (timer_elapsed (start) < ticks) 
     continue;
 }
 
-void
-timer_usleep (int64_t us) 
+/* Returns MS milliseconds in timer ticks, rounding up. */
+int64_t
+timer_ms2ticks (int64_t ms) 
 {
-  timer_msleep (us / 1000 + 1);
+  /*       MS / 1000 s          
+     ------------------------ = MS * TIMER_FREQ / 1000 ticks. 
+     (1 / TIMER_FREQ) ticks/s
+  */
+  return DIV_ROUND_UP (ms * TIMER_FREQ, 1000);
 }
 
-void
-timer_nsleep (int64_t ns) 
+/* Returns US microseconds in timer ticks, rounding up. */
+int64_t
+timer_us2ticks (int64_t us) 
+{
+  return DIV_ROUND_UP (us * TIMER_FREQ, 1000000);
+}
+
+/* Returns NS nanoseconds in timer ticks, rounding up. */
+int64_t
+timer_ns2ticks (int64_t ns) 
 {
-  timer_msleep (ns / 1000000 + 1);
+  return DIV_ROUND_UP (ns * TIMER_FREQ, 1000000000);
+}
+\f
+/* Timer interrupt handler. */
+static void
+timer_interrupt (struct intr_frame *args UNUSED)
+{
+  ticks++;
+  if (ticks % TIME_SLICE == 0)
+    intr_yield_on_return ();
 }