X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=src%2Fdevices%2Ftimer.c;h=9c611a1d3eda68b6fd2317304faaef9381f9eb40;hb=231f9a0dc4528a081b0295d98d732d4de74a47b2;hp=85bc3ee33d3345fa519f6d3cbd80c1011aee01e1;hpb=f6580e9ad405b519dbe85027691bf3c66074b0a4;p=pintos-anon diff --git a/src/devices/timer.c b/src/devices/timer.c index 85bc3ee..9c611a1 100644 --- a/src/devices/timer.c +++ b/src/devices/timer.c @@ -1,18 +1,27 @@ -#include "timer.h" -#include "lib/debug.h" +#include "devices/timer.h" +#include +#include #include "threads/interrupt.h" #include "threads/io.h" +#include "threads/thread.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 intr_handler_func timer_interrupt; -/* Sets up the 8254 Programmable Interrupt Timer (PIT) to +/* Sets up the 8254 Programmable Interval Timer (PIT) to interrupt PIT_FREQ times per second, and registers the corresponding interrupt. */ void @@ -47,31 +56,40 @@ timer_elapsed (int64_t then) return timer_ticks () - then; } -/* Suspends execution for approximately MS milliseconds. */ +/* Suspends execution 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; + if (intr_get_level () == INTR_ON) + thread_yield (); } -/* Suspends execution for approximately US microseconds. - Note: this is ridiculously inaccurate. */ -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); } -/* Suspends execution for approximately NS nanoseconds. - Note: this is ridiculously inaccurate. */ -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); } /* Timer interrupt handler. */ @@ -79,5 +97,6 @@ static void timer_interrupt (struct intr_frame *args UNUSED) { ticks++; - intr_yield_on_return (); + if (ticks % TIME_SLICE == 0) + intr_yield_on_return (); }