750145b184d7ae267e77adcd079d837843ae1748
[pintos-anon] / doc / tour.texi
1 @node Pintos Tour, Project 1--Threads, Introduction, Top
2 @chapter A Tour Through Pintos
3
4 This chapter is a brief tour through the Pintos code.  It covers the
5 entire code base, but you'll only be using Pintos one part at a time,
6 so you may find that you want to read each part as you work on the
7 corresponding project.
8
9 (Actually, the tour is currently incomplete.  It fully covers only the
10 threads project.)
11
12 We recommend using ``tags'' to follow along with references to function
13 and variable names (@pxref{Tags}).
14
15 @menu
16 * Pintos Loading::              
17 * Threads Tour::                
18 * User Programs Tour::          
19 * Virtual Memory Tour::         
20 * File Systems Tour::           
21 @end menu
22
23 @node Pintos Loading
24 @section Loading
25
26 This section covers the Pintos loader and basic kernel
27 initialization.
28
29 @menu
30 * Pintos Loader::               
31 * Kernel Initialization::       
32 @end menu
33
34 @node Pintos Loader
35 @subsection The Loader
36
37 The first part of Pintos that runs is the loader, in
38 @file{threads/loader.S}.  The PC BIOS loads the loader into memory.
39 The loader, in turn, is responsible for initializing the CPU, loading
40 the rest of Pintos into memory, and then jumping to its start.  It's
41 not important to understand exactly what the loader does, but if
42 you're interested, read on.  You should probably read along with the
43 loader's source.  You should also understand the basics of the
44 80@var{x}86 architecture as described by chapter 3 of
45 @bibref{IA32-v1}.
46
47 Because the PC BIOS loads the loader, the loader has to play by the
48 BIOS's rules.  In particular, the BIOS only loads 512 bytes (one disk
49 sector) into memory.  This is a severe restriction and it means that,
50 practically speaking, the loader has to be written in assembly
51 language.
52
53 Pintos' loader first initializes the CPU.  The first important part of
54 this is to enable the A20 line, that is, the CPU's address line
55 numbered 20.  For historical reasons, PCs start out with this address
56 line fixed at 0, which means that attempts to access memory beyond the
57 first 1 MB (2 raised to the 20th power) will fail.  Pintos wants to
58 access more memory than this, so we have to enable it.
59
60 Next, the loader asks the BIOS for the PC's memory size.  Again for
61 historical reasons, the function that we call in the BIOS to do this
62 can only detect up to 64 MB of RAM, so that's the practical limit that
63 Pintos can support.  The memory size is stashed away in a location in
64 the loader that the kernel can read after it boots.
65
66 Third, the loader creates a basic page table.  This page table maps
67 the 64 MB at the base of virtual memory (starting at virtual address
68 0) directly to the identical physical addresses.  It also maps the
69 same physical memory starting at virtual address
70 @code{LOADER_PHYS_BASE}, which defaults to @t{0xc0000000} (3 GB).  The
71 Pintos kernel only wants the latter mapping, but there's a
72 chicken-and-egg problem if we don't include the former: our current
73 virtual address is roughly @t{0x7c00}, the location where the BIOS
74 loaded us, and we can't jump to @t{0xc0007c00} until we turn on the
75 page table, but if we turn on the page table without jumping there,
76 then we've just pulled the rug out from under ourselves.
77
78 After the page table is initialized, we load the CPU's control
79 registers to turn on protected mode and paging, and then we set up the
80 segment registers.  We aren't equipped to handle interrupts in
81 protected mode yet, so we disable interrupts.
82
83 Finally it's time to load the kernel from disk.  We use a simple but
84 inflexible method to do this: we program the IDE disk
85 controller directly.  We assume that the kernel is stored starting
86 from the second sector of the first IDE disk (the first sector normally
87 contains the boot loader).  We also assume that the BIOS has
88 already set up the IDE controller for us.  We read
89 @code{KERNEL_LOAD_PAGES} pages of data (4 kB per page) from the disk directly
90 into virtual memory, starting @code{LOADER_KERN_BASE} bytes past
91 @code{LOADER_PHYS_BASE}, which by default means that we load the
92 kernel starting 1 MB into physical memory.
93
94 Then we jump to the start of the compiled kernel image.  Using the
95 ``linker script'' in @file{threads/kernel.lds.S}, the kernel has
96 arranged that it begins with the assembly module
97 @file{threads/start.S}.  This assembly module just calls
98 @func{main}, which never returns.
99
100 There's one more trick: the Pintos kernel command line
101 is stored in the boot loader.  The @command{pintos} program actually
102 modifies the boot loader on disk each time it runs the kernel, putting
103 in whatever command line arguments the user supplies to the kernel,
104 and then the kernel at boot time reads those arguments out of the boot
105 loader in memory.  This is something of a nasty hack, but it is simple
106 and effective.
107
108 @node Kernel Initialization
109 @subsection Kernel Initialization
110
111 The kernel proper starts with the @func{main} function.  The
112 @func{main} function is written in C, as will be most of the code we
113 encounter in Pintos from here on out.
114
115 When @func{main} starts, the system is in a pretty raw state.  We're
116 in protected mode with paging enabled, but hardly anything else is
117 ready.  Thus, the @func{main} function consists primarily of calls
118 into other Pintos modules' initialization functions.  
119 These are usually named @func{@var{module}_init}, where
120 @var{module} is the module's name, @file{@var{module}.c} is the
121 module's source code, and @file{@var{module}.h} is the module's
122 header.
123
124 First we initialize kernel RAM in @func{ram_init}.  The first step
125 is to clear out the kernel's so-called ``BSS'' segment.  The BSS is a
126 segment that should be initialized to all zeros.  In most C
127 implementations, whenever you
128 declare a variable outside a function without providing an
129 initializer, that variable goes into the BSS.  Because it's all zeros, the
130 BSS isn't stored in the image that the loader brought into memory.  We
131 just use @func{memset} to zero it out.  The other task of
132 @func{ram_init} is to read out the machine's memory size from where
133 the loader stored it and put it into the @code{ram_pages} variable for
134 later use.
135
136 Next, @func{thread_init} initializes the thread system.  We will defer
137 full discussion to our discussion of Pintos threads below.  It is
138 called so early in initialization because the console, initialized
139 just afterward, tries to use locks, and locks in turn require there to be a
140 running thread.
141
142 Then we initialize the console so that we can use @func{printf}.
143 @func{main} calls @func{vga_init}, which initializes the VGA text
144 display and clears the screen.  It also calls @func{serial_init_poll}
145 to initialize the first serial port in ``polling mode,'' that is,
146 where the kernel busy-waits for the port to be ready for each
147 character to be output.  (We use polling mode until we're ready to set
148 up interrupts later.)  Finally we initialize the console device and
149 print a startup message to the console.
150
151 @func{main} calls @func{read_command_line} to break the kernel command
152 line into arguments, then @func{parse_options} to read any options at
153 the beginning of the command line.  (Executing actions specified on the
154 command line happens later.)
155
156 The next block of functions we call initialize the kernel's memory
157 system.  @func{palloc_init} sets up the kernel page allocator, which
158 doles out memory one or more pages at a time.  @func{malloc_init} sets
159 up the allocator that handles odd-sized allocations.
160 @func{paging_init} sets up a page table for the kernel.
161
162 In projects 2 and later, @func{main} also calls @func{tss_init} and
163 @func{gdt_init}, but we'll talk about those later.
164
165 @func{main} calls @func{random_init} to initialize the kernel random
166 number generator.  If the user specified @option{-rs} on the
167 @command{pintos} command line, @func{parse_options} has already done
168 this, but calling it a second time is harmless and has no effect.
169
170 We initialize the interrupt system in the next set of calls.
171 @func{intr_init} sets up the CPU's @dfn{interrupt descriptor table}
172 (IDT) to ready it for interrupt handling (@pxref{Interrupt
173 Infrastructure}), then @func{timer_init} and @func{kbd_init} prepare for
174 handling timer interrupts and keyboard interrupts, respectively.  In
175 projects 2 and later, we also prepare to handle interrupts caused by
176 user programs using @func{exception_init} and @func{syscall_init}.
177
178 Now that interrupts are set up, we can start preemptively scheduling
179 threads with @func{thread_start}, which also enables interrupts.
180 With interrupts enabled, interrupt-driven serial port I/O becomes
181 possible, so we use
182 @func{serial_init_queue} to switch to that mode.  Finally,
183 @func{timer_calibrate} calibrates the timer for accurate short delays.
184
185 If the file system is compiled in, as it will starting in project 2, we
186 now initialize the disks with @func{disk_init}, then the
187 file system with @func{filesys_init}.
188
189 Boot is complete, so we print a message.
190
191 Function @func{run_actions} now parses and executes actions specified on
192 the kernel command line, such as @command{run} to run a test (in project
193 1) or a user program (in later projects).
194
195 Finally, if @option{-q} was specified on the kernel command line, we
196 call @func{power_off} to terminate the machine simulator.  Otherwise,
197 @func{main} calls @func{thread_exit}, which allows any other running
198 threads to continue running.
199
200 @node Threads Tour
201 @section Threads Project
202
203 @menu
204 * Thread Support::              
205 * Synchronization::             
206 * Interrupt Handling::          
207 * Memory Allocation::           
208 @end menu
209
210 @node Thread Support
211 @subsection Thread Support
212
213 @menu
214 * struct thread::               
215 * Thread Functions::            
216 * Thread Switching::            
217 @end menu
218
219 @node struct thread
220 @subsubsection @code{struct thread}
221
222 The main Pintos data structure for threads is @struct{thread},
223 declared in @file{threads/thread.h}.
224
225 @deftp {Structure} {@struct{thread}}
226 Represents a thread or a user process.  In the projects, you will have
227 to add your own members to @struct{thread}.  You may also change or
228 delete the definitions of existing members.
229
230 Every @struct{thread} occupies the beginning of its own page of
231 memory.  The rest of the page is used for the thread's stack, which
232 grows downward from the end of the page.  It looks like this:
233
234 @example
235 @group
236         4 kB +---------------------------------+
237              |          kernel stack           |
238              |                |                |
239              |                |                |
240              |                V                |
241              |         grows downward          |
242              |                                 |
243              |                                 |
244              |                                 |
245              |                                 |
246              |                                 |
247              |                                 |
248              |                                 |
249              |                                 |
250              +---------------------------------+
251              |              magic              |
252              |                :                |
253              |                :                |
254              |              status             |
255              |               tid               |
256         0 kB +---------------------------------+
257 @end group
258 @end example
259
260 This has two consequences.  First, @struct{thread} must not be allowed
261 to grow too big.  If it does, then there will not be enough room for the
262 kernel stack.  The base @struct{thread} is only a few bytes in size.  It
263 probably should stay well under 1 kB.
264
265 Second, kernel stacks must not be allowed to grow too large.  If a stack
266 overflows, it will corrupt the thread state.  Thus, kernel functions
267 should not allocate large structures or arrays as non-static local
268 variables.  Use dynamic allocation with @func{malloc} or
269 @func{palloc_get_page} instead (@pxref{Memory Allocation}).
270 @end deftp
271
272 @deftypecv {Member} {@struct{thread}} {tid_t} tid
273 The thread's thread identifier or @dfn{tid}.  Every thread must have a
274 tid that is unique over the entire lifetime of the kernel.  By
275 default, @code{tid_t} is a @code{typedef} for @code{int} and each new
276 thread receives the numerically next higher tid, starting from 1 for
277 the initial process.  You can change the type and the numbering scheme
278 if you like.
279 @end deftypecv
280
281 @deftypecv {Member} {@struct{thread}} {enum thread_status} status
282 The thread's state, one of the following:
283
284 @defvr {Thread State} @code{THREAD_RUNNING}
285 The thread is running.  Exactly one thread is running at a given time.
286 @func{thread_current} returns the running thread.
287 @end defvr
288
289 @defvr {Thread State} @code{THREAD_READY}
290 The thread is ready to run, but it's not running right now.  The
291 thread could be selected to run the next time the scheduler is
292 invoked.  Ready threads are kept in a doubly linked list called
293 @code{ready_list}.
294 @end defvr
295
296 @defvr {Thread State} @code{THREAD_BLOCKED}
297 The thread is waiting for something, e.g.@: a lock to become
298 available, an interrupt to be invoked.  The thread won't be scheduled
299 again until it transitions to the @code{THREAD_READY} state with a
300 call to @func{thread_unblock}.
301 @end defvr
302
303 @defvr {Thread State} @code{THREAD_DYING}
304 The thread will be destroyed by the scheduler after switching to the
305 next thread.
306 @end defvr
307 @end deftypecv
308
309 @deftypecv {Member} {@struct{thread}} {char} name[16]
310 The thread's name as a string, or at least the first few characters of
311 it.
312 @end deftypecv
313
314 @deftypecv {Member} {@struct{thread}} {uint8_t *} stack
315 Every thread has its own stack to keep track of its state.  When the
316 thread is running, the CPU's stack pointer register tracks the top of
317 the stack and this member is unused.  But when the CPU switches to
318 another thread, this member saves the thread's stack pointer.  No
319 other members are needed to save the thread's registers, because the
320 other registers that must be saved are saved on the stack.
321
322 When an interrupt occurs, whether in the kernel or a user program, an
323 @struct{intr_frame} is pushed onto the stack.  When the interrupt occurs
324 in a user program, the @struct{intr_frame} is always at the very top of
325 the page.  @xref{Interrupt Handling}, for more information.
326 @end deftypecv
327
328 @deftypecv {Member} {@struct{thread}} {int} priority
329 A thread priority, ranging from @code{PRI_MIN} (0) to @code{PRI_MAX}
330 (63).  Lower numbers correspond to @emph{higher} priorities, so that
331 priority 0 is the highest priority and priority 63 is the lowest.
332 Pintos as provided ignores thread priorities, but you will implement
333 priority scheduling in project 1 (@pxref{Priority Scheduling}).
334 @end deftypecv
335
336 @deftypecv {Member} {@struct{thread}} {@struct{list_elem}} elem
337 A ``list element'' used to put the thread into doubly linked lists,
338 either the list of threads ready to run or a list of threads waiting
339 on a semaphore.  Take a look at @file{lib/kernel/list.h} for
340 information on how to use Pintos doubly linked lists.
341 @end deftypecv
342
343 @deftypecv {Member} {@struct{thread}} {uint32_t *} pagedir
344 Only present in project 2 and later.
345 @end deftypecv
346
347 @deftypecv {Member} {@struct{thread}} {unsigned} magic
348 Always set to @code{THREAD_MAGIC}, which is just a random number defined
349 in @file{threads/thread.c}, and used to detect stack overflow.
350 @func{thread_current} checks that the @code{magic} member of the running
351 thread's @struct{thread} is set to @code{THREAD_MAGIC}.  Stack overflow
352 will normally change this value, triggering the assertion.  For greatest
353 benefit, as you add members to @struct{thread}, leave @code{magic} as
354 the final member.
355 @end deftypecv
356
357 @node Thread Functions
358 @subsubsection Thread Functions
359
360 @file{threads/thread.c} implements several public functions for thread
361 support.  Let's take a look at the most useful:
362
363 @deftypefun void thread_init (void)
364 Called by @func{main} to initialize the thread system.  Its main
365 purpose is to create a @struct{thread} for Pintos's initial thread.
366 This is possible because the Pintos loader puts the initial
367 thread's stack at the top of a page, in the same position as any other
368 Pintos thread.
369
370 Before @func{thread_init} runs,
371 @func{thread_current} will fail because the running thread's
372 @code{magic} value is incorrect.  Lots of functions call
373 @func{thread_current} directly or indirectly, including
374 @func{lock_acquire} for locking a lock, so @func{thread_init} is
375 called early in Pintos initialization.
376 @end deftypefun
377
378 @deftypefun void thread_start (void)
379 Called by @func{main} to start the scheduler.  Creates the idle
380 thread, that is, the thread that is scheduled when no other thread is
381 ready.  Then enables interrupts, which as a side effect enables the
382 scheduler because the scheduler runs on return from the timer interrupt, using
383 @func{intr_yield_on_return} (@pxref{External Interrupt Handling}).
384 @end deftypefun
385
386 @deftypefun void thread_tick (void)
387 Called by the timer interrupt at each timer tick.  It keeps track of
388 thread statistics and triggers the scheduler when a time slice expires.
389 @end deftypefun
390
391 @deftypefun void thread_print_stats (void)
392 Called during Pintos shutdown to print thread statistics.
393 @end deftypefun
394
395 @deftypefun tid_t thread_create (const char *@var{name}, int @var{priority}, thread_func *@var{func}, void *@var{aux})
396 Creates and starts a new thread named @var{name} with the given
397 @var{priority}, returning the new thread's tid.  The thread executes
398 @var{func}, passing @var{aux} as the function's single argument.
399
400 @func{thread_create} allocates a page for the thread's
401 @struct{thread} and stack and initializes its members, then it sets
402 up a set of fake stack frames for it (more about this
403 later).  The thread is initialized in the blocked state, so the final
404 action before returning is to unblock it, which allows the new thread to
405 be scheduled.
406 @end deftypefun
407
408 @deftp {Type} {void thread_func (void *@var{aux})}
409 This is the type of a thread function.  Its @var{aux} argument is the
410 value passed to @func{thread_create}.
411 @end deftp
412
413 @deftypefun void thread_block (void)
414 Transitions the running thread from the running state to the blocked
415 state.  The thread will not run again until @func{thread_unblock} is
416 called on it, so you'd better have some way arranged for that to happen.
417 Because @func{thread_block} is so low-level, you should prefer to use
418 one of the synchronization primitives instead (@pxref{Synchronization}).
419 @end deftypefun
420
421 @deftypefun void thread_unblock (struct thread *@var{thread})
422 Transitions @var{thread}, which must be in the blocked state, to the
423 ready state, allowing it to resume running.  This is called when the
424 event that the thread is waiting for occurs, e.g.@: when the lock that
425 the thread is waiting on becomes available.
426 @end deftypefun
427
428 @deftypefun {struct thread *} thread_current (void)
429 Returns the running thread.
430 @end deftypefun
431
432 @deftypefun {tid_t} thread_tid (void)
433 Returns the running thread's thread id.  Equivalent to
434 @code{thread_current ()->tid}.
435 @end deftypefun
436
437 @deftypefun {const char *} thread_name (void)
438 Returns the running thread's name.  Equivalent to @code{thread_current
439 ()->name}.
440 @end deftypefun
441
442 @deftypefun void thread_exit (void) @code{NO_RETURN}
443 Causes the current thread to exit.  Never returns, hence
444 @code{NO_RETURN} (@pxref{Function and Parameter Attributes}).
445 @end deftypefun
446
447 @deftypefun void thread_yield (void)
448 Yields the CPU to the scheduler, which picks a new thread to run.  The
449 new thread might be the current thread, so you can't depend on this
450 function to keep this thread from running for any particular length of
451 time.
452 @end deftypefun
453
454 @deftypefun int thread_get_priority (void)
455 @deftypefunx void thread_set_priority (int @var{new_priority})
456 Skeleton to set and get thread priority.  @xref{Priority Scheduling}.
457 @end deftypefun
458
459 @deftypefun int thread_get_nice (void)
460 @deftypefunx void thread_set_nice (int @var{new_nice})
461 @deftypefunx int thread_get_recent_cpu (void)
462 @deftypefunx int thread_get_load_avg (void)
463 Skeletons for the advanced scheduler.  @xref{4.4BSD Scheduler}.
464 @end deftypefun
465
466 @node Thread Switching
467 @subsubsection Thread Switching
468
469 @func{schedule} is the function responsible for switching threads.  It
470 is internal to @file{threads/thread.c} and called only by the three
471 public thread functions that need to switch threads:
472 @func{thread_block}, @func{thread_exit}, and @func{thread_yield}.
473 Before any of these functions call @func{schedule}, they disable
474 interrupts (or ensure that they are already disabled) and then change
475 the running thread's state to something other than running.
476
477 @func{schedule} is simple but tricky.  It records the
478 current thread in local variable @var{cur}, determines the next thread
479 to run as local variable @var{next} (by calling
480 @func{next_thread_to_run}), and then calls @func{switch_threads} to do
481 the actual thread switch.  The thread we switched to was also running
482 inside @func{switch_threads}, as are all the threads not currently
483 running, so the new thread now returns out of
484 @func{switch_threads}, returning the previously running thread.
485
486 @func{switch_threads} is an assembly language routine in
487 @file{threads/switch.S}.  It saves registers on the stack, saves the
488 CPU's current stack pointer in the current @struct{thread}'s @code{stack}
489 member, restores the new thread's @code{stack} into the CPU's stack
490 pointer, restores registers from the stack, and returns.
491
492 The rest of the scheduler is implemented as @func{schedule_tail}.  It
493 marks the new thread as running.  If the thread we just switched from
494 is in the dying state, then it also frees the page that contained the
495 dying thread's @struct{thread} and stack.  These couldn't be freed
496 prior to the thread switch because the switch needed to use it.
497
498 Running a thread for the first time is a special case.  When
499 @func{thread_create} creates a new thread, it goes through a fair
500 amount of trouble to get it started properly.  In particular, a new
501 thread hasn't started running yet, so there's no way for it to be
502 running inside @func{switch_threads} as the scheduler expects.  To
503 solve the problem, @func{thread_create} creates some fake stack frames
504 in the new thread's stack:
505
506 @itemize @bullet
507 @item
508 The topmost fake stack frame is for @func{switch_threads}, represented
509 by @struct{switch_threads_frame}.  The important part of this frame is
510 its @code{eip} member, the return address.  We point @code{eip} to
511 @func{switch_entry}, indicating it to be the function that called
512 @func{switch_entry}.
513
514 @item
515 The next fake stack frame is for @func{switch_entry}, an assembly
516 language routine in @file{threads/switch.S} that adjusts the stack
517 pointer,@footnote{This is because @func{switch_threads} takes
518 arguments on the stack and the 80@var{x}86 SVR4 calling convention
519 requires the caller, not the called function, to remove them when the
520 call is complete.  See @bibref{SysV-i386} chapter 3 for details.}
521 calls @func{schedule_tail} (this special case is why
522 @func{schedule_tail} is separate from @func{schedule}), and returns.
523 We fill in its stack frame so that it returns into
524 @func{kernel_thread}, a function in @file{threads/thread.c}.
525
526 @item
527 The final stack frame is for @func{kernel_thread}, which enables
528 interrupts and calls the thread's function (the function passed to
529 @func{thread_create}).  If the thread's function returns, it calls
530 @func{thread_exit} to terminate the thread.
531 @end itemize
532
533 @node Synchronization
534 @subsection Synchronization
535
536 If sharing of resources between threads is not handled in a careful,
537 controlled fashion, then the result is usually a big mess.
538 This is especially the case in operating system kernels, where
539 faulty sharing can crash the entire machine.  Pintos provides several
540 synchronization primitives to help out.
541
542 @menu
543 * Disabling Interrupts::        
544 * Semaphores::                  
545 * Locks::                       
546 * Condition Variables::         
547 * Memory Barriers::             
548 @end menu
549
550 @node Disabling Interrupts
551 @subsubsection Disabling Interrupts
552
553 The crudest way to do synchronization is to disable interrupts, that
554 is, to temporarily prevent the CPU from responding to interrupts.  If
555 interrupts are off, no other thread will preempt the running thread,
556 because thread preemption is driven by the timer interrupt.  If
557 interrupts are on, as they normally are, then the running thread may
558 be preempted by another at any time, whether between two C statements
559 or even within the execution of one.
560
561 Incidentally, this means that Pintos is a ``preemptible kernel,'' that
562 is, kernel threads can be preempted at any time.  Traditional Unix
563 systems are ``nonpreemptible,'' that is, kernel threads can only be
564 preempted at points where they explicitly call into the scheduler.
565 (User programs can be preempted at any time in both models.)  As you
566 might imagine, preemptible kernels require more explicit
567 synchronization.
568
569 You should have little need to set the interrupt state directly.  Most
570 of the time you should use the other synchronization primitives
571 described in the following sections.  The main reason to disable
572 interrupts is to synchronize kernel threads with external interrupt
573 handlers, which cannot sleep and thus cannot use most other forms of
574 synchronization (@pxref{External Interrupt Handling}).
575
576 Types and functions for disabling and enabling interrupts are in
577 @file{threads/interrupt.h}.
578
579 @deftp Type {enum intr_level}
580 One of @code{INTR_OFF} or @code{INTR_ON}, denoting that interrupts are
581 disabled or enabled, respectively.
582 @end deftp
583
584 @deftypefun {enum intr_level} intr_get_level (void)
585 Returns the current interrupt state.
586 @end deftypefun
587
588 @deftypefun {enum intr_level} intr_set_level (enum intr_level @var{level})
589 Turns interrupts on or off according to @var{level}.  Returns the
590 previous interrupt state.
591 @end deftypefun
592
593 @deftypefun {enum intr_level} intr_enable (void)
594 Turns interrupts on.  Returns the previous interrupt state.
595 @end deftypefun
596
597 @deftypefun {enum intr_level} intr_disable (void)
598 Turns interrupts off.  Returns the previous interrupt state.
599 @end deftypefun
600
601 @node Semaphores
602 @subsubsection Semaphores
603
604 Pintos' semaphore type and operations are declared in
605 @file{threads/synch.h}.
606
607 @deftp {Type} {struct semaphore}
608 Represents a @dfn{semaphore}, a nonnegative integer together with two
609 operators that manipulate it atomically, which are:
610
611 @itemize @bullet
612 @item
613 ``Down'' or ``P'': wait for the value to become positive, then
614 decrement it.
615
616 @item
617 ``Up'' or ``V'': increment the value (and wake up one waiting thread,
618 if any).
619 @end itemize
620
621 A semaphore initialized to 0 may be used to wait for an event
622 that will happen exactly once.  For example, suppose thread @var{A}
623 starts another thread @var{B} and wants to wait for @var{B} to signal
624 that some activity is complete.  @var{A} can create a semaphore
625 initialized to 0, pass it to @var{B} as it starts it, and then
626 ``down'' the semaphore.  When @var{B} finishes its activity, it
627 ``ups'' the semaphore.  This works regardless of whether @var{A}
628 ``downs'' the semaphore or @var{B} ``ups'' it first.
629
630 A semaphore initialized to 1 is typically used for controlling access
631 to a resource.  Before a block of code starts using the resource, it
632 ``downs'' the semaphore, then after it is done with the resource it
633 ``ups'' the resource.  In such a case a lock, described below, may be
634 more appropriate.
635
636 Semaphores can also be initialized to values larger than 1.  These are
637 rarely used.
638 @end deftp
639
640 @deftypefun void sema_init (struct semaphore *@var{sema}, unsigned @var{value})
641 Initializes @var{sema} as a new semaphore with the given initial
642 @var{value}.
643 @end deftypefun
644
645 @deftypefun void sema_down (struct semaphore *@var{sema})
646 Executes the ``down'' or ``P'' operation on @var{sema}, waiting for
647 its value to become positive and then decrementing it by one.
648 @end deftypefun
649
650 @deftypefun bool sema_try_down (struct semaphore *@var{sema})
651 Tries to execute the ``down'' or ``P'' operation on @var{sema},
652 without waiting.  Returns true if @var{sema} had a positive value
653 that was successfully decremented, or false if it was already
654 zero and thus could not be decremented.  Calling this function in a
655 tight loop wastes CPU time (use @func{sema_down} instead, or find a
656 different approach).
657 @end deftypefun
658
659 @deftypefun void sema_up (struct semaphore *@var{sema})
660 Executes the ``up'' or ``V'' operation on @var{sema},
661 incrementing its value.  If any threads are waiting on
662 @var{sema}, wakes one of them up.
663 @end deftypefun
664
665 Semaphores are internally built out of disabling interrupt
666 (@pxref{Disabling Interrupts}) and thread blocking and unblocking
667 (@func{thread_block} and @func{thread_unblock}).  Each semaphore maintains
668 a list of waiting threads, using the linked list
669 implementation in @file{lib/kernel/list.c}.
670
671 @node Locks
672 @subsubsection Locks
673
674 Lock types and functions are declared in @file{threads/synch.h}.
675
676 @deftp {Type} {struct lock}
677 Represents a @dfn{lock}, a specialized semaphore with an initial value
678 of 1 (@pxref{Semaphores}).  The difference between a lock and such a
679 semaphore is twofold.  First, a semaphore does not have an owner,
680 meaning that one thread can ``down'' the semaphore and then another one
681 ``up'' it, but a single thread must both acquire and release a lock.
682 Second, a semaphore can have a value greater than 1, but a lock can only
683 be owned by a single thread at a time.  If these restrictions prove
684 onerous, it's a good sign that a semaphore should be used, instead of a
685 lock.
686
687 Locks in Pintos are not ``recursive,'' that is, it is an error for the
688 thread currently holding a lock to try to acquire that lock.
689 @end deftp
690
691 @deftypefun void lock_init (struct lock *@var{lock})
692 Initializes @var{lock} as a new lock.
693 @end deftypefun
694
695 @deftypefun void lock_acquire (struct lock *@var{lock})
696 Acquires @var{lock} for use by the current thread, first waiting for
697 any current owner to release it if necessary.
698 @end deftypefun
699
700 @deftypefun bool lock_try_acquire (struct lock *@var{lock})
701 Tries to acquire @var{lock} for use by the current thread, without
702 waiting.  Returns true if successful, false if the lock is already
703 owned.  Calling this function in a tight loop is a bad idea because it
704 wastes CPU time (use @func{lock_acquire} instead).
705 @end deftypefun
706
707 @deftypefun void lock_release (struct lock *@var{lock})
708 Releases @var{lock}, which the current thread must own.
709 @end deftypefun
710
711 @deftypefun bool lock_held_by_current_thread (const struct lock *@var{lock})
712 Returns true if the running thread owns @var{lock},
713 false otherwise.
714 @end deftypefun
715
716 @node Condition Variables
717 @subsubsection Condition Variables
718
719 Condition variable types and functions are declared in
720 @file{threads/synch.h}.
721
722 @deftp {Type} {struct condition}
723 Represents a condition variable, which allows one piece of code to
724 signal a condition
725 and cooperating code to receive the signal and act upon it.  Each
726 condition variable is associated with a lock.  A given condition
727 variable is associated with only a single lock, but one lock may be
728 associated with any number of condition variables.  A set of condition
729 variables taken together with their lock is called a ``monitor.''
730
731 A thread that owns the monitor lock is said to be ``in the monitor.''
732 The thread in the monitor has control over all the data protected by
733 the lock.  It may freely examine or modify this data.  If it discovers
734 that it needs to wait for some condition to become true, then it
735 ``waits'' on the associated condition, which releases the lock and
736 waits for the condition to be signaled.  If, on the other hand, it has
737 caused one of these conditions to become true, it ``signals'' the
738 condition to wake up one waiter, or ``broadcasts'' the condition to
739 wake all of them.
740
741 Pintos monitors are ``Mesa'' style, not
742 ``Hoare'' style.  That is, sending and receiving a signal are not an
743 atomic operation.  Thus, typically the caller must recheck the
744 condition after the wait completes and, if necessary, wait again.
745 @end deftp
746
747 @deftypefun void cond_init (struct condition *@var{cond})
748 Initializes @var{cond} as a new condition variable.
749 @end deftypefun
750
751 @deftypefun void cond_wait (struct condition *@var{cond}, struct lock *@var{lock})
752 Atomically releases @var{lock} (the monitor lock) and waits for
753 @var{cond} to be signaled by some other piece of code.  After
754 @var{cond} is signaled, reacquires @var{lock} before returning.
755 @var{lock} must be held before calling this function.
756 @end deftypefun
757
758 @deftypefun void cond_signal (struct condition *@var{cond}, struct lock *@var{lock})
759 If any threads are waiting on @var{cond} (protected by monitor lock
760 @var{lock}), then this function wakes up one of them.  If no threads are
761 waiting, returns without performing any action.
762 @var{lock} must be held before calling this function.
763 @end deftypefun
764
765 @deftypefun void cond_broadcast (struct condition *@var{cond}, struct lock *@var{lock})
766 Wakes up all threads, if any, waiting on @var{cond} (protected by
767 monitor lock @var{lock}).  @var{lock} must be held before calling this
768 function.
769 @end deftypefun
770
771 @subsubheading Monitor Example
772
773 The classical example of a monitor is handling a buffer into which one
774 ``producer'' thread writes characters and out of which a second
775 ``consumer'' thread reads characters.  To implement this case we need,
776 besides the monitor lock, two condition variables which we will call
777 @var{not_full} and @var{not_empty}:
778
779 @example
780 char buf[BUF_SIZE];     /* @r{Buffer.} */
781 size_t n = 0;           /* @r{0 <= n <= @var{BUF_SIZE}: # of characters in buffer.} */
782 size_t head = 0;        /* @r{@var{buf} index of next char to write (mod @var{BUF_SIZE}).} */
783 size_t tail = 0;        /* @r{@var{buf} index of next char to read (mod @var{BUF_SIZE}).} */
784 struct lock lock;       /* @r{Monitor lock.} */
785 struct condition not_empty; /* @r{Signaled when the buffer is not empty.} */
786 struct condition not_full; /* @r{Signaled when the buffer is not full.} */
787
788 @dots{}@r{initialize the locks and condition variables}@dots{}
789
790 void put (char ch) @{
791   lock_acquire (&lock);
792   while (n == BUF_SIZE)            /* @r{Can't add to @var{buf} as long as it's full.} */
793     cond_wait (&not_full, &lock);
794   buf[head++ % BUF_SIZE] = ch;     /* @r{Add @var{ch} to @var{buf}.} */
795   n++;
796   cond_signal (&not_empty, &lock); /* @r{@var{buf} can't be empty anymore.} */
797   lock_release (&lock);
798 @}
799
800 char get (void) @{
801   char ch;
802   lock_acquire (&lock);
803   while (n == 0)                  /* @r{Can't read @var{buf} as long as it's empty.} */
804     cond_wait (&not_empty, &lock);
805   ch = buf[tail++ % BUF_SIZE];    /* @r{Get @var{ch} from @var{buf}.} */
806   n--;
807   cond_signal (&not_full, &lock); /* @r{@var{buf} can't be full anymore.} */
808   lock_release (&lock);
809 @}
810 @end example
811
812 @node Memory Barriers
813 @subsubsection Memory Barriers
814
815 Suppose we add a ``feature'' that, whenever a timer interrupt
816 occurs, the character in global variable @code{timer_put_char} is
817 printed on the console, but only if global Boolean variable
818 @code{timer_do_put} is true.
819
820 If interrupts are enabled, this code for setting up @samp{x} to be
821 printed is clearly incorrect, because the timer interrupt could intervene
822 between the two assignments:
823
824 @example
825 timer_do_put = true;            /* INCORRECT CODE */
826 timer_put_char = 'x';
827 @end example
828
829 It might not be as obvious that the following code is just as
830 incorrect:
831
832 @example
833 timer_put_char = 'x';           /* INCORRECT CODE */
834 timer_do_put = true;
835 @end example
836
837 The reason this second example might be a problem is that the compiler
838 is, in general, free to reorder operations when it doesn't have a
839 visible reason to keep them in the same order.  In this case, the
840 compiler doesn't know that the order of assignments is important, so its
841 optimization pass is permitted to exchange their order.
842 There's no telling whether it will actually do this, and it is possible
843 that passing the compiler different optimization flags or changing
844 compiler versions will produce different behavior.
845
846 The following is @emph{not} a solution, because locks neither prevent
847 interrupts nor prevent the compiler from reordering the code within the
848 region where the lock is held:
849
850 @example
851 lock_acquire (&timer_lock);     /* INCORRECT CODE */
852 timer_put_char = 'x';
853 timer_do_put = true;
854 lock_release (&timer_lock);
855 @end example
856
857 Fortunately, real solutions do exist.  One possibility is to
858 disable interrupts around the assignments.  This does not prevent
859 reordering, but it makes the assignments atomic as observed by the
860 interrupt handler.  It also has the extra runtime cost of disabling and
861 re-enabling interrupts:
862
863 @example
864 enum intr_level old_level = intr_disable ();
865 timer_put_char = 'x';
866 timer_do_put = true;
867 intr_set_level (old_level);
868 @end example
869
870 A second possibility is to mark the declarations of
871 @code{timer_put_char} and @code{timer_do_put} as @samp{volatile}.  This
872 keyword tells the compiler that the variables are externally observable
873 and allows it less latitude for optimization.  However, the semantics of
874 @samp{volatile} are not well-defined, so it is not a good general
875 solution.
876
877 Usually, the best solution is to use a compiler feature called a
878 @dfn{memory barrier}, a special statement that prevents the compiler
879 from reordering memory operations across the barrier.  In Pintos,
880 @file{threads/synch.h} defines the @code{barrier()} macro as a memory
881 barrier.  Here's how we would use a memory barrier to fix this code:
882
883 @example
884 timer_put_char = 'x';
885 barrier ();
886 timer_do_put = true;
887 @end example
888
889 The compiler also treats invocation of any function defined externally,
890 that is, in another source file, as a limited form of a memory barrier.
891 Specifically, the compiler assumes that any externally defined function
892 may access any statically or dynamically allocated data and any local
893 variable whose address is taken.  This often means that explicit
894 barriers can be omitted, and, indeed, this is why the base Pintos code
895 does not need any barriers.
896
897 A function defined in the same source file, or in a header included by
898 the source file, cannot be relied upon as a memory barrier.
899 This applies even to invocation of a function before its
900 definition, because the compiler may read and parse the entire source
901 file before performing optimization.
902
903 @node Interrupt Handling
904 @subsection Interrupt Handling
905
906 An @dfn{interrupt} notifies the CPU of some event.  Much of the work
907 of an operating system relates to interrupts in one way or another.
908 For our purposes, we classify interrupts into two broad categories:
909
910 @itemize @bullet
911 @item
912 @dfn{External interrupts}, that is, interrupts originating outside the
913 CPU.  These interrupts come from hardware devices such as the system
914 timer, keyboard, serial ports, and disks.  External interrupts are
915 @dfn{asynchronous}, meaning that their delivery is not
916 synchronized with normal CPU activities.  External interrupts
917 are what @func{intr_disable} and related functions
918 postpone (@pxref{Disabling Interrupts}).
919
920 @item
921 @dfn{Internal interrupts}, that is, interrupts caused by something
922 executing on the CPU.  These interrupts are caused by something
923 unusual happening during instruction execution: accessing invalid
924 memory (a @dfn{page fault}), executing invalid instructions, and
925 various other disallowed activities.  Because they are caused by CPU
926 instructions, internal interrupts are @dfn{synchronous} or
927 synchronized with CPU instructions.  @func{intr_disable} does not
928 disable internal interrupts.
929 @end itemize
930
931 Because the CPU treats all interrupts largely the same way, regardless
932 of source, Pintos uses the same infrastructure for both internal and
933 external interrupts, to a point.  The following section describes this
934 common infrastructure, and sections after that give the specifics of
935 external and internal interrupts.
936
937 If you haven't already read chapter 3 in @bibref{IA32-v1}, it is
938 recommended that you do so now.  You might also want to skim chapter 5
939 in @bibref{IA32-v3}.
940
941 @menu
942 * Interrupt Infrastructure::    
943 * Internal Interrupt Handling::  
944 * External Interrupt Handling::  
945 @end menu
946
947 @node Interrupt Infrastructure
948 @subsubsection Interrupt Infrastructure
949
950 When an interrupt occurs while the kernel is running, the CPU saves
951 its most essential state on the stack and jumps to an interrupt
952 handler routine.  The 80@var{x}86 architecture allows for 256 possible
953 interrupts, each of which can have its own handler. The handler for
954 each interrupt is defined in an array called the @dfn{interrupt
955 descriptor table} or IDT.
956
957 In Pintos, @func{intr_init} in @file{threads/interrupt.c} sets up the
958 IDT so that each entry points to a unique entry point in
959 @file{threads/intr-stubs.S} named @func{intr@var{NN}_stub}, where
960 @var{NN} is the interrupt number in
961 hexadecimal.  Because the CPU doesn't give
962 us any other way to find out the interrupt number, this entry point
963 pushes the interrupt number on the stack.  Then it jumps to
964 @func{intr_entry}, which pushes all the registers that the processor
965 didn't already save for us, and then calls @func{intr_handler}, which
966 brings us back into C in @file{threads/interrupt.c}.
967
968 The main job of @func{intr_handler} is to call any function that has
969 been registered for handling the particular interrupt.  (If no
970 function is registered, it dumps some information to the console and
971 panics.)  It does some extra processing for external
972 interrupts that we'll discuss later.
973
974 When @func{intr_handler} returns, the assembly code in
975 @file{threads/intr-stubs.S} restores all the CPU registers saved
976 earlier and directs the CPU to return from the interrupt.
977
978 A few types and functions apply to both internal and external
979 interrupts.
980
981 @deftp {Type} {void intr_handler_func (struct intr_frame *@var{frame})}
982 This is how an interrupt handler function must be declared.  Its @var{frame}
983 argument (see below) allows it to determine the cause of the interrupt
984 and the state of the thread that was interrupted.
985 @end deftp
986
987 @deftp {Type} {struct intr_frame}
988 The stack frame of an interrupt handler, as saved by CPU, the interrupt
989 stubs, and @func{intr_entry}. Its most interesting members are described
990 below.
991 @end deftp
992
993 @deftypecv {Member} {@struct{intr_frame}} uint32_t edi
994 @deftypecvx {Member} {@struct{intr_frame}} uint32_t esi
995 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ebp
996 @deftypecvx {Member} {@struct{intr_frame}} uint32_t esp_dummy
997 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ebx
998 @deftypecvx {Member} {@struct{intr_frame}} uint32_t edx
999 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ecx
1000 @deftypecvx {Member} {@struct{intr_frame}} uint32_t eax
1001 @deftypecvx {Member} {@struct{intr_frame}} uint16_t es
1002 @deftypecvx {Member} {@struct{intr_frame}} uint16_t ds
1003 Register values in the interrupted thread saved by @func{intr_entry}.
1004 The @code{esp_dummy} value isn't actually used (refer to the
1005 description of @code{PUSHA} in @bibref{IA32-v2b} for details).
1006 @end deftypecv
1007
1008 @deftypecv {Member} {@struct{intr_frame}} uint32_t vec_no
1009 The interrupt vector number, ranging from 0 to 255.
1010 @end deftypecv
1011
1012 @deftypecv {Member} {@struct{intr_frame}} uint32_t error_code
1013 The ``error code'' pushed on the stack by the CPU for some internal
1014 interrupts.
1015 @end deftypecv
1016
1017 @deftypecv {Member} {@struct{intr_frame}} void (*eip) (void)
1018 The address of the next instruction to be executed by the interrupted
1019 thread. 
1020 @end deftypecv
1021
1022 @deftypecv {Member} {@struct{intr_frame}} {void *} esp
1023 The interrupted thread's stack pointer.
1024 @end deftypecv
1025
1026 @deftypefun {const char *} intr_name (uint8_t @var{vec})
1027 Returns the name of the interrupt numbered @var{vec}, or
1028 @code{"unknown"} if the interrupt has no registered name.
1029 @end deftypefun
1030
1031 @node Internal Interrupt Handling
1032 @subsubsection Internal Interrupt Handling
1033
1034 When an internal interrupt occurs, it is because the running kernel
1035 thread (or, starting from project 2, the running user process) has
1036 caused it.  Thus, because it is related to a thread (or process), an
1037 internal interrupt is said to happen in a ``process context.''
1038
1039 In an internal interrupt, it can make sense to examine the
1040 @struct{intr_frame} passed to the interrupt handler, or even to modify
1041 it.  When the interrupt returns, modified members
1042 in @struct{intr_frame} become changes to the thread's registers.
1043 We'll use this in project 2 to return values from system call
1044 handlers.
1045
1046 There are no special restrictions on what an internal interrupt
1047 handler can or can't do.  Generally they should run with interrupts
1048 enabled, just like other code, and so they can be preempted by other
1049 kernel threads.  Thus, they do need to synchronize with other threads
1050 on shared data and other resources (@pxref{Synchronization}).
1051
1052 @deftypefun void intr_register_int (uint8_t @var{vec}, int @var{dpl}, enum intr_level @var{level}, intr_handler_func *@var{handler}, const char *@var{name})
1053 Registers @var{handler} to be called when internal interrupt numbered
1054 @var{vec} is triggered.  Names the interrupt @var{name} for debugging
1055 purposes.
1056
1057 If @var{level} is @code{INTR_OFF} then handling of further interrupts
1058 will be disabled while the interrupt is being processed.  Interrupts
1059 should normally be turned on during the handling of an internal
1060 interrupt.
1061
1062 @var{dpl} determines how the interrupt can be
1063 invoked.  If @var{dpl} is 0, then the interrupt can be invoked only by
1064 kernel threads.  Otherwise @var{dpl} should be 3, which allows user
1065 processes to invoke the interrupt as well (this is useful only
1066 starting with project 2).
1067 @end deftypefun
1068
1069 @node External Interrupt Handling
1070 @subsubsection External Interrupt Handling
1071
1072 Whereas an internal interrupt runs in the context of the thread that
1073 caused it, external interrupts do not have any predictable context.
1074 They are asynchronous, so they can be invoked at any time that
1075 interrupts have not been disabled.  We say that an external interrupt
1076 runs in an ``interrupt context.''
1077
1078 In an external interrupt, the @struct{intr_frame} passed to the
1079 handler is not very meaningful.  It describes the state of the thread
1080 or process that was interrupted, but there is no way to predict which
1081 one that is.  It is possible, although rarely useful, to examine it, but
1082 modifying it is a recipe for disaster.
1083
1084 The activities of an external interrupt handler are severely
1085 restricted.  First, only one external interrupt may be processed at a
1086 time, that is, nested external interrupt handling is not supported.
1087 This means that external interrupts must be processed with interrupts
1088 disabled (@pxref{Disabling Interrupts}) and that interrupts may not be
1089 enabled at any point during their execution.
1090
1091 Second, an interrupt handler must not call any function that can
1092 sleep, which rules out @func{thread_yield}, @func{lock_acquire}, and
1093 many others.  This is because external interrupts use space on the
1094 stack of the kernel thread that was running at the time the interrupt
1095 occurred.  If the interrupt handler tried to sleep and that thread
1096 resumed, then the two uses of the single stack would interfere, which
1097 cannot be allowed.
1098
1099 Because an external interrupt runs with interrupts disabled, it
1100 effectively monopolizes the machine and delays all other activities.
1101 Therefore, external interrupt handlers should complete as quickly as
1102 they can.  Any activities that require much CPU time should instead
1103 run in a kernel thread, possibly a thread whose activity is triggered
1104 by the interrupt using some synchronization primitive.
1105
1106 External interrupts are also special because they are controlled by a
1107 pair of devices outside the CPU called @dfn{programmable interrupt
1108 controllers}, @dfn{PICs} for short.  When @func{intr_init} sets up the
1109 CPU's IDT, it also initializes the PICs for interrupt handling.  The
1110 PICs also must be ``acknowledged'' at the end of processing for each
1111 external interrupt.  @func{intr_handler} takes care of that by calling
1112 @func{pic_end_of_interrupt}, which sends the proper signals to the
1113 right PIC.
1114
1115 The following additional functions are related to external
1116 interrupts.
1117
1118 @deftypefun void intr_register_ext (uint8_t @var{vec}, intr_handler_func *@var{handler}, const char *@var{name})
1119 Registers @var{handler} to be called when external interrupt numbered
1120 @var{vec} is triggered.  Names the interrupt @var{name} for debugging
1121 purposes.  The handler will run with interrupts disabled.
1122 @end deftypefun
1123
1124 @deftypefun bool intr_context (void)
1125 Returns true if we are running in an interrupt context, otherwise
1126 false.  Mainly used at the beginning of functions that might sleep
1127 or that otherwise should not be called from interrupt context, in this
1128 form:
1129 @example
1130 ASSERT (!intr_context ());
1131 @end example
1132 @end deftypefun
1133
1134 @deftypefun void intr_yield_on_return (void)
1135 When called in an interrupt context, causes @func{thread_yield} to be
1136 called just before the interrupt returns.  This is used, for example,
1137 in the timer interrupt handler to cause a new thread to be scheduled
1138 when a thread's time slice expires.
1139 @end deftypefun
1140
1141 @node Memory Allocation
1142 @subsection Memory Allocation
1143
1144 Pintos contains two memory allocators, one that allocates memory in
1145 units of a page, and one that can allocate blocks of any size.
1146
1147 @menu
1148 * Page Allocator::              
1149 * Block Allocator::             
1150 @end menu
1151
1152 @node Page Allocator
1153 @subsubsection Page Allocator
1154
1155 The page allocator declared in @file{threads/palloc.h} allocates
1156 memory in units of a page.  It is most often used to allocate memory
1157 one page at a time, but it can also allocate multiple contiguous pages
1158 at once.
1159
1160 The page allocator divides the memory it allocates into two pools,
1161 called the kernel and user pools.  By default, each pool gets half of
1162 system memory, but this can be changed with a kernel command line
1163 option (@pxref{Why PAL_USER?}).  An allocation request draws from one
1164 pool or the other.  If one pool becomes empty, the other may still
1165 have free pages.  The user pool should be used for allocating memory
1166 for user processes and the kernel pool for all other allocations.
1167 This will only become important starting with project 3.  Until then,
1168 all allocations should be made from the kernel pool.
1169
1170 Each pool's usage is tracked with a bitmap, one bit per page in
1171 the pool.  A request to allocate @var{n} pages scans the bitmap
1172 for @var{n} consecutive bits set to
1173 false, indicating that those pages are free, and then sets those bits
1174 to true to mark them as used.  This is a ``first fit'' allocation
1175 strategy.
1176
1177 The page allocator is subject to fragmentation.  That is, it may not
1178 be possible to allocate @var{n} contiguous pages even though @var{n}
1179 or more pages are free, because the free pages are separated by used
1180 pages.  In fact, in pathological cases it may be impossible to
1181 allocate 2 contiguous pages even though @var{n} / 2 pages are free!
1182 Single-page requests can't fail due to fragmentation, so
1183 it is best to limit, as much as possible, the need for multiple
1184 contiguous pages.
1185
1186 Pages may not be allocated from interrupt context, but they may be
1187 freed.
1188
1189 When a page is freed, all of its bytes are cleared to @t{0xcc}, as
1190 a debugging aid (@pxref{Debugging Tips}).
1191
1192 Page allocator types and functions are described below.
1193
1194 @deftp {Type} {enum palloc_flags}
1195 A set of flags that describe how to allocate pages.  These flags may
1196 be combined in any combination.
1197 @end deftp
1198
1199 @defvr {Page Allocator Flag} @code{PAL_ASSERT}
1200 If the pages cannot be allocated, panic the kernel.  This is only
1201 appropriate during kernel initialization.  User processes
1202 should never be permitted to panic the kernel.
1203 @end defvr
1204
1205 @defvr {Page Allocator Flag} @code{PAL_ZERO}
1206 Zero all the bytes in the allocated pages before returning them.  If not
1207 set, the contents of newly allocated pages are unpredictable.
1208 @end defvr
1209
1210 @defvr {Page Allocator Flag} @code{PAL_USER}
1211 Obtain the pages from the user pool.  If not set, pages are allocated
1212 from the kernel pool.
1213 @end defvr
1214
1215 @deftypefun {void *} palloc_get_page (enum palloc_flags @var{flags})
1216 Obtains and returns a single page, allocating it in the manner specified by
1217 @var{flags}.  Returns a null pointer if no pages are
1218 free.
1219 @end deftypefun
1220
1221 @deftypefun {void *} palloc_get_multiple (enum palloc_flags @var{flags}, size_t @var{page_cnt})
1222 Obtains @var{page_cnt} contiguous free pages, allocating them in the
1223 manner specified by @var{flags}, and returns them.  Returns a null
1224 pointer if no pages are free.
1225 @end deftypefun
1226
1227 @deftypefun void palloc_free_page (void *@var{page})
1228 Frees @var{page}, which must have been obtained using
1229 @func{palloc_get_page} or @func{palloc_get_multiple}.
1230 @end deftypefun
1231
1232 @deftypefun void palloc_free_multiple (void *@var{pages}, size_t @var{page_cnt})
1233 Frees the @var{page_cnt} contiguous pages starting at @var{pages}.
1234 All of the pages must have been obtained using @func{palloc_get_page}
1235 or @func{palloc_get_multiple}.
1236 @end deftypefun
1237
1238 @node Block Allocator
1239 @subsubsection Block Allocator
1240
1241 The block allocator, declared in @file{threads/malloc.h}, can allocate
1242 blocks of any size.  It is layered on top of the page allocator
1243 described in the previous section.  Blocks returned by the block
1244 allocator are obtained from the kernel pool.
1245
1246 The block allocator uses two different strategies for allocating
1247 memory.  The first of these applies to ``small'' blocks, those 1 kB or
1248 smaller (one
1249 fourth of the the page size).  These allocations are rounded up to the
1250 nearest power of 2, or 16 bytes, whichever is larger.  Then they are
1251 grouped into a page used only for allocations of the smae
1252 size.
1253
1254 The second strategy applies to allocating ``large'' blocks, those larger
1255 than 1 kB.
1256 These allocations (plus a small amount of overhead) are rounded up to
1257 the nearest page in size, and then the block allocator requests that
1258 number of contiguous pages from the page allocator.  
1259
1260 In either case, the difference between the allocation requested size
1261 and the actual block size is wasted.  A real operating system would
1262 carefully tune its allocator to minimize this waste, but this is
1263 unimportant in an instructional system like Pintos.
1264
1265 As long as a page can be obtained from the page allocator, small
1266 allocations always succeed.  Most small allocations will not require a
1267 new page from the page allocator at all.  However, large allocations
1268 always require calling into the page allocator, and any allocation
1269 that needs more than one contiguous page can fail due to fragmentation,
1270 as already discussed in the previous section.  Thus, you should
1271 minimize the number of large allocations in your code, especially
1272 those over approximately 4 kB each.
1273
1274 The interface to the block allocator is through the standard C library
1275 functions @func{malloc}, @func{calloc}, and @func{free}.
1276
1277 When a block is freed, all of its bytes are cleared to @t{0xcc}, as
1278 a debugging aid (@pxref{Debugging Tips}).
1279
1280 The block allocator may not be called from interrupt context.
1281
1282 @node User Programs Tour
1283 @section User Programs Project
1284
1285 The tour for this project has not yet been written.
1286
1287 @node Virtual Memory Tour
1288 @section Virtual Memory Project
1289
1290 The tour for this project is under construction.
1291
1292 @menu
1293 * Hash Table::                  
1294 @end menu
1295
1296 @node Hash Table
1297 @subsection Hash Table
1298
1299 Most implementations of the virtual memory project use a hash table to
1300 translate virtual page frames to physical page frames.  It is possible
1301 to do this translation without adding a new data structure, by modifying
1302 the code in @file{userprog/pagedir.c}.  However, if you do that you'll
1303 need to carefully study and understand section 3.7 in @bibref{IA32-v3},
1304 and in practice it is probably easier to add a new data structure.  You
1305 may find other uses for hash tables as well.
1306
1307 Pintos provides a hash table data structure in @file{lib/kernel/hash.c}.
1308 To use it you will need to manually include its header file,
1309 @file{lib/kernel/hash.h}, with @code{#include <hash.h>}.  Intentionally,
1310 no code provided with Pintos uses the hash table, which means that you
1311 are free to use it as is, modify its implementation for your own
1312 purposes, or ignore it, as you wish.
1313
1314 @menu
1315 * Hash Data Types::             
1316 * Basic Hash Functions::        
1317 * Hash Search Functions::       
1318 * Hash Iteration Functions::    
1319 * Hash Table Example::          
1320 * Hash Auxiliary Data::         
1321 * Hash Synchronization::        
1322 @end menu
1323
1324 @node Hash Data Types
1325 @subsubsection Data Types
1326
1327 A hash table is represented by @struct{hash}.
1328
1329 @deftp {Type} {@struct{hash}}
1330 Represents an entire hash table.  The actual members of @struct{hash}
1331 are ``opaque.''  That is, code that uses a hash table should not access
1332 @struct{hash} members directly, nor should it need to.  Instead, use
1333 hash table functions and macros.
1334 @end deftp
1335
1336 The hash table operates on elements of type @struct{hash_elem}.  
1337
1338 @deftp {Type} {@struct{hash_elem}}
1339 Embed a @struct{hash_elem} member in the structure you want to include
1340 in a hash table.  Like @struct{hash}, @struct{hash_elem} is opaque.
1341 All functions for operating on hash table elements actually take and
1342 return pointers to @struct{hash_elem}, not pointers to your hash table's
1343 real element type.
1344 @end deftp
1345
1346 You will often need to obtain a @struct{hash_elem}
1347 given a real element of the hash table, and vice versa.  Given
1348 a real element of the hash table, obtaining a pointer to its
1349 @struct{hash_elem} is trivial: take the address of the
1350 @struct{hash_elem} member.  Use the @code{hash_entry()} macro to go the
1351 other direction.
1352
1353 @deftypefn {Macro} {@var{type} *} hash_entry (struct hash_elem *@var{elem}, @var{type}, @var{member})
1354 Returns a pointer to the structure that @var{elem}, a pointer to a
1355 @struct{hash_elem}, is embedded within.  You must provide @var{type},
1356 the name of the structure that @var{elem} is inside, and @var{member},
1357 the name of the member in @var{type} that @var{elem} points to.
1358
1359 For example, suppose @code{h} is a @code{struct hash_elem *} variable
1360 that points to a @struct{thread} member (of type @struct{hash_elem})
1361 named @code{h_elem}.  Then, @code{hash_entry (h, struct thread, h_elem)}
1362 yields the address of the @struct{thread} that @code{h} points within.
1363 @end deftypefn
1364
1365 Each hash table element must contain a key, that is, data that
1366 identifies and distinguishes elements in the hash table.  Every element
1367 in a hash table at a given time must have a unique key.  (Elements may
1368 also contain non-key data that need not be unique.)  While an element is
1369 in a hash table, its key data must not be changed.  For each hash table,
1370 you must write two functions that act on keys: a hash function and a
1371 comparison function.  These functions must match the following
1372 prototypes:
1373
1374 @deftp {Type} {unsigned hash_hash_func (const struct hash_elem *@var{element}, void *@var{aux})}
1375 Returns a hash of @var{element}'s data, as a value anywhere in the range
1376 of @code{unsigned int}.  The hash of an element should be a
1377 pseudo-random function of the element's key.  It must not depend on
1378 non-key data in the element or on any non-constant data other than the
1379 key.  Pintos provides the following functions as a suitable basis for
1380 hash functions.
1381
1382 @deftypefun unsigned hash_bytes (const void *@var{buf}, size_t *@var{size})
1383 Returns a hash of the @var{size} bytes starting at @var{buf}.  The
1384 implementation is the general-purpose
1385 @uref{http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash, Fowler-Noll-Vo
1386 hash} for 32-bit words.
1387 @end deftypefun
1388
1389 @deftypefun unsigned hash_string (const char *@var{s})
1390 Returns a hash of null-terminated string @var{s}.
1391 @end deftypefun
1392
1393 @deftypefun unsigned hash_int (int @var{i}) 
1394 Returns a hash of integer @var{i}.
1395 @end deftypefun
1396
1397 If your key is a single piece of data of an appropriate type, it is
1398 sensible for your hash function to directly return the output of one of
1399 these functions.  For multiple pieces of data, you may wish to combine
1400 the output of more than one call to them using, e.g., the @samp{^}
1401 operator.  Finally, you may entirely ignore these functions and write
1402 your own hash function from scratch, but remember that your goal is to
1403 build an operating system kernel, not to design a hash function.
1404
1405 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1406 @end deftp
1407
1408 @deftp {Type} {bool hash_less_func (const struct hash_elem *@var{a}, const struct hash_elem *@var{b}, void *@var{aux})}
1409 Compares the keys stored in elements @var{a} and @var{b}.  Returns
1410 true if @var{a} is less than @var{b}, false if @var{a} is greater than
1411 or equal to @var{b}.
1412
1413 If two elements compare equal, then they must hash to equal values.
1414
1415 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1416 @end deftp
1417
1418 A few functions that act on hashes accept a pointer to a third kind of
1419 function as an argument:
1420
1421 @deftp {Type} {void hash_action_func (struct hash_elem *@var{element}, void *@var{aux})}
1422 Performs some kind of action, chosen by the caller, on @var{element}.
1423
1424 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1425 @end deftp
1426
1427 @node Basic Hash Functions
1428 @subsubsection Basic Functions
1429
1430 These functions create and destroy hash tables and obtain basic
1431 information about their contents.
1432
1433 @deftypefun bool hash_init (struct hash *@var{hash}, hash_hash_func *@var{hash_func}, hash_less_func *@var{less_func}, void *@var{aux})
1434 Initializes @var{hash} as a hash table using @var{hash_func} as hash
1435 function, @var{less_func} as comparison function, and @var{aux} as
1436 auxiliary data.
1437 Returns true if successful, false on failure.  @func{hash_init} calls
1438 @func{malloc} and fails if memory cannot be allocated.
1439
1440 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}, which is
1441 most often a null pointer.
1442 @end deftypefun
1443
1444 @deftypefun void hash_clear (struct hash *@var{hash}, hash_action_func *@var{action})
1445 Removes all the elements from @var{hash}, which must have been
1446 previously initialized with @func{hash_init}.
1447
1448 If @var{action} is non-null, then it is called once for each element in
1449 the hash table, which gives the caller an opportunity to deallocate any
1450 memory or other resources used by the element.  For example, if the hash
1451 table elements are dynamically allocated using @func{malloc}, then
1452 @var{action} could @func{free} the element.  This is safe because
1453 @func{hash_clear} will not access the memory in a given hash element
1454 after calling @var{action} on it.  However, @var{action} must not call
1455 any function that may modify the hash table, such as @func{hash_insert}
1456 or @func{hash_delete}.
1457 @end deftypefun
1458
1459 @deftypefun void hash_destroy (struct hash *@var{hash}, hash_action_func *@var{action})
1460 If @var{action} is non-null, calls it for each element in the hash, with
1461 the same semantics as a call to @func{hash_clear}.  Then, frees the
1462 memory held by @var{hash}.  Afterward, @var{hash} must not be passed to
1463 any hash table function, absent an intervening call to @func{hash_init}.
1464 @end deftypefun
1465
1466 @deftypefun size_t hash_size (struct hash *@var{hash})
1467 Returns the number of elements currently stored in @var{hash}.
1468 @end deftypefun
1469
1470 @deftypefun bool hash_empty (struct hash *@var{hash})
1471 Returns true if @var{hash} currently contains no elements,
1472 false if @var{hash} contains at least one element.
1473 @end deftypefun
1474
1475 @node Hash Search Functions
1476 @subsubsection Search Functions
1477
1478 Each of these functions searches a hash table for an element that
1479 compares equal to one provided.  Based on the success of the search,
1480 they perform some action, such as inserting a new element into the hash
1481 table, or simply return the result of the search.
1482
1483 @deftypefun {struct hash_elem *} hash_insert (struct hash *@var{hash}, struct hash_elem *@var{element})
1484 Searches @var{hash} for an element equal to @var{element}.  If none is
1485 found, inserts @var{element} into @var{hash} and returns a null pointer.
1486 If the table already contains an element equal to @var{element}, returns
1487 the existing element without modifying @var{hash}.
1488 @end deftypefun
1489
1490 @deftypefun {struct hash_elem *} hash_replace (struct hash *@var{hash}, struct hash_elem *@var{element})
1491 Inserts @var{element} into @var{hash}.  Any element equal to
1492 @var{element} already in @var{hash} is removed.  Returns the element
1493 removed, or a null pointer if @var{hash} did not contain an element
1494 equal to @var{element}.
1495
1496 The caller is responsible for deallocating any resources associated with
1497 the element returned, as appropriate.  For example, if the hash table
1498 elements are dynamically allocated using @func{malloc}, then the caller
1499 must @func{free} the element after it is no longer needed.
1500 @end deftypefun
1501
1502 The element passed to the following functions is only used for hashing
1503 and comparison purposes.  It is never actually inserted into the hash
1504 table.  Thus, only the key data in the element need be initialized, and
1505 other data in the element will not be used.  It often makes sense to
1506 declare an instance of the element type as a local variable, initialize
1507 the key data, and then pass the address of its @struct{hash_elem} to
1508 @func{hash_find} or @func{hash_delete}.  @xref{Hash Table Example}, for
1509 an example.  (Large structures should not be
1510 allocated as local variables.  @xref{struct thread}, for more
1511 information.)
1512
1513 @deftypefun {struct hash_elem *} hash_find (struct hash *@var{hash}, struct hash_elem *@var{element})
1514 Searches @var{hash} for an element equal to @var{element}.  Returns the
1515 element found, if any, or a null pointer otherwise.
1516 @end deftypefun
1517
1518 @deftypefun {struct hash_elem *} hash_delete (struct hash *@var{hash}, struct hash_elem *@var{element})
1519 Searches @var{hash} for an element equal to @var{element}.  If one is
1520 found, it is removed from @var{hash} and returned.  Otherwise, a null
1521 pointer is returned and @var{hash} is unchanged.
1522
1523 The caller is responsible for deallocating any resources associated with
1524 the element returned, as appropriate.  For example, if the hash table
1525 elements are dynamically allocated using @func{malloc}, then the caller
1526 must @func{free} the element after it is no longer needed.
1527 @end deftypefun
1528
1529 @node Hash Iteration Functions
1530 @subsubsection Iteration Functions
1531
1532 These functions allow iterating through the elements in a hash table.
1533 Two interfaces are supplied.  The first requires writing and supplying a
1534 @var{hash_action_func} to act on each element (@pxref{Hash Data Types}).
1535
1536 @deftypefun void hash_apply (struct hash *@var{hash}, hash_action_func *@var{action})
1537 Calls @var{action} once for each element in @var{hash}, in arbitrary
1538 order.  @var{action} must not call any function that may modify the hash
1539 table, such as @func{hash_insert} or @func{hash_delete}.  @var{action}
1540 must not modify key data in elements, although it may modify any other
1541 data.
1542 @end deftypefun
1543
1544 The second interface is based on an ``iterator'' data type.
1545 Idiomatically, iterators are used as follows:
1546
1547 @example
1548 struct hash_iterator i;
1549
1550 hash_first (&i, h);
1551 while (hash_next (&i))
1552   @{
1553     struct foo *f = hash_entry (hash_cur (&i), struct foo, elem);
1554     @r{@dots{}do something with @i{f}@dots{}}
1555   @}
1556 @end example
1557
1558 @deftp {Type} {@struct{hash_iterator}}
1559 Represents a position within a hash table.  Calling any function that
1560 may modify a hash table, such as @func{hash_insert} or
1561 @func{hash_delete}, invalidates all iterators within that hash table.
1562
1563 Like @struct{hash} and @struct{hash_elem}, @struct{hash_elem} is opaque.
1564 @end deftp
1565
1566 @deftypefun void hash_first (struct hash_iterator *@var{iterator}, struct hash *@var{hash})
1567 Initializes @var{iterator} to just before the first element in
1568 @var{hash}.
1569 @end deftypefun
1570
1571 @deftypefun {struct hash_elem *} hash_next (struct hash_iterator *@var{iterator})
1572 Advances @var{iterator} to the next element in @var{hash}, and returns
1573 that element.  Returns a null pointer if no elements remain.  After
1574 @func{hash_next} returns null for @var{iterator}, calling it again
1575 yields undefined behavior.
1576 @end deftypefun
1577
1578 @deftypefun {struct hash_elem *} hash_cur (struct hash_iterator *@var{iterator})
1579 Returns the value most recently returned by @func{hash_next} for
1580 @var{iterator}.  Yields undefined behavior after @func{hash_first} has
1581 been called on @var{iterator} but before @func{hash_next} has been
1582 called for the first time.
1583 @end deftypefun
1584
1585 @node Hash Table Example
1586 @subsubsection Hash Table Example
1587
1588 Suppose you have a structure, called @struct{page}, that you
1589 want to put into a hash table.  First, define @struct{page} to include a
1590 @struct{hash_elem} member:
1591
1592 @example
1593 struct page
1594   @{
1595     struct hash_elem hash_elem; /* @r{Hash table element.} */
1596     void *addr;                 /* @r{Virtual address.} */
1597     /* @r{@dots{}other members@dots{}} */
1598   @};
1599 @end example
1600
1601 We write a hash function and a comparison function using @var{addr} as
1602 the key.  A pointer can be hashed based on its bytes, and the @samp{<}
1603 operator works fine for comparing pointers:
1604
1605 @example
1606 /* @r{Returns a hash value for page @var{p}.} */
1607 unsigned
1608 page_hash (const struct hash_elem *p_, void *aux UNUSED) 
1609 @{
1610   const struct page *p = hash_entry (p_, struct page, hash_elem);
1611   return hash_bytes (&p->addr, sizeof p->addr);
1612 @}
1613
1614 /* @r{Returns true if page @var{a} precedes page @var{b}.} */
1615 bool
1616 page_less (const struct hash_elem *a_, const struct hash_elem *b_,
1617            void *aux UNUSED) 
1618 @{
1619   const struct page *a = hash_entry (a_, struct page, hash_elem);
1620   const struct page *b = hash_entry (b_, struct page, hash_elem);
1621   
1622   return a->addr < b->addr;
1623 @}
1624 @end example
1625
1626 @noindent
1627 (The use of @code{UNUSED} in these functions' prototypes suppresses a
1628 warning that @var{aux} is unused.  @xref{Function and Parameter
1629 Attributes}, for information about @code{UNUSED}.  @xref{Hash Auxiliary
1630 Data}, for an explanation of @var{aux}.)
1631
1632 Then, we can create a hash table like this:
1633
1634 @example
1635 struct hash pages;
1636
1637 hash_init (&pages, page_hash, page_less, NULL);
1638 @end example
1639
1640 Now we can manipulate the hash table we've created.  If @code{@var{p}}
1641 is a pointer to a @struct{page}, we can insert it into the hash table
1642 with:
1643
1644 @example
1645 hash_insert (&pages, &p->hash_elem);
1646 @end example
1647
1648 @noindent If there's a chance that @var{pages} might already contain a
1649 page with the same @var{addr}, then we should check @func{hash_insert}'s
1650 return value.
1651
1652 To search for an element in the hash table, use @func{hash_find}.  This
1653 takes a little setup, because @func{hash_find} takes an element to
1654 compare against.  Here's a function that will find and return a page
1655 based on a virtual address, assuming that @var{pages} is defined at file
1656 scope:
1657
1658 @example
1659 /* @r{Returns the page containing the given virtual @var{address},
1660    or a null pointer if no such page exists.} */
1661 struct page *
1662 page_lookup (const void *address) 
1663 @{
1664   struct page p;
1665   struct hash_elem *e;
1666
1667   p.addr = address;
1668   e = hash_find (&pages, &p.hash_elem);
1669   return e != NULL ? hash_entry (e, struct page, hash_elem) : NULL;
1670 @}
1671 @end example
1672
1673 @noindent
1674 @struct{page} is allocated as a local variable here on the assumption
1675 that it is fairly small.  Large structures should not be allocated as
1676 local variables.  @xref{struct thread}, for more information.
1677
1678 A similar function could delete a page by address using
1679 @func{hash_delete}.
1680
1681 @node Hash Auxiliary Data
1682 @subsubsection Auxiliary Data
1683
1684 In simple cases like the example above, there's no need for the
1685 @var{aux} parameters.  In these cases, just pass a null pointer to
1686 @func{hash_init} for @var{aux} and ignore the values passed to the hash
1687 function and comparison functions.  (You'll get a compiler warning if
1688 you don't use the @var{aux} parameter, but you can turn that off with
1689 the @code{UNUSED} macro, as shown in the example, or you can just ignore
1690 it.)
1691
1692 @var{aux} is useful when you have some property of the data in the
1693 hash table that's both constant and needed for hashing or comparisons,
1694 but which is not stored in the data items themselves.  For example, if
1695 the items in a hash table contain fixed-length strings, but the items
1696 themselves don't indicate what that fixed length is, you could pass
1697 the length as an @var{aux} parameter.
1698
1699 @node Hash Synchronization
1700 @subsubsection Synchronization
1701
1702 The hash table does not do any internal synchronization.  It is the
1703 caller's responsibility to synchronize calls to hash table functions.
1704 In general, any number of functions that examine but do not modify the
1705 hash table, such as @func{hash_find} or @func{hash_next}, may execute
1706 simultaneously.  However, these function cannot safely execute at the
1707 same time as any function that may modify a given hash table, such as
1708 @func{hash_insert} or @func{hash_delete}, nor may more than one function
1709 that can modify a given hash table execute safely at once.
1710
1711 It is also the caller's responsibility to synchronize access to data in
1712 hash table elements.  How to synchronize access to this data depends on
1713 how it is designed and organized, as with any other data structure.
1714
1715 @node File Systems Tour
1716 @section File Systems Project
1717
1718 The tour for this project has not yet been written.
1719