1 diff -Nur ../../src/devices/timer.c src/devices/timer.c
2 --- ../../src/devices/timer.c 2008-08-27 08:04:38.000000000 -0400
3 +++ src/devices/timer.c 2008-08-27 12:42:33.000000000 -0400
5 Initialized by timer_calibrate(). */
6 static unsigned loops_per_tick;
8 +/* Threads waiting in timer_sleep(). */
9 +static struct list wait_list;
11 static intr_handler_func timer_interrupt;
12 static bool too_many_loops (unsigned loops);
13 static void busy_wait (int64_t loops);
15 outb (0x40, count >> 8);
17 intr_register_ext (0x20, timer_interrupt, "8254 Timer");
19 + list_init (&wait_list);
22 /* Calibrates loops_per_tick, used to implement brief delays. */
24 return timer_ticks () - then;
27 +/* Compares two threads based on their wake-up times. */
29 +compare_threads_by_wakeup_time (const struct list_elem *a_,
30 + const struct list_elem *b_,
33 + const struct thread *a = list_entry (a_, struct thread, timer_elem);
34 + const struct thread *b = list_entry (b_, struct thread, timer_elem);
36 + return a->wakeup_time < b->wakeup_time;
39 /* Sleeps for approximately TICKS timer ticks. Interrupts must
42 timer_sleep (int64_t ticks)
44 - int64_t start = timer_ticks ();
45 + struct thread *t = thread_current ();
47 + /* Schedule our wake-up time. */
48 + t->wakeup_time = timer_ticks () + ticks;
50 + /* Atomically insert the current thread into the wait list. */
51 ASSERT (intr_get_level () == INTR_ON);
52 - while (timer_elapsed (start) < ticks)
55 + list_insert_ordered (&wait_list, &t->timer_elem,
56 + compare_threads_by_wakeup_time, NULL);
60 + sema_down (&t->timer_sema);
63 /* Sleeps for approximately MS milliseconds. Interrupts must be
69 + while (!list_empty (&wait_list))
71 + struct thread *t = list_entry (list_front (&wait_list),
72 + struct thread, timer_elem);
73 + if (ticks < t->wakeup_time)
75 + sema_up (&t->timer_sema);
76 + thread_yield_to_higher_priority ();
77 + list_pop_front (&wait_list);
81 /* Returns true if LOOPS iterations waits for more than one timer
82 diff -Nur ../../src/threads/fixed-point.h src/threads/fixed-point.h
83 --- ../../src/threads/fixed-point.h 1969-12-31 19:00:00.000000000 -0500
84 +++ src/threads/fixed-point.h 2008-08-27 12:42:33.000000000 -0400
86 +#ifndef THREADS_FIXED_POINT_H
87 +#define THREADS_FIXED_POINT_H
92 +#define FIX_BITS 32 /* Total bits per fixed-point number. */
93 +#define FIX_P 16 /* Number of integer bits. */
94 +#define FIX_Q 16 /* Number of fractional bits. */
95 +#define FIX_F (1 << FIX_Q) /* pow(2, FIX_Q). */
97 +#define FIX_MIN_INT (-FIX_MAX_INT) /* Smallest representable integer. */
98 +#define FIX_MAX_INT ((1 << FIX_P) - 1) /* Largest representable integer. */
100 +/* A fixed-point number. */
107 +/* Returns a fixed-point number with F as its internal value. */
108 +static inline fixed_point_t
116 +/* Returns fixed-point number corresponding to integer N. */
117 +static inline fixed_point_t
120 + ASSERT (n >= FIX_MIN_INT && n <= FIX_MAX_INT);
121 + return __mk_fix (n * FIX_F);
124 +/* Returns fixed-point number corresponding to N divided by D. */
125 +static inline fixed_point_t
126 +fix_frac (int n, int d)
129 + ASSERT (n / d >= FIX_MIN_INT && n / d <= FIX_MAX_INT);
130 + return __mk_fix ((long long) n * FIX_F / d);
133 +/* Returns X rounded to the nearest integer. */
135 +fix_round (fixed_point_t x)
137 + return (x.f + FIX_F / 2) / FIX_F;
140 +/* Returns X truncated down to the nearest integer. */
142 +fix_trunc (fixed_point_t x)
144 + return x.f / FIX_F;
147 +/* Returns X + Y. */
148 +static inline fixed_point_t
149 +fix_add (fixed_point_t x, fixed_point_t y)
151 + return __mk_fix (x.f + y.f);
154 +/* Returns X - Y. */
155 +static inline fixed_point_t
156 +fix_sub (fixed_point_t x, fixed_point_t y)
158 + return __mk_fix (x.f - y.f);
161 +/* Returns X * Y. */
162 +static inline fixed_point_t
163 +fix_mul (fixed_point_t x, fixed_point_t y)
165 + return __mk_fix ((long long) x.f * y.f / FIX_F);
168 +/* Returns X * N. */
169 +static inline fixed_point_t
170 +fix_scale (fixed_point_t x, int n)
173 + return __mk_fix (x.f * n);
176 +/* Returns X / Y. */
177 +static inline fixed_point_t
178 +fix_div (fixed_point_t x, fixed_point_t y)
180 + return __mk_fix ((long long) x.f * FIX_F / y.f);
183 +/* Returns X / N. */
184 +static inline fixed_point_t
185 +fix_unscale (fixed_point_t x, int n)
188 + return __mk_fix (x.f / n);
191 +/* Returns 1 / X. */
192 +static inline fixed_point_t
193 +fix_inv (fixed_point_t x)
195 + return fix_div (fix_int (1), x);
198 +/* Returns -1 if X < Y, 0 if X == Y, 1 if X > Y. */
200 +fix_compare (fixed_point_t x, fixed_point_t y)
202 + return x.f < y.f ? -1 : x.f > y.f;
205 +#endif /* threads/fixed-point.h */
206 diff -Nur ../../src/threads/synch.c src/threads/synch.c
207 --- ../../src/threads/synch.c 2006-07-20 22:05:37.000000000 -0400
208 +++ src/threads/synch.c 2008-08-27 12:42:33.000000000 -0400
209 @@ -113,10 +113,28 @@
210 ASSERT (sema != NULL);
212 old_level = intr_disable ();
213 - if (!list_empty (&sema->waiters))
214 - thread_unblock (list_entry (list_pop_front (&sema->waiters),
215 - struct thread, elem));
217 + if (!list_empty (&sema->waiters))
219 + /* Find highest-priority waiting thread. */
220 + struct thread *max = list_entry (list_max (&sema->waiters,
221 + thread_lower_priority, NULL),
222 + struct thread, elem);
224 + /* Remove `max' from wait list and unblock. */
225 + list_remove (&max->elem);
226 + thread_unblock (max);
228 + /* Yield to a higher-priority thread, if we're running in a
229 + context where it makes sense to do so.
231 + Kind of a funny interaction with donation here.
232 + We only support donation for locks, and locks turn off
233 + interrupts before calling us, so we automatically don't
234 + do the yield here, delegating to lock_release(). */
235 + if (!intr_context () && old_level == INTR_ON)
236 + thread_yield_to_higher_priority ();
238 intr_set_level (old_level);
241 @@ -192,12 +210,33 @@
243 lock_acquire (struct lock *lock)
245 + enum intr_level old_level;
247 ASSERT (lock != NULL);
248 ASSERT (!intr_context ());
249 ASSERT (!lock_held_by_current_thread (lock));
251 + old_level = intr_disable ();
253 + if (lock->holder != NULL)
255 + /* Donate our priority to the thread holding the lock.
256 + First, update the data structures. */
257 + struct thread *donor = thread_current ();
258 + donor->want_lock = lock;
259 + donor->donee = lock->holder;
260 + list_push_back (&lock->holder->donors, &donor->donor_elem);
262 + /* Now implement the priority donation itself
263 + by recomputing the donee's priority
264 + and cascading the donation as far as necessary. */
265 + if (donor->donee != NULL)
266 + thread_recompute_priority (donor->donee);
269 sema_down (&lock->semaphore);
270 lock->holder = thread_current ();
271 + intr_set_level (old_level);
274 /* Tries to acquires LOCK and returns true if successful or false
275 @@ -228,11 +267,39 @@
277 lock_release (struct lock *lock)
279 + enum intr_level old_level;
280 + struct thread *t = thread_current ();
281 + struct list_elem *e;
283 ASSERT (lock != NULL);
284 ASSERT (lock_held_by_current_thread (lock));
286 + old_level = intr_disable ();
288 + /* Return donations to threads that want this lock. */
289 + for (e = list_begin (&t->donors); e != list_end (&t->donors); )
291 + struct thread *donor = list_entry (e, struct thread, donor_elem);
292 + if (donor->want_lock == lock)
294 + donor->donee = NULL;
295 + e = list_remove (e);
301 + /* Release lock. */
303 sema_up (&lock->semaphore);
305 + /* Recompute our priority based on our remaining donations,
306 + then yield to a higher-priority ready thread if one now
308 + thread_recompute_priority (t);
309 + thread_yield_to_higher_priority ();
311 + intr_set_level (old_level);
314 /* Returns true if the current thread holds LOCK, false
317 struct list_elem elem; /* List element. */
318 struct semaphore semaphore; /* This semaphore. */
319 + struct thread *thread; /* Thread. */
322 /* Initializes condition variable COND. A condition variable
323 @@ -295,12 +363,26 @@
324 ASSERT (lock_held_by_current_thread (lock));
326 sema_init (&waiter.semaphore, 0);
327 + waiter.thread = thread_current ();
328 list_push_back (&cond->waiters, &waiter.elem);
330 sema_down (&waiter.semaphore);
335 +semaphore_elem_lower_priority (const struct list_elem *a_,
336 + const struct list_elem *b_,
339 + const struct semaphore_elem *a
340 + = list_entry (a_, struct semaphore_elem, elem);
341 + const struct semaphore_elem *b
342 + = list_entry (b_, struct semaphore_elem, elem);
344 + return a->thread->priority < b->thread->priority;
347 /* If any threads are waiting on COND (protected by LOCK), then
348 this function signals one of them to wake up from its wait.
349 LOCK must be held before calling this function.
351 ASSERT (lock_held_by_current_thread (lock));
353 if (!list_empty (&cond->waiters))
354 - sema_up (&list_entry (list_pop_front (&cond->waiters),
355 - struct semaphore_elem, elem)->semaphore);
357 + struct list_elem *max
358 + = list_max (&cond->waiters, semaphore_elem_lower_priority, NULL);
360 + sema_up (&list_entry (max, struct semaphore_elem, elem)->semaphore);
364 /* Wakes up all threads, if any, waiting on COND (protected by
365 diff -Nur ../../src/threads/thread.c src/threads/thread.c
366 --- ../../src/threads/thread.c 2008-08-27 13:06:01.000000000 -0400
367 +++ src/threads/thread.c 2008-08-27 13:14:12.000000000 -0400
371 #include "threads/flags.h"
372 +#include "threads/init.h"
373 #include "threads/interrupt.h"
374 #include "threads/intr-stubs.h"
375 #include "threads/palloc.h"
376 #include "threads/switch.h"
377 #include "threads/synch.h"
378 +#include "devices/timer.h"
379 #include "threads/vaddr.h"
381 #include "userprog/process.h"
384 #define TIME_SLICE 4 /* # of timer ticks to give each thread. */
385 static unsigned thread_ticks; /* # of timer ticks since last yield. */
386 +static fixed_point_t load_avg; /* Load average. */
388 /* If false (default), use round-robin scheduler.
389 If true, use multi-level feedback queue scheduler.
391 lock_init (&tid_lock);
392 list_init (&ready_list);
393 list_init (&all_list);
394 + load_avg = fix_int (0);
396 /* Set up a thread structure for the running thread. */
397 initial_thread = running_thread ();
399 sema_down (&idle_started);
402 +/* Adjust recent CPU of a thread based on load factor
403 + and recompute its priority. */
405 +adjust_recent_cpu (struct thread *t, void *aux)
407 + fixed_point_t load_factor = *(fixed_point_t *)aux;
409 + t->recent_cpu = fix_add (fix_mul (load_factor, t->recent_cpu),
410 + fix_int (t->nice));
411 + thread_recompute_priority (t);
414 /* Called by the timer interrupt handler at each timer tick.
415 Thus, this function runs in an external interrupt context. */
421 - /* Enforce preemption. */
422 - if (++thread_ticks >= TIME_SLICE)
423 - intr_yield_on_return ();
426 + /* Update load average. */
427 + if (timer_ticks () % TIMER_FREQ == 0)
429 + size_t ready_threads = list_size (&ready_list);
430 + if (t != idle_thread)
433 + load_avg = fix_add (fix_mul (fix_frac (59, 60), load_avg),
434 + fix_mul (fix_frac (1, 60), fix_int (ready_threads)));
437 + /* Increment running process's recent_cpu. */
438 + if (t != idle_thread)
439 + t->recent_cpu = fix_add (t->recent_cpu, fix_int (1));
441 + /* Update recent_cpu and thread priorities once per second. */
442 + if (timer_ticks () % TIMER_FREQ == 0)
444 + fixed_point_t twice_load = fix_scale (load_avg, 2);
445 + fixed_point_t twice_load_plus_1 = fix_add (twice_load, fix_int (1));
446 + fixed_point_t load_factor = fix_div (twice_load, twice_load_plus_1);
448 + thread_foreach (adjust_recent_cpu, &load_factor);
452 + /* Switch threads if time slice has expired. */
453 + if (++thread_ticks >= TIME_SLICE)
456 + thread_recompute_priority (thread_current ());
457 + intr_yield_on_return ();
461 /* Prints thread statistics. */
462 @@ -166,11 +214,12 @@
463 thread_create (const char *name, int priority,
464 thread_func *function, void *aux)
466 + struct thread *cur = thread_current ();
468 struct kernel_thread_frame *kf;
469 struct switch_entry_frame *ef;
470 struct switch_threads_frame *sf;
473 ASSERT (function != NULL);
478 /* Initialize thread. */
479 - init_thread (t, name, priority);
480 + init_thread (t, name, thread_mlfqs ? cur->priority : priority);
481 tid = t->tid = allocate_tid ();
482 + t->nice = cur->nice;
483 + t->recent_cpu = cur->recent_cpu;
485 /* Prepare thread for first run by initializing its stack.
486 Do this atomically so intermediate values for the 'stack'
489 /* Add to run queue. */
491 + if (priority > thread_get_priority ())
500 +/* Returns true if A has lower priority than B,
501 + within a list of threads. */
503 +thread_lower_priority (const struct list_elem *a_,
504 + const struct list_elem *b_,
507 + const struct thread *a = list_entry (a_, struct thread, elem);
508 + const struct thread *b = list_entry (b_, struct thread, elem);
510 + return a->priority < b->priority;
513 /* Transitions a blocked thread T to the ready-to-run state.
514 This is an error if T is not blocked. (Use thread_yield() to
515 make the running thread ready.)
516 @@ -339,11 +405,26 @@
520 -/* Sets the current thread's priority to NEW_PRIORITY. */
522 +recompute_priority_chain (void)
524 + enum intr_level old_level = intr_disable ();
525 + thread_recompute_priority (thread_current ());
526 + thread_yield_to_higher_priority ();
527 + intr_set_level (old_level);
530 +/* Sets the current thread's priority to PRIORITY. */
532 -thread_set_priority (int new_priority)
533 +thread_set_priority (int priority)
535 - thread_current ()->priority = new_priority;
538 + struct thread *t = thread_current ();
540 + t->normal_priority = priority;
541 + recompute_priority_chain ();
545 /* Returns the current thread's priority. */
546 @@ -355,33 +436,98 @@
548 /* Sets the current thread's nice value to NICE. */
550 -thread_set_nice (int nice UNUSED)
551 +thread_set_nice (int nice)
553 - /* Not yet implemented. */
554 + thread_current ()->nice = nice;
555 + recompute_priority_chain ();
558 /* Returns the current thread's nice value. */
560 thread_get_nice (void)
562 - /* Not yet implemented. */
564 + return thread_current ()->nice;
567 -/* Returns 100 times the system load average. */
569 thread_get_load_avg (void)
571 - /* Not yet implemented. */
574 + enum intr_level level = intr_disable ();
575 + load_avg_int = fix_round (fix_scale (load_avg, 100));
576 + intr_set_level (level);
577 + return load_avg_int;
580 -/* Returns 100 times the current thread's recent_cpu value. */
582 thread_get_recent_cpu (void)
584 - /* Not yet implemented. */
586 + int recent_cpu_int;
587 + enum intr_level level = intr_disable ();
588 + recent_cpu_int = fix_round (fix_scale (thread_current ()->recent_cpu, 100));
589 + intr_set_level (level);
590 + return recent_cpu_int;
593 +/* Returns true if thread A has lower priority than thread B,
594 + within a list of donors. */
596 +donated_lower_priority (const struct list_elem *a_,
597 + const struct list_elem *b_,
600 + const struct thread *a = list_entry (a_, struct thread, donor_elem);
601 + const struct thread *b = list_entry (b_, struct thread, donor_elem);
603 + return a->priority < b->priority;
606 +/* Recomputes T's priority in terms of its normal priority and
607 + its donors' priorities, if any,
608 + and cascades the donation as necessary. */
610 +thread_recompute_priority (struct thread *t)
612 + int old_priority = t->priority;
613 + int default_priority = t->normal_priority;
614 + int donation = PRI_MIN;
617 + default_priority = PRI_MAX - fix_round (t->recent_cpu) / 4 - t->nice * 2;
618 + if (default_priority < PRI_MIN)
619 + default_priority = PRI_MIN;
620 + else if (default_priority > PRI_MAX)
621 + default_priority = PRI_MAX;
623 + if (!list_empty (&t->donors))
624 + donation = list_entry (list_max (&t->donors, donated_lower_priority, NULL),
625 + struct thread, donor_elem)->priority;
626 + t->priority = donation > default_priority ? donation : default_priority;
627 + if (t->priority > old_priority && t->donee != NULL)
628 + thread_recompute_priority (t->donee);
631 +/* If the ready list contains a thread with a higher priority,
634 +thread_yield_to_higher_priority (void)
636 + enum intr_level old_level = intr_disable ();
637 + if (!list_empty (&ready_list))
639 + struct thread *cur = thread_current ();
640 + struct thread *max = list_entry (list_max (&ready_list,
641 + thread_lower_priority, NULL),
642 + struct thread, elem);
643 + if (max->priority > cur->priority)
645 + if (intr_context ())
646 + intr_yield_on_return ();
651 + intr_set_level (old_level);
654 /* Idle thread. Executes when no other thread is ready to run.
655 @@ -467,11 +613,13 @@
656 t->status = THREAD_BLOCKED;
657 strlcpy (t->name, name, sizeof t->name);
658 t->stack = (uint8_t *) t + PGSIZE;
659 - t->priority = priority;
660 + t->priority = t->normal_priority = priority;
661 t->magic = THREAD_MAGIC;
662 + sema_init (&t->timer_sema, 0);
663 + list_init (&t->donors);
665 old_level = intr_disable ();
666 list_push_back (&all_list, &t->allelem);
667 intr_set_level (old_level);
672 if (list_empty (&ready_list))
675 - return list_entry (list_pop_front (&ready_list), struct thread, elem);
679 + = list_entry (list_max (&ready_list, thread_lower_priority, NULL),
680 + struct thread, elem);
681 + list_remove (&max->elem);
686 /* Completes a thread switch by activating the new thread's page
687 diff -Nur ../../src/threads/thread.h src/threads/thread.h
688 --- ../../src/threads/thread.h 2008-08-27 08:45:26.000000000 -0400
689 +++ src/threads/thread.h 2008-08-27 12:45:31.000000000 -0400
694 +#include "threads/synch.h"
695 +#include "threads/fixed-point.h"
697 /* States in a thread's life cycle. */
700 enum thread_status status; /* Thread state. */
701 char name[16]; /* Name (for debugging purposes). */
702 uint8_t *stack; /* Saved stack pointer. */
703 - int priority; /* Priority. */
705 + /* Scheduler data. */
706 + int priority; /* Priority, including donations. */
707 + int normal_priority; /* Priority, without donations. */
708 + struct list donors; /* Threads donating priority to us. */
709 + struct list_elem donor_elem; /* Element in donors list. */
710 + struct thread *donee; /* Thread we're donating to. */
711 + struct lock *want_lock; /* Lock we're waiting to acquire. */
712 + int nice; /* Niceness. */
713 + fixed_point_t recent_cpu; /* Recent amount of CPU time. */
714 struct list_elem allelem; /* List element for all threads list. */
716 /* Shared between thread.c and synch.c. */
717 struct list_elem elem; /* List element. */
720 + int64_t wakeup_time; /* Time to wake this thread up. */
721 + struct list_elem timer_elem; /* Element in wait_list. */
722 + struct semaphore timer_sema; /* Semaphore. */
725 /* Owned by userprog/process.c. */
726 uint32_t *pagedir; /* Page directory. */
729 void thread_exit (void) NO_RETURN;
730 void thread_yield (void);
731 +void thread_yield_to_higher_priority (void);
732 +void thread_recompute_priority (struct thread *);
733 +bool thread_lower_priority (const struct list_elem *, const struct list_elem *,
736 /* Performs some operation on thread t, given auxiliary data AUX. */
737 typedef void thread_action_func (struct thread *t, void *aux);