- moved all instructions that related to local CVS/group setup in localcvsinstruction...
[pintos.git] / doc / threads.texi
blob6eec6bb1ea5a44d1620b04faf8108b879d7ad5f1
1 @node Project 1--Threads
2 @chapter Project 1: Threads
4 In this assignment, we give you a minimally functional thread system.
5 Your job is to extend the functionality of this system to gain a
6 better understanding of synchronization problems.
8 You will be working primarily in the @file{threads} directory for
9 this assignment, with some work in the @file{devices} directory on the
10 side.  Compilation should be done in the @file{threads} directory.
12 Before you read the description of this project, you should read all of
13 the following sections: @ref{Introduction}, @ref{Coding Standards},
14 @ref{Debugging Tools}, and @ref{Development Tools}.  You should at least
15 skim the material from @ref{Pintos Loading} through @ref{Memory
16 Allocation}, especially @ref{Synchronization}.  To complete this project
17 you will also need to read @ref{4.4BSD Scheduler}.
19 @menu
20 * Project 1 Background::        
21 * Project 1 Requirements::      
22 * Project 1 FAQ::               
23 @end menu
25 @node Project 1 Background
26 @section Background
29 @menu
30 * Understanding Threads::       
31 * Project 1 Source Files::      
32 * Project 1 Synchronization::   
33 * Development Suggestions::     
34 @end menu
36 @node Understanding Threads
37 @subsection Understanding Threads
39 The first step is to read and understand the code for the initial thread
40 system.
41 Pintos already implements thread creation and thread completion,
42 a simple scheduler to switch between threads, and synchronization
43 primitives (semaphores, locks, condition variables, and optimization
44 barriers).
46 Some of this code might seem slightly mysterious.  If
47 you haven't already compiled and run the base system, as described in
48 the introduction (@pxref{Introduction}), you should do so now.  You
49 can read through parts of the source code to see what's going
50 on.  If you like, you can add calls to @func{printf} almost
51 anywhere, then recompile and run to see what happens and in what
52 order.  You can also run the kernel in a debugger and set breakpoints
53 at interesting spots, single-step through code and examine data, and
54 so on.
56 When a thread is created, you are creating a new context to be
57 scheduled.  You provide a function to be run in this context as an
58 argument to @func{thread_create}.  The first time the thread is
59 scheduled and runs, it starts from the beginning of that function
60 and executes in that context.  When the function returns, the thread
61 terminates.  Each thread, therefore, acts like a mini-program running
62 inside Pintos, with the function passed to @func{thread_create}
63 acting like @func{main}.
65 At any given time, exactly one thread runs and the rest, if any,
66 become inactive.  The scheduler decides which thread to
67 run next.  (If no thread is ready to run
68 at any given time, then the special ``idle'' thread, implemented in
69 @func{idle}, runs.)
70 Synchronization primitives can force context switches when one
71 thread needs to wait for another thread to do something.
73 The mechanics of a context switch are
74 in @file{threads/switch.S}, which is 80@var{x}86
75 assembly code.  (You don't have to understand it.)  It saves the
76 state of the currently running thread and restores the state of the
77 thread we're switching to.
79 Using the GDB debugger, slowly trace through a context
80 switch to see what happens (@pxref{GDB}).  You can set a
81 breakpoint on @func{schedule} to start out, and then
82 single-step from there.@footnote{GDB might tell you that
83 @func{schedule} doesn't exist, which is arguably a GDB bug.
84 You can work around this by setting the breakpoint by filename and
85 line number, e.g.@: @code{break thread.c:@var{ln}} where @var{ln} is
86 the line number of the first declaration in @func{schedule}.}  Be sure
87 to keep track of each thread's address
88 and state, and what procedures are on the call stack for each thread.
89 You will notice that when one thread calls @func{switch_threads},
90 another thread starts running, and the first thing the new thread does
91 is to return from @func{switch_threads}.  You will understand the thread
92 system once you understand why and how the @func{switch_threads} that
93 gets called is different from the @func{switch_threads} that returns.
94 @xref{Thread Switching}, for more information.
96 @strong{Warning}: In Pintos, each thread is assigned a small,
97 fixed-size execution stack just under @w{4 kB} in size.  The kernel
98 tries to detect stack overflow, but it cannot do so perfectly.  You
99 may cause bizarre problems, such as mysterious kernel panics, if you
100 declare large data structures as non-static local variables,
101 e.g. @samp{int buf[1000];}.  Alternatives to stack allocation include
102 the page allocator and the block allocator (@pxref{Memory Allocation}).
104 @node Project 1 Source Files
105 @subsection Source Files
107 Here is a brief overview of the files in the @file{threads}
108 directory.  You will not need to modify most of this code, but the
109 hope is that presenting this overview will give you a start on what
110 code to look at.
112 @table @file
113 @item loader.S
114 @itemx loader.h
115 The kernel loader.  Assembles to 512 bytes of code and data that the
116 PC BIOS loads into memory and which in turn loads the kernel into
117 memory, does basic processor initialization, and jumps to the
118 beginning of the kernel.  @xref{Pintos Loader}, for details. You should
119 not need to look at this code or modify it.
121 @item kernel.lds.S
122 The linker script used to link the kernel.  Sets the load address of
123 the kernel and arranges for @file{start.S} to be at the very beginning
124 of the kernel image.  @xref{Pintos Loader}, for details. Again, you
125 should not need to look at this code
126 or modify it, but it's here in case you're curious.
128 @item start.S
129 Jumps to @func{main}.
131 @item init.c
132 @itemx init.h
133 Kernel initialization, including @func{main}, the kernel's ``main
134 program.''  You should look over @func{main} at least to see what
135 gets initialized.  You might want to add your own initialization code
136 here.  @xref{Kernel Initialization}, for details.
138 @item thread.c
139 @itemx thread.h
140 Basic thread support.  Much of your work will take place in these files.
141 @file{thread.h} defines @struct{thread}, which you are likely to modify
142 in all four projects.  See @ref{struct thread} and @ref{Threads} for
143 more information.
145 @item switch.S
146 @itemx switch.h
147 Assembly language routine for switching threads.  Already discussed
148 above.  @xref{Thread Functions}, for more information.
150 @item palloc.c
151 @itemx palloc.h
152 Page allocator, which hands out system memory in multiples of 4 kB
153 pages.  @xref{Page Allocator}, for more information.
155 @item malloc.c
156 @itemx malloc.h
157 A simple implementation of @func{malloc} and @func{free} for
158 the kernel.  @xref{Block Allocator}, for more information.
160 @item interrupt.c
161 @itemx interrupt.h
162 Basic interrupt handling and functions for turning interrupts on and
163 off.  @xref{Interrupt Handling}, for more information.
165 @item intr-stubs.S
166 @itemx intr-stubs.h
167 Assembly code for low-level interrupt handling.  @xref{Interrupt
168 Infrastructure}, for more information.
170 @item synch.c
171 @itemx synch.h
172 Basic synchronization primitives: semaphores, locks, condition
173 variables, and optimization barriers.  You will need to use these for
174 synchronization in all
175 four projects.  @xref{Synchronization}, for more information.
177 @item io.h
178 Functions for I/O port access.  This is mostly used by source code in
179 the @file{devices} directory that you won't have to touch.
181 @item vaddr.h
182 @itemx pte.h
183 Functions and macros for working with virtual addresses and page table
184 entries.  These will be more important to you in project 3.  For now,
185 you can ignore them.
187 @item flags.h
188 Macros that define a few bits in the 80@var{x}86 ``flags'' register.
189 Probably of no interest.  See @bibref{IA32-v1}, section 3.4.3, ``EFLAGS
190 Register,'' for more information.
191 @end table
193 @menu
194 * devices code::                
195 * lib files::                   
196 @end menu
198 @node devices code
199 @subsubsection @file{devices} code
201 The basic threaded kernel also includes these files in the
202 @file{devices} directory:
204 @table @file
205 @item timer.c
206 @itemx timer.h
207 System timer that ticks, by default, 100 times per second.  You will
208 modify this code in this project.
210 @item vga.c
211 @itemx vga.h
212 VGA display driver.  Responsible for writing text to the screen.
213 You should have no need to look at this code.  @func{printf}
214 calls into the VGA display driver for you, so there's little reason to
215 call this code yourself.
217 @item serial.c
218 @itemx serial.h
219 Serial port driver.  Again, @func{printf} calls this code for you,
220 so you don't need to do so yourself.
221 It handles serial input by passing it to the input layer (see below).
223 @item disk.c
224 @itemx disk.h
225 Supports reading and writing sectors on up to 4 IDE disks.  This won't
226 actually be used until project 2.
228 @item kbd.c
229 @itemx kbd.h
230 Keyboard driver.  Handles keystrokes passing them to the input layer
231 (see below).
233 @item input.c
234 @itemx input.h
235 Input layer.  Queues input characters passed along by the keyboard or
236 serial drivers.
238 @item intq.c
239 @itemx intq.h
240 Interrupt queue, for managing a circular queue that both kernel
241 threads and interrupt handlers want to access.  Used by the keyboard
242 and serial drivers.
243 @end table
245 @node lib files
246 @subsubsection @file{lib} files
248 Finally, @file{lib} and @file{lib/kernel} contain useful library
249 routines.  (@file{lib/user} will be used by user programs, starting in
250 project 2, but it is not part of the kernel.)  Here's a few more
251 details:
253 @table @file
254 @item ctype.h
255 @itemx inttypes.h
256 @itemx limits.h
257 @itemx stdarg.h
258 @itemx stdbool.h
259 @itemx stddef.h
260 @itemx stdint.h
261 @itemx stdio.c
262 @itemx stdio.h
263 @itemx stdlib.c
264 @itemx stdlib.h
265 @itemx string.c
266 @itemx string.h
267 A subset of the standard C library.  @xref{C99}, for
268 information
269 on a few recently introduced pieces of the C library that you might
270 not have encountered before.  @xref{Unsafe String Functions}, for
271 information on what's been intentionally left out for safety.
273 @item debug.c
274 @itemx debug.h
275 Functions and macros to aid debugging.  @xref{Debugging Tools}, for
276 more information.
278 @item random.c
279 @itemx random.h
280 Pseudo-random number generator.
282 @item round.h
283 Macros for rounding.
285 @item syscall-nr.h
286 System call numbers.  Not used until project 2.
288 @item kernel/list.c
289 @itemx kernel/list.h
290 Doubly linked list implementation.  Used all over the Pintos code, and
291 you'll probably want to use it a few places yourself in project 1.
293 @item kernel/bitmap.c
294 @itemx kernel/bitmap.h
295 Bitmap implementation.  You can use this in your code if you like, but
296 you probably won't have any need for it in project 1.
298 @item kernel/hash.c
299 @itemx kernel/hash.h
300 Hash table implementation.  Likely to come in handy for project 3.
302 @item kernel/console.c
303 @itemx kernel/console.h
304 @item kernel/stdio.h
305 Implements @func{printf} and a few other functions.
306 @end table
308 @node Project 1 Synchronization
309 @subsection Synchronization
311 Proper synchronization is an important part of the solutions to these
312 problems.  Any synchronization problem can be easily solved by turning
313 interrupts off: while interrupts are off, there is no concurrency, so
314 there's no possibility for race conditions.  Therefore, it's tempting to
315 solve all synchronization problems this way, but @strong{don't}.
316 Instead, use semaphores, locks, and condition variables to solve the
317 bulk of your synchronization problems.  Read the tour section on
318 synchronization (@pxref{Synchronization}) or the comments in
319 @file{threads/synch.c} if you're unsure what synchronization primitives
320 may be used in what situations.
322 In the Pintos projects, the only class of problem best solved by
323 disabling interrupts is coordinating data shared between a kernel thread
324 and an interrupt handler.  Because interrupt handlers can't sleep, they
325 can't acquire locks.  This means that data shared between kernel threads
326 and an interrupt handler must be protected within a kernel thread by
327 turning off interrupts.
329 This project only requires accessing a little bit of thread state from
330 interrupt handlers.  For the alarm clock, the timer interrupt needs to
331 wake up sleeping threads.  In the advanced scheduler, the timer
332 interrupt needs to access a few global and per-thread variables.  When
333 you access these variables from kernel threads, you will need to disable
334 interrupts to prevent the timer interrupt from interfering.
336 When you do turn off interrupts, take care to do so for the least amount
337 of code possible, or you can end up losing important things such as
338 timer ticks or input events.  Turning off interrupts also increases the
339 interrupt handling latency, which can make a machine feel sluggish if
340 taken too far.
342 The synchronization primitives themselves in @file{synch.c} are
343 implemented by disabling interrupts.  You may need to increase the
344 amount of code that runs with interrupts disabled here, but you should
345 still try to keep it to a minimum.
347 Disabling interrupts can be useful for debugging, if you want to make
348 sure that a section of code is not interrupted.  You should remove
349 debugging code before turning in your project.  (Don't just comment it
350 out, because that can make the code difficult to read.)
352 There should be no busy waiting in your submission.  A tight loop that
353 calls @func{thread_yield} is one form of busy waiting.
355 @node Development Suggestions
356 @subsection Development Suggestions
358 In the past, many groups divided the assignment into pieces, then each
359 group member worked on his or her piece until just before the
360 deadline, at which time the group reconvened to combine their code and
361 submit.  @strong{This is a bad idea.  We do not recommend this
362 approach.}  Groups that do this often find that two changes conflict
363 with each other, requiring lots of last-minute debugging.  Some groups
364 who have done this have turned in code that did not even compile or
365 boot, much less pass any tests.
367 @localcvspolicy{}
369 You should expect to run into bugs that you simply don't understand
370 while working on this and subsequent projects.  When you do,
371 reread the appendix on debugging tools, which is filled with
372 useful debugging tips that should help you to get back up to speed
373 (@pxref{Debugging Tools}).  Be sure to read the section on backtraces
374 (@pxref{Backtraces}), which will help you to get the most out of every
375 kernel panic or assertion failure.
377 @node Project 1 Requirements
378 @section Requirements
380 @menu
381 * Project 1 Design Document::   
382 * Alarm Clock::                 
383 * Priority Scheduling::         
384 * Advanced Scheduler::          
385 @end menu
387 @node Project 1 Design Document
388 @subsection Design Document
390 Before you turn in your project, you must copy @uref{threads.tmpl, , the
391 project 1 design document template} into your source tree under the name
392 @file{pintos/src/threads/DESIGNDOC} and fill it in.  We recommend that
393 you read the design document template before you start working on the
394 project.  @xref{Project Documentation}, for a sample design document
395 that goes along with a fictitious project.
397 @node Alarm Clock
398 @subsection Alarm Clock
400 Reimplement @func{timer_sleep}, defined in @file{devices/timer.c}.
401 Although a working implementation is provided, it ``busy waits,'' that
402 is, it spins in a loop checking the current time and calling
403 @func{thread_yield} until enough time has gone by.  Reimplement it to
404 avoid busy waiting.
406 @deftypefun void timer_sleep (int64_t @var{ticks})
407 Suspends execution of the calling thread until time has advanced by at
408 least @w{@var{x} timer ticks}.  Unless the system is otherwise idle, the
409 thread need not wake up after exactly @var{x} ticks.  Just put it on
410 the ready queue after they have waited for the right amount of time.
412 @func{timer_sleep} is useful for threads that operate in real-time,
413 e.g.@: for blinking the cursor once per second.
415 The argument to @func{timer_sleep} is expressed in timer ticks, not in
416 milliseconds or any another unit.  There are @code{TIMER_FREQ} timer
417 ticks per second, where @code{TIMER_FREQ} is a macro defined in
418 @code{devices/timer.h}.  The default value is 100.  We don't recommend
419 changing this value, because any change is likely to cause many of
420 the tests to fail.
421 @end deftypefun
423 Separate functions @func{timer_msleep}, @func{timer_usleep}, and
424 @func{timer_nsleep} do exist for sleeping a specific number of
425 milliseconds, microseconds, or nanoseconds, respectively, but these will
426 call @func{timer_sleep} automatically when necessary.  You do not need
427 to modify them.
429 If your delays seem too short or too long, reread the explanation of the
430 @option{-r} option to @command{pintos} (@pxref{Debugging versus
431 Testing}).
433 The alarm clock implementation is not needed for later projects,
434 although it could be useful for project 4.
436 @node Priority Scheduling
437 @subsection Priority Scheduling
439 Implement priority scheduling in Pintos.
440 When a thread is added to the ready list that has a higher priority
441 than the currently running thread, the current thread should
442 immediately yield the processor to the new thread.  Similarly, when
443 threads are waiting for a lock, semaphore, or condition variable, the
444 highest priority waiting thread should be awakened first.  A thread
445 may raise or lower its own priority at any time, but lowering its
446 priority such that it no longer has the highest priority must cause it
447 to immediately yield the CPU.
449 Thread priorities range from @code{PRI_MIN} (0) to @code{PRI_MAX} (63).
450 Lower numbers correspond to lower priorities, so that priority 0
451 is the lowest priority and priority 63 is the highest.
452 The initial thread priority is passed as an argument to
453 @func{thread_create}.  If there's no reason to choose another
454 priority, use @code{PRI_DEFAULT} (31).  The @code{PRI_} macros are
455 defined in @file{threads/thread.h}, and you should not change their
456 values.
458 One issue with priority scheduling is ``priority inversion''.  Consider
459 high, medium, and low priority threads @var{H}, @var{M}, and @var{L},
460 respectively.  If @var{H} needs to wait for @var{L} (for instance, for a
461 lock held by @var{L}), and @var{M} is on the ready list, then @var{H}
462 will never get the CPU because the low priority thread will not get any
463 CPU time.  A partial fix for this problem is for @var{H} to ``donate''
464 its priority to @var{L} while @var{L} is holding the lock, then recall
465 the donation once @var{L} releases (and thus @var{H} acquires) the lock.
467 Implement priority donation.  You will need to account for all different
468 situations in which priority donation is required.  Be sure to handle
469 multiple donations, in which multiple priorities are donated to a single
470 thread.  You must also handle nested donation: if @var{H} is waiting on
471 a lock that @var{M} holds and @var{M} is waiting on a lock that @var{L}
472 holds, then both @var{M} and @var{L} should be boosted to @var{H}'s
473 priority.  If necessary, you may impose a reasonable limit on depth of
474 nested priority donation, such as 8 levels.
476 You must implement priority donation for locks.  You need not
477 implement priority donation for the other Pintos synchronization
478 constructs.  You do need to implement priority scheduling in all
479 cases.
481 Finally, implement the following functions that allow a thread to
482 examine and modify its own priority.  Skeletons for these functions are
483 provided in @file{threads/thread.c}.
485 @deftypefun void thread_set_priority (int @var{new_priority})
486 Sets the current thread's priority to @var{new_priority}.  If the
487 current thread no longer has the highest priority, yields.
488 @end deftypefun
490 @deftypefun int thread_get_priority (void)
491 Returns the current thread's priority.  In the presence of priority
492 donation, returns the higher (donated) priority.
493 @end deftypefun
495 You need not provide any interface to allow a thread to directly modify
496 other threads' priorities.
498 The priority scheduler is not used in any later project.
500 @node Advanced Scheduler
501 @subsection Advanced Scheduler
503 Implement a multilevel feedback queue scheduler similar to the
504 4.4@acronym{BSD} scheduler to
505 reduce the average response time for running jobs on your system.
506 @xref{4.4BSD Scheduler}, for detailed requirements.
508 Like the priority scheduler, the advanced scheduler chooses the thread
509 to run based on priorities.  However, the advanced scheduler does not do
510 priority donation.  Thus, we recommend that you have the priority
511 scheduler working, except possibly for priority donation, before you
512 start work on the advanced scheduler.
514 You must write your code to allow us to choose a scheduling algorithm
515 policy at Pintos startup time.  By default, the priority scheduler
516 must be active, but we must be able to choose the 4.4@acronym{BSD}
517 scheduler
518 with the @option{-mlfqs} kernel option.  Passing this
519 option sets @code{thread_mlfqs}, declared in @file{threads/thread.h}, to
520 true when the options are parsed by @func{parse_options}, which happens
521 early in @func{main}.
523 When the 4.4@acronym{BSD} scheduler is enabled, threads no longer
524 directly control their own priorities.  The @var{priority} argument to
525 @func{thread_create} should be ignored, as well as any calls to
526 @func{thread_set_priority}, and @func{thread_get_priority} should return
527 the thread's current priority as set by the scheduler.
529 The advanced scheduler is not used in any later project.
531 @node Project 1 FAQ
532 @section FAQ
534 @table @b
535 @item How much code will I need to write?
537 Here's a summary of our reference solution, produced by the
538 @command{diffstat} program.  The final row gives total lines inserted
539 and deleted; a changed line counts as both an insertion and a deletion.
541 The reference solution represents just one possible solution.  Many
542 other solutions are also possible and many of those differ greatly from
543 the reference solution.  Some excellent solutions may not modify all the
544 files modified by the reference solution, and some may modify files not
545 modified by the reference solution.
547 @verbatim
548  devices/timer.c       |   42 +++++-
549  threads/fixed-point.h |  120 ++++++++++++++++++
550  threads/synch.c       |   88 ++++++++++++-
551  threads/thread.c      |  196 ++++++++++++++++++++++++++----
552  threads/thread.h      |   23 +++
553  5 files changed, 440 insertions(+), 29 deletions(-)
554 @end verbatim
556 @file{fixed-point.h} is a new file added by the reference solution.
558 @item How do I update the @file{Makefile}s when I add a new source file?
560 @anchor{Adding Source Files}
561 To add a @file{.c} file, edit the top-level @file{Makefile.build}.
562 Add the new file to variable @samp{@var{dir}_SRC}, where
563 @var{dir} is the directory where you added the file.  For this
564 project, that means you should add it to @code{threads_SRC} or
565 @code{devices_SRC}.  Then run @code{make}.  If your new file
566 doesn't get
567 compiled, run @code{make clean} and then try again.
569 When you modify the top-level @file{Makefile.build} and re-run
570 @command{make}, the modified
571 version should be automatically copied to
572 @file{threads/build/Makefile}.  The converse is
573 not true, so any changes will be lost the next time you run @code{make
574 clean} from the @file{threads} directory.  Unless your changes are
575 truly temporary, you should prefer to edit @file{Makefile.build}.
577 A new @file{.h} file does not require editing the @file{Makefile}s.
579 @item What does @code{warning: no previous prototype for `@var{func}'} mean?
581 It means that you defined a non-@code{static} function without
582 preceding it by a prototype.  Because non-@code{static} functions are
583 intended for use by other @file{.c} files, for safety they should be
584 prototyped in a header file included before their definition.  To fix
585 the problem, add a prototype in a header file that you include, or, if
586 the function isn't actually used by other @file{.c} files, make it
587 @code{static}.
589 @item What is the interval between timer interrupts?
591 Timer interrupts occur @code{TIMER_FREQ} times per second.  You can
592 adjust this value by editing @file{devices/timer.h}.  The default is
593 100 Hz.
595 We don't recommend changing this value, because any changes are likely
596 to cause many of the tests to fail.
598 @item How long is a time slice?
600 There are @code{TIME_SLICE} ticks per time slice.  This macro is
601 declared in @file{threads/thread.c}.  The default is 4 ticks.
603 We don't recommend changing this value, because any changes are likely
604 to cause many of the tests to fail.
606 @item How do I run the tests?
608 @xref{Testing}.
610 @item Why do I get a test failure in @func{pass}?
612 @anchor{The pass function fails}
613 You are probably looking at a backtrace that looks something like this:
615 @example
616 0xc0108810: debug_panic (lib/kernel/debug.c:32)
617 0xc010a99f: pass (tests/threads/tests.c:93)
618 0xc010bdd3: test_mlfqs_load_1 (...threads/mlfqs-load-1.c:33)
619 0xc010a8cf: run_test (tests/threads/tests.c:51)
620 0xc0100452: run_task (threads/init.c:283)
621 0xc0100536: run_actions (threads/init.c:333)
622 0xc01000bb: main (threads/init.c:137)
623 @end example
625 This is just confusing output from the @command{backtrace} program.  It
626 does not actually mean that @func{pass} called @func{debug_panic}.  In
627 fact, @func{fail} called @func{debug_panic} (via the @func{PANIC}
628 macro).  GCC knows that @func{debug_panic} does not return, because it
629 is declared @code{NO_RETURN} (@pxref{Function and Parameter
630 Attributes}), so it doesn't include any code in @func{fail} to take
631 control when @func{debug_panic} returns.  This means that the return
632 address on the stack looks like it is at the beginning of the function
633 that happens to follow @func{fail} in memory, which in this case happens
634 to be @func{pass}.
636 @xref{Backtraces}, for more information.
638 @item How do interrupts get re-enabled in the new thread following @func{schedule}?
640 Every path into @func{schedule} disables interrupts.  They eventually
641 get re-enabled by the next thread to be scheduled.  Consider the
642 possibilities: the new thread is running in @func{switch_thread} (but
643 see below), which is called by @func{schedule}, which is called by one
644 of a few possible functions:
646 @itemize @bullet
647 @item
648 @func{thread_exit}, but we'll never switch back into such a thread, so
649 it's uninteresting.
651 @item
652 @func{thread_yield}, which immediately restores the interrupt level upon
653 return from @func{schedule}.
655 @item
656 @func{thread_block}, which is called from multiple places:
658 @itemize @minus
659 @item
660 @func{sema_down}, which restores the interrupt level before returning.
662 @item
663 @func{idle}, which enables interrupts with an explicit assembly STI
664 instruction.
666 @item
667 @func{wait} in @file{devices/intq.c}, whose callers are responsible for
668 re-enabling interrupts.
669 @end itemize
670 @end itemize
672 There is a special case when a newly created thread runs for the first
673 time.  Such a thread calls @func{intr_enable} as the first action in
674 @func{kernel_thread}, which is at the bottom of the call stack for every
675 kernel thread but the first.
676 @end table
678 @menu
679 * Alarm Clock FAQ::             
680 * Priority Scheduling FAQ::     
681 * Advanced Scheduler FAQ::      
682 @end menu
684 @node Alarm Clock FAQ
685 @subsection Alarm Clock FAQ
687 @table @b
688 @item Do I need to account for timer values overflowing?
690 Don't worry about the possibility of timer values overflowing.  Timer
691 values are expressed as signed 64-bit numbers, which at 100 ticks per
692 second should be good for almost 2,924,712,087 years.  By then, we
693 expect Pintos to have been phased out of the @value{coursenumber} curriculum.
694 @end table
696 @node Priority Scheduling FAQ
697 @subsection Priority Scheduling FAQ
699 @table @b
700 @item Doesn't priority scheduling lead to starvation?
702 Yes, strict priority scheduling can lead to starvation
703 because a thread will not run if any higher-priority thread is runnable.
704 The advanced scheduler introduces a mechanism for dynamically
705 changing thread priorities.
707 Strict priority scheduling is valuable in real-time systems because it
708 offers the programmer more control over which jobs get processing
709 time.  High priorities are generally reserved for time-critical
710 tasks. It's not ``fair,'' but it addresses other concerns not
711 applicable to a general-purpose operating system.
713 @item What thread should run after a lock has been released?
715 When a lock is released, the highest priority thread waiting for that
716 lock should be unblocked and put on the list of ready threads.  The
717 scheduler should then run the highest priority thread on the ready
718 list.
720 @item If the highest-priority thread yields, does it continue running?
722 Yes.  If there is a single highest-priority thread, it continues
723 running until it blocks or finishes, even if it calls
724 @func{thread_yield}.
725 If multiple threads have the same highest priority,
726 @func{thread_yield} should switch among them in ``round robin'' order.
728 @item What happens to the priority of a donating thread?
730 Priority donation only changes the priority of the donee
731 thread.  The donor thread's priority is unchanged.  
732 Priority donation is not additive: if thread @var{A} (with priority 5) donates
733 to thread @var{B} (with priority 3), then @var{B}'s new priority is 5, not 8.
735 @item Can a thread's priority change while it is on the ready queue?
737 Yes.  Consider a ready, low-priority thread @var{L} that holds a lock.
738 High-priority thread @var{H} attempts to acquire the lock and blocks,
739 thereby donating its priority to ready thread @var{L}.
741 @item Can a thread's priority change while it is blocked?
743 Yes.  While a thread that has acquired lock @var{L} is blocked for any
744 reason, its priority can increase by priority donation if a
745 higher-priority thread attempts to acquire @var{L}.  This case is
746 checked by the @code{priority-donate-sema} test.
748 @item Can a thread added to the ready list preempt the processor?
750 Yes.  If a thread added to the ready list has higher priority than the
751 running thread, the correct behavior is to immediately yield the
752 processor.  It is not acceptable to wait for the next timer interrupt.
753 The highest priority thread should run as soon as it is runnable,
754 preempting whatever thread is currently running.
756 @item How does @func{thread_set_priority} affect a thread receiving donations?
758 It sets the thread's base priority.  The thread's effective priority
759 becomes the higher of the newly set priority or the highest donated
760 priority.  When the donations are released, the thread's priority
761 becomes the one set through the function call.  This behavior is checked
762 by the @code{priority-donate-lower} test.
763 @end table
765 @node Advanced Scheduler FAQ
766 @subsection Advanced Scheduler FAQ
768 @table @b
769 @item How does priority donation interact with the advanced scheduler?
771 It doesn't have to.  We won't test priority donation and the advanced
772 scheduler at the same time.
774 @item Can I use one queue instead of 64 queues?
776 Yes.  In general, your implementation may differ from the description,
777 as long as its behavior is the same.
779 @item Some scheduler tests fail and I don't understand why.  Help!
781 If your implementation mysteriously fails some of the advanced
782 scheduler tests, try the following:
784 @itemize
785 @item
786 Read the source files for the tests that you're failing, to make sure
787 that you understand what's going on.  Each one has a comment at the
788 top that explains its purpose and expected results.
790 @item
791 Double-check your fixed-point arithmetic routines and your use of them
792 in the scheduler routines.
794 @item
795 Consider how much work your implementation does in the timer
796 interrupt.  If the timer interrupt handler takes too long, then it
797 will take away most of a timer tick from the thread that the timer
798 interrupt preempted.  When it returns control to that thread, it
799 therefore won't get to do much work before the next timer interrupt
800 arrives.  That thread will therefore get blamed for a lot more CPU
801 time than it actually got a chance to use.  This raises the
802 interrupted thread's recent CPU count, thereby lowering its priority.
803 It can cause scheduling decisions to change.  It also raises the load
804 average.
805 @end itemize
806 @end table