Implement a proper block layer with partition support.
[pintos-anon] / doc / threads.texi
1 @node Project 1--Threads
2 @chapter Project 1: Threads
3
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.
7
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.
11
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}.
18
19 @menu
20 * Project 1 Background::        
21 * Project 1 Requirements::      
22 * Project 1 FAQ::               
23 @end menu
24
25 @node Project 1 Background
26 @section Background
27
28
29 @menu
30 * Understanding Threads::       
31 * Project 1 Source Files::      
32 * Project 1 Synchronization::   
33 * Development Suggestions::     
34 @end menu
35
36 @node Understanding Threads
37 @subsection Understanding Threads
38
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).
45
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.
55
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}.
64
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.
72
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.
78
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.
95
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}).
103
104 @node Project 1 Source Files
105 @subsection Source Files
106
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.
111
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 finds the kernel on disk,
117 loads it into memory, and jumps to @func{start} in @file{start.S}.
118 @xref{Pintos Loader}, for details.  You should not need to look at
119 this code or modify it.
120
121 @item start.S
122 Does basic setup needed for memory protection and 32-bit
123 operation on 80@var{x}86 CPUs.  Unlike the loader, this code is
124 actually part of the kernel.  @xref{Low-Level Kernel Initialization},
125 for details.
126
127 @item kernel.lds.S
128 The linker script used to link the kernel.  Sets the load address of
129 the kernel and arranges for @file{start.S} to be near the beginning
130 of the kernel image.  @xref{Pintos Loader}, for details. Again, you
131 should not need to look at this code
132 or modify it, but it's here in case you're curious.
133
134 @item init.c
135 @itemx init.h
136 Kernel initialization, including @func{main}, the kernel's ``main
137 program.''  You should look over @func{main} at least to see what
138 gets initialized.  You might want to add your own initialization code
139 here.  @xref{High-Level Kernel Initialization}, for details.
140
141 @item thread.c
142 @itemx thread.h
143 Basic thread support.  Much of your work will take place in these files.
144 @file{thread.h} defines @struct{thread}, which you are likely to modify
145 in all four projects.  See @ref{struct thread} and @ref{Threads} for
146 more information.
147
148 @item switch.S
149 @itemx switch.h
150 Assembly language routine for switching threads.  Already discussed
151 above.  @xref{Thread Functions}, for more information.
152
153 @item palloc.c
154 @itemx palloc.h
155 Page allocator, which hands out system memory in multiples of 4 kB
156 pages.  @xref{Page Allocator}, for more information.
157
158 @item malloc.c
159 @itemx malloc.h
160 A simple implementation of @func{malloc} and @func{free} for
161 the kernel.  @xref{Block Allocator}, for more information.
162
163 @item interrupt.c
164 @itemx interrupt.h
165 Basic interrupt handling and functions for turning interrupts on and
166 off.  @xref{Interrupt Handling}, for more information.
167
168 @item intr-stubs.S
169 @itemx intr-stubs.h
170 Assembly code for low-level interrupt handling.  @xref{Interrupt
171 Infrastructure}, for more information.
172
173 @item synch.c
174 @itemx synch.h
175 Basic synchronization primitives: semaphores, locks, condition
176 variables, and optimization barriers.  You will need to use these for
177 synchronization in all
178 four projects.  @xref{Synchronization}, for more information.
179
180 @item io.h
181 Functions for I/O port access.  This is mostly used by source code in
182 the @file{devices} directory that you won't have to touch.
183
184 @item vaddr.h
185 @itemx pte.h
186 Functions and macros for working with virtual addresses and page table
187 entries.  These will be more important to you in project 3.  For now,
188 you can ignore them.
189
190 @item flags.h
191 Macros that define a few bits in the 80@var{x}86 ``flags'' register.
192 Probably of no interest.  See @bibref{IA32-v1}, section 3.4.3, ``EFLAGS
193 Register,'' for more information.
194 @end table
195
196 @menu
197 * devices code::                
198 * lib files::                   
199 @end menu
200
201 @node devices code
202 @subsubsection @file{devices} code
203
204 The basic threaded kernel also includes these files in the
205 @file{devices} directory:
206
207 @table @file
208 @item timer.c
209 @itemx timer.h
210 System timer that ticks, by default, 100 times per second.  You will
211 modify this code in this project.
212
213 @item vga.c
214 @itemx vga.h
215 VGA display driver.  Responsible for writing text to the screen.
216 You should have no need to look at this code.  @func{printf}
217 calls into the VGA display driver for you, so there's little reason to
218 call this code yourself.
219
220 @item serial.c
221 @itemx serial.h
222 Serial port driver.  Again, @func{printf} calls this code for you,
223 so you don't need to do so yourself.
224 It handles serial input by passing it to the input layer (see below).
225
226 @item block.c
227 @itemx block.h
228 An abstraction layer for @dfn{block devices}, that is, random-access,
229 disk-like devices that are organized as arrays of fixed-size blocks.
230 Out of the box, Pintos supports two types of block devices: IDE disks
231 and partitions.  Block devices, regardless of type, won't actually be
232 used until project 2.
233
234 @item ide.c
235 @itemx ide.h
236 Supports reading and writing sectors on up to 4 IDE disks.
237
238 @item partition.c
239 @itemx partition.h
240 Understands the structure of partitions on disks, allowing a single
241 disk to be carved up into multiple regions (partitions) for
242 independent use.
243
244 @item kbd.c
245 @itemx kbd.h
246 Keyboard driver.  Handles keystrokes passing them to the input layer
247 (see below).
248
249 @item input.c
250 @itemx input.h
251 Input layer.  Queues input characters passed along by the keyboard or
252 serial drivers.
253
254 @item intq.c
255 @itemx intq.h
256 Interrupt queue, for managing a circular queue that both kernel
257 threads and interrupt handlers want to access.  Used by the keyboard
258 and serial drivers.
259
260 @item rtc.c
261 @itemx rtc.h
262 Real-time clock driver, to enable the kernel to determine the current
263 date and time.  By default, this is only used by @file{thread/init.c}
264 to choose an initial seed for the random number generator.
265
266 @item speaker.c
267 @itemx speaker.h
268 Driver that can produce tones on the PC speaker.
269
270 @item pit.c
271 @itemx pit.h
272 Code to configure the 8254 Programmable Interrupt Timer.  This code is
273 used by both @file{devices/timer.c} and @file{devices/speaker.c}
274 because each device uses one of the PIT's output channel.
275 @end table
276
277 @node lib files
278 @subsubsection @file{lib} files
279
280 Finally, @file{lib} and @file{lib/kernel} contain useful library
281 routines.  (@file{lib/user} will be used by user programs, starting in
282 project 2, but it is not part of the kernel.)  Here's a few more
283 details:
284
285 @table @file
286 @item ctype.h
287 @itemx inttypes.h
288 @itemx limits.h
289 @itemx stdarg.h
290 @itemx stdbool.h
291 @itemx stddef.h
292 @itemx stdint.h
293 @itemx stdio.c
294 @itemx stdio.h
295 @itemx stdlib.c
296 @itemx stdlib.h
297 @itemx string.c
298 @itemx string.h
299 A subset of the standard C library.  @xref{C99}, for
300 information
301 on a few recently introduced pieces of the C library that you might
302 not have encountered before.  @xref{Unsafe String Functions}, for
303 information on what's been intentionally left out for safety.
304
305 @item debug.c
306 @itemx debug.h
307 Functions and macros to aid debugging.  @xref{Debugging Tools}, for
308 more information.
309
310 @item random.c
311 @itemx random.h
312 Pseudo-random number generator.  The actual sequence of random values
313 will not vary from one Pintos run to another, unless you do one of
314 three things: specify a new random seed value on the @option{-rs}
315 kernel command-line option on each run, or use a simulator other than
316 Bochs, or specify the @option{-r} option to @command{pintos}.
317
318 @item round.h
319 Macros for rounding.
320
321 @item syscall-nr.h
322 System call numbers.  Not used until project 2.
323
324 @item kernel/list.c
325 @itemx kernel/list.h
326 Doubly linked list implementation.  Used all over the Pintos code, and
327 you'll probably want to use it a few places yourself in project 1.
328
329 @item kernel/bitmap.c
330 @itemx kernel/bitmap.h
331 Bitmap implementation.  You can use this in your code if you like, but
332 you probably won't have any need for it in project 1.
333
334 @item kernel/hash.c
335 @itemx kernel/hash.h
336 Hash table implementation.  Likely to come in handy for project 3.
337
338 @item kernel/console.c
339 @itemx kernel/console.h
340 @item kernel/stdio.h
341 Implements @func{printf} and a few other functions.
342 @end table
343
344 @node Project 1 Synchronization
345 @subsection Synchronization
346
347 Proper synchronization is an important part of the solutions to these
348 problems.  Any synchronization problem can be easily solved by turning
349 interrupts off: while interrupts are off, there is no concurrency, so
350 there's no possibility for race conditions.  Therefore, it's tempting to
351 solve all synchronization problems this way, but @strong{don't}.
352 Instead, use semaphores, locks, and condition variables to solve the
353 bulk of your synchronization problems.  Read the tour section on
354 synchronization (@pxref{Synchronization}) or the comments in
355 @file{threads/synch.c} if you're unsure what synchronization primitives
356 may be used in what situations.
357
358 In the Pintos projects, the only class of problem best solved by
359 disabling interrupts is coordinating data shared between a kernel thread
360 and an interrupt handler.  Because interrupt handlers can't sleep, they
361 can't acquire locks.  This means that data shared between kernel threads
362 and an interrupt handler must be protected within a kernel thread by
363 turning off interrupts.
364
365 This project only requires accessing a little bit of thread state from
366 interrupt handlers.  For the alarm clock, the timer interrupt needs to
367 wake up sleeping threads.  In the advanced scheduler, the timer
368 interrupt needs to access a few global and per-thread variables.  When
369 you access these variables from kernel threads, you will need to disable
370 interrupts to prevent the timer interrupt from interfering.
371
372 When you do turn off interrupts, take care to do so for the least amount
373 of code possible, or you can end up losing important things such as
374 timer ticks or input events.  Turning off interrupts also increases the
375 interrupt handling latency, which can make a machine feel sluggish if
376 taken too far.
377
378 The synchronization primitives themselves in @file{synch.c} are
379 implemented by disabling interrupts.  You may need to increase the
380 amount of code that runs with interrupts disabled here, but you should
381 still try to keep it to a minimum.
382
383 Disabling interrupts can be useful for debugging, if you want to make
384 sure that a section of code is not interrupted.  You should remove
385 debugging code before turning in your project.  (Don't just comment it
386 out, because that can make the code difficult to read.)
387
388 There should be no busy waiting in your submission.  A tight loop that
389 calls @func{thread_yield} is one form of busy waiting.
390
391 @node Development Suggestions
392 @subsection Development Suggestions
393
394 In the past, many groups divided the assignment into pieces, then each
395 group member worked on his or her piece until just before the
396 deadline, at which time the group reconvened to combine their code and
397 submit.  @strong{This is a bad idea.  We do not recommend this
398 approach.}  Groups that do this often find that two changes conflict
399 with each other, requiring lots of last-minute debugging.  Some groups
400 who have done this have turned in code that did not even compile or
401 boot, much less pass any tests.
402
403 @localcvspolicy{}
404
405 You should expect to run into bugs that you simply don't understand
406 while working on this and subsequent projects.  When you do,
407 reread the appendix on debugging tools, which is filled with
408 useful debugging tips that should help you to get back up to speed
409 (@pxref{Debugging Tools}).  Be sure to read the section on backtraces
410 (@pxref{Backtraces}), which will help you to get the most out of every
411 kernel panic or assertion failure.
412
413 @node Project 1 Requirements
414 @section Requirements
415
416 @menu
417 * Project 1 Design Document::   
418 * Alarm Clock::                 
419 * Priority Scheduling::         
420 * Advanced Scheduler::          
421 @end menu
422
423 @node Project 1 Design Document
424 @subsection Design Document
425
426 Before you turn in your project, you must copy @uref{threads.tmpl, , the
427 project 1 design document template} into your source tree under the name
428 @file{pintos/src/threads/DESIGNDOC} and fill it in.  We recommend that
429 you read the design document template before you start working on the
430 project.  @xref{Project Documentation}, for a sample design document
431 that goes along with a fictitious project.
432
433 @node Alarm Clock
434 @subsection Alarm Clock
435
436 Reimplement @func{timer_sleep}, defined in @file{devices/timer.c}.
437 Although a working implementation is provided, it ``busy waits,'' that
438 is, it spins in a loop checking the current time and calling
439 @func{thread_yield} until enough time has gone by.  Reimplement it to
440 avoid busy waiting.
441
442 @deftypefun void timer_sleep (int64_t @var{ticks})
443 Suspends execution of the calling thread until time has advanced by at
444 least @w{@var{x} timer ticks}.  Unless the system is otherwise idle, the
445 thread need not wake up after exactly @var{x} ticks.  Just put it on
446 the ready queue after they have waited for the right amount of time.
447
448 @func{timer_sleep} is useful for threads that operate in real-time,
449 e.g.@: for blinking the cursor once per second.
450
451 The argument to @func{timer_sleep} is expressed in timer ticks, not in
452 milliseconds or any another unit.  There are @code{TIMER_FREQ} timer
453 ticks per second, where @code{TIMER_FREQ} is a macro defined in
454 @code{devices/timer.h}.  The default value is 100.  We don't recommend
455 changing this value, because any change is likely to cause many of
456 the tests to fail.
457 @end deftypefun
458
459 Separate functions @func{timer_msleep}, @func{timer_usleep}, and
460 @func{timer_nsleep} do exist for sleeping a specific number of
461 milliseconds, microseconds, or nanoseconds, respectively, but these will
462 call @func{timer_sleep} automatically when necessary.  You do not need
463 to modify them.
464
465 If your delays seem too short or too long, reread the explanation of the
466 @option{-r} option to @command{pintos} (@pxref{Debugging versus
467 Testing}).
468
469 The alarm clock implementation is not needed for later projects,
470 although it could be useful for project 4.
471
472 @node Priority Scheduling
473 @subsection Priority Scheduling
474
475 Implement priority scheduling in Pintos.
476 When a thread is added to the ready list that has a higher priority
477 than the currently running thread, the current thread should
478 immediately yield the processor to the new thread.  Similarly, when
479 threads are waiting for a lock, semaphore, or condition variable, the
480 highest priority waiting thread should be awakened first.  A thread
481 may raise or lower its own priority at any time, but lowering its
482 priority such that it no longer has the highest priority must cause it
483 to immediately yield the CPU.
484
485 Thread priorities range from @code{PRI_MIN} (0) to @code{PRI_MAX} (63).
486 Lower numbers correspond to lower priorities, so that priority 0
487 is the lowest priority and priority 63 is the highest.
488 The initial thread priority is passed as an argument to
489 @func{thread_create}.  If there's no reason to choose another
490 priority, use @code{PRI_DEFAULT} (31).  The @code{PRI_} macros are
491 defined in @file{threads/thread.h}, and you should not change their
492 values.
493
494 One issue with priority scheduling is ``priority inversion''.  Consider
495 high, medium, and low priority threads @var{H}, @var{M}, and @var{L},
496 respectively.  If @var{H} needs to wait for @var{L} (for instance, for a
497 lock held by @var{L}), and @var{M} is on the ready list, then @var{H}
498 will never get the CPU because the low priority thread will not get any
499 CPU time.  A partial fix for this problem is for @var{H} to ``donate''
500 its priority to @var{L} while @var{L} is holding the lock, then recall
501 the donation once @var{L} releases (and thus @var{H} acquires) the lock.
502
503 Implement priority donation.  You will need to account for all different
504 situations in which priority donation is required.  Be sure to handle
505 multiple donations, in which multiple priorities are donated to a single
506 thread.  You must also handle nested donation: if @var{H} is waiting on
507 a lock that @var{M} holds and @var{M} is waiting on a lock that @var{L}
508 holds, then both @var{M} and @var{L} should be boosted to @var{H}'s
509 priority.  If necessary, you may impose a reasonable limit on depth of
510 nested priority donation, such as 8 levels.
511
512 You must implement priority donation for locks.  You need not
513 implement priority donation for the other Pintos synchronization
514 constructs.  You do need to implement priority scheduling in all
515 cases.
516
517 Finally, implement the following functions that allow a thread to
518 examine and modify its own priority.  Skeletons for these functions are
519 provided in @file{threads/thread.c}.
520
521 @deftypefun void thread_set_priority (int @var{new_priority})
522 Sets the current thread's priority to @var{new_priority}.  If the
523 current thread no longer has the highest priority, yields.
524 @end deftypefun
525
526 @deftypefun int thread_get_priority (void)
527 Returns the current thread's priority.  In the presence of priority
528 donation, returns the higher (donated) priority.
529 @end deftypefun
530
531 You need not provide any interface to allow a thread to directly modify
532 other threads' priorities.
533
534 The priority scheduler is not used in any later project.
535
536 @node Advanced Scheduler
537 @subsection Advanced Scheduler
538
539 Implement a multilevel feedback queue scheduler similar to the
540 4.4@acronym{BSD} scheduler to
541 reduce the average response time for running jobs on your system.
542 @xref{4.4BSD Scheduler}, for detailed requirements.
543
544 Like the priority scheduler, the advanced scheduler chooses the thread
545 to run based on priorities.  However, the advanced scheduler does not do
546 priority donation.  Thus, we recommend that you have the priority
547 scheduler working, except possibly for priority donation, before you
548 start work on the advanced scheduler.
549
550 You must write your code to allow us to choose a scheduling algorithm
551 policy at Pintos startup time.  By default, the priority scheduler
552 must be active, but we must be able to choose the 4.4@acronym{BSD}
553 scheduler
554 with the @option{-mlfqs} kernel option.  Passing this
555 option sets @code{thread_mlfqs}, declared in @file{threads/thread.h}, to
556 true when the options are parsed by @func{parse_options}, which happens
557 early in @func{main}.
558
559 When the 4.4@acronym{BSD} scheduler is enabled, threads no longer
560 directly control their own priorities.  The @var{priority} argument to
561 @func{thread_create} should be ignored, as well as any calls to
562 @func{thread_set_priority}, and @func{thread_get_priority} should return
563 the thread's current priority as set by the scheduler.
564
565 The advanced scheduler is not used in any later project.
566
567 @node Project 1 FAQ
568 @section FAQ
569
570 @table @b
571 @item How much code will I need to write?
572
573 Here's a summary of our reference solution, produced by the
574 @command{diffstat} program.  The final row gives total lines inserted
575 and deleted; a changed line counts as both an insertion and a deletion.
576
577 The reference solution represents just one possible solution.  Many
578 other solutions are also possible and many of those differ greatly from
579 the reference solution.  Some excellent solutions may not modify all the
580 files modified by the reference solution, and some may modify files not
581 modified by the reference solution.
582
583 @verbatim
584  devices/timer.c       |   42 +++++-
585  threads/fixed-point.h |  120 ++++++++++++++++++
586  threads/synch.c       |   88 ++++++++++++-
587  threads/thread.c      |  196 ++++++++++++++++++++++++++----
588  threads/thread.h      |   23 +++
589  5 files changed, 440 insertions(+), 29 deletions(-)
590 @end verbatim
591
592 @file{fixed-point.h} is a new file added by the reference solution.
593
594 @item How do I update the @file{Makefile}s when I add a new source file?
595
596 @anchor{Adding Source Files}
597 To add a @file{.c} file, edit the top-level @file{Makefile.build}.
598 Add the new file to variable @samp{@var{dir}_SRC}, where
599 @var{dir} is the directory where you added the file.  For this
600 project, that means you should add it to @code{threads_SRC} or
601 @code{devices_SRC}.  Then run @code{make}.  If your new file
602 doesn't get
603 compiled, run @code{make clean} and then try again.
604
605 When you modify the top-level @file{Makefile.build} and re-run
606 @command{make}, the modified
607 version should be automatically copied to
608 @file{threads/build/Makefile}.  The converse is
609 not true, so any changes will be lost the next time you run @code{make
610 clean} from the @file{threads} directory.  Unless your changes are
611 truly temporary, you should prefer to edit @file{Makefile.build}.
612
613 A new @file{.h} file does not require editing the @file{Makefile}s.
614
615 @item What does @code{warning: no previous prototype for `@var{func}'} mean?
616
617 It means that you defined a non-@code{static} function without
618 preceding it by a prototype.  Because non-@code{static} functions are
619 intended for use by other @file{.c} files, for safety they should be
620 prototyped in a header file included before their definition.  To fix
621 the problem, add a prototype in a header file that you include, or, if
622 the function isn't actually used by other @file{.c} files, make it
623 @code{static}.
624
625 @item What is the interval between timer interrupts?
626
627 Timer interrupts occur @code{TIMER_FREQ} times per second.  You can
628 adjust this value by editing @file{devices/timer.h}.  The default is
629 100 Hz.
630
631 We don't recommend changing this value, because any changes are likely
632 to cause many of the tests to fail.
633
634 @item How long is a time slice?
635
636 There are @code{TIME_SLICE} ticks per time slice.  This macro is
637 declared in @file{threads/thread.c}.  The default is 4 ticks.
638
639 We don't recommend changing this value, because any changes are likely
640 to cause many of the tests to fail.
641
642 @item How do I run the tests?
643
644 @xref{Testing}.
645
646 @item Why do I get a test failure in @func{pass}?
647
648 @anchor{The pass function fails}
649 You are probably looking at a backtrace that looks something like this:
650
651 @example
652 0xc0108810: debug_panic (lib/kernel/debug.c:32)
653 0xc010a99f: pass (tests/threads/tests.c:93)
654 0xc010bdd3: test_mlfqs_load_1 (...threads/mlfqs-load-1.c:33)
655 0xc010a8cf: run_test (tests/threads/tests.c:51)
656 0xc0100452: run_task (threads/init.c:283)
657 0xc0100536: run_actions (threads/init.c:333)
658 0xc01000bb: main (threads/init.c:137)
659 @end example
660
661 This is just confusing output from the @command{backtrace} program.  It
662 does not actually mean that @func{pass} called @func{debug_panic}.  In
663 fact, @func{fail} called @func{debug_panic} (via the @func{PANIC}
664 macro).  GCC knows that @func{debug_panic} does not return, because it
665 is declared @code{NO_RETURN} (@pxref{Function and Parameter
666 Attributes}), so it doesn't include any code in @func{fail} to take
667 control when @func{debug_panic} returns.  This means that the return
668 address on the stack looks like it is at the beginning of the function
669 that happens to follow @func{fail} in memory, which in this case happens
670 to be @func{pass}.
671
672 @xref{Backtraces}, for more information.
673
674 @item How do interrupts get re-enabled in the new thread following @func{schedule}?
675
676 Every path into @func{schedule} disables interrupts.  They eventually
677 get re-enabled by the next thread to be scheduled.  Consider the
678 possibilities: the new thread is running in @func{switch_thread} (but
679 see below), which is called by @func{schedule}, which is called by one
680 of a few possible functions:
681
682 @itemize @bullet
683 @item
684 @func{thread_exit}, but we'll never switch back into such a thread, so
685 it's uninteresting.
686
687 @item
688 @func{thread_yield}, which immediately restores the interrupt level upon
689 return from @func{schedule}.
690
691 @item
692 @func{thread_block}, which is called from multiple places:
693
694 @itemize @minus
695 @item
696 @func{sema_down}, which restores the interrupt level before returning.
697
698 @item
699 @func{idle}, which enables interrupts with an explicit assembly STI
700 instruction.
701
702 @item
703 @func{wait} in @file{devices/intq.c}, whose callers are responsible for
704 re-enabling interrupts.
705 @end itemize
706 @end itemize
707
708 There is a special case when a newly created thread runs for the first
709 time.  Such a thread calls @func{intr_enable} as the first action in
710 @func{kernel_thread}, which is at the bottom of the call stack for every
711 kernel thread but the first.
712 @end table
713
714 @menu
715 * Alarm Clock FAQ::             
716 * Priority Scheduling FAQ::     
717 * Advanced Scheduler FAQ::      
718 @end menu
719
720 @node Alarm Clock FAQ
721 @subsection Alarm Clock FAQ
722
723 @table @b
724 @item Do I need to account for timer values overflowing?
725
726 Don't worry about the possibility of timer values overflowing.  Timer
727 values are expressed as signed 64-bit numbers, which at 100 ticks per
728 second should be good for almost 2,924,712,087 years.  By then, we
729 expect Pintos to have been phased out of the @value{coursenumber} curriculum.
730 @end table
731
732 @node Priority Scheduling FAQ
733 @subsection Priority Scheduling FAQ
734
735 @table @b
736 @item Doesn't priority scheduling lead to starvation?
737
738 Yes, strict priority scheduling can lead to starvation
739 because a thread will not run if any higher-priority thread is runnable.
740 The advanced scheduler introduces a mechanism for dynamically
741 changing thread priorities.
742
743 Strict priority scheduling is valuable in real-time systems because it
744 offers the programmer more control over which jobs get processing
745 time.  High priorities are generally reserved for time-critical
746 tasks. It's not ``fair,'' but it addresses other concerns not
747 applicable to a general-purpose operating system.
748
749 @item What thread should run after a lock has been released?
750
751 When a lock is released, the highest priority thread waiting for that
752 lock should be unblocked and put on the list of ready threads.  The
753 scheduler should then run the highest priority thread on the ready
754 list.
755
756 @item If the highest-priority thread yields, does it continue running?
757
758 Yes.  If there is a single highest-priority thread, it continues
759 running until it blocks or finishes, even if it calls
760 @func{thread_yield}.
761 If multiple threads have the same highest priority,
762 @func{thread_yield} should switch among them in ``round robin'' order.
763
764 @item What happens to the priority of a donating thread?
765
766 Priority donation only changes the priority of the donee
767 thread.  The donor thread's priority is unchanged.  
768 Priority donation is not additive: if thread @var{A} (with priority 5) donates
769 to thread @var{B} (with priority 3), then @var{B}'s new priority is 5, not 8.
770
771 @item Can a thread's priority change while it is on the ready queue?
772
773 Yes.  Consider a ready, low-priority thread @var{L} that holds a lock.
774 High-priority thread @var{H} attempts to acquire the lock and blocks,
775 thereby donating its priority to ready thread @var{L}.
776
777 @item Can a thread's priority change while it is blocked?
778
779 Yes.  While a thread that has acquired lock @var{L} is blocked for any
780 reason, its priority can increase by priority donation if a
781 higher-priority thread attempts to acquire @var{L}.  This case is
782 checked by the @code{priority-donate-sema} test.
783
784 @item Can a thread added to the ready list preempt the processor?
785
786 Yes.  If a thread added to the ready list has higher priority than the
787 running thread, the correct behavior is to immediately yield the
788 processor.  It is not acceptable to wait for the next timer interrupt.
789 The highest priority thread should run as soon as it is runnable,
790 preempting whatever thread is currently running.
791
792 @item How does @func{thread_set_priority} affect a thread receiving donations?
793
794 It sets the thread's base priority.  The thread's effective priority
795 becomes the higher of the newly set priority or the highest donated
796 priority.  When the donations are released, the thread's priority
797 becomes the one set through the function call.  This behavior is checked
798 by the @code{priority-donate-lower} test.
799
800 @item Doubled test names in output make them fail.
801
802 Suppose you are seeing output in which some test names are doubled,
803 like this:
804
805 @example
806 (alarm-priority) begin
807 (alarm-priority) (alarm-priority) Thread priority 30 woke up.
808 Thread priority 29 woke up.
809 (alarm-priority) Thread priority 28 woke up.
810 @end example
811
812 What is happening is that output from two threads is being
813 interleaved.  That is, one thread is printing @code{"(alarm-priority)
814 Thread priority 29 woke up.\n"} and another thread is printing
815 @code{"(alarm-priority) Thread priority 30 woke up.\n"}, but the first
816 thread is being preempted by the second in the middle of its output.
817
818 This problem indicates a bug in your priority scheduler.  After all, a
819 thread with priority 29 should not be able to run while a thread with
820 priority 30 has work to do.
821
822 Normally, the implementation of the @code{printf()} function in the
823 Pintos kernel attempts to prevent such interleaved output by acquiring
824 a console lock during the duration of the @code{printf} call and
825 releasing it afterwards.  However, the output of the test name,
826 e.g., @code{(alarm-priority)}, and the message following it is output
827 using two calls to @code{printf}, resulting in the console lock being
828 acquired and released twice.
829 @end table
830
831 @node Advanced Scheduler FAQ
832 @subsection Advanced Scheduler FAQ
833
834 @table @b
835 @item How does priority donation interact with the advanced scheduler?
836
837 It doesn't have to.  We won't test priority donation and the advanced
838 scheduler at the same time.
839
840 @item Can I use one queue instead of 64 queues?
841
842 Yes.  In general, your implementation may differ from the description,
843 as long as its behavior is the same.
844
845 @item Some scheduler tests fail and I don't understand why.  Help!
846
847 If your implementation mysteriously fails some of the advanced
848 scheduler tests, try the following:
849
850 @itemize
851 @item
852 Read the source files for the tests that you're failing, to make sure
853 that you understand what's going on.  Each one has a comment at the
854 top that explains its purpose and expected results.
855
856 @item
857 Double-check your fixed-point arithmetic routines and your use of them
858 in the scheduler routines.
859
860 @item
861 Consider how much work your implementation does in the timer
862 interrupt.  If the timer interrupt handler takes too long, then it
863 will take away most of a timer tick from the thread that the timer
864 interrupt preempted.  When it returns control to that thread, it
865 therefore won't get to do much work before the next timer interrupt
866 arrives.  That thread will therefore get blamed for a lot more CPU
867 time than it actually got a chance to use.  This raises the
868 interrupted thread's recent CPU count, thereby lowering its priority.
869 It can cause scheduling decisions to change.  It also raises the load
870 average.
871 @end itemize
872 @end table