bcdcd63324bca3b01efc4c32ba796de1bb9c1d0b
[pintos-anon] / doc / reference.texi
1 @node Reference Guide
2 @appendix Reference Guide
3
4 This chapter is a reference for 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 project where it becomes important.
8
9 (Actually, the reference guide is currently incomplete.)
10
11 We recommend using ``tags'' to follow along with references to function
12 and variable names (@pxref{Tags}).
13
14 @menu
15 * Pintos Loading::              
16 * Threads::                     
17 * Synchronization::             
18 * Interrupt Handling::          
19 * Memory Allocation::           
20 * Virtual Addresses::           
21 * Page Table::                  
22 * Hash Table::                  
23 @end menu
24
25 @node Pintos Loading
26 @section Loading
27
28 This section covers the Pintos loader and basic kernel
29 initialization.
30
31 @menu
32 * Pintos Loader::               
33 * Kernel Initialization::       
34 @end menu
35
36 @node Pintos Loader
37 @subsection The Loader
38
39 The first part of Pintos that runs is the loader, in
40 @file{threads/loader.S}.  The PC BIOS loads the loader into memory.
41 The loader, in turn, is responsible for initializing the CPU, loading
42 the rest of Pintos into memory, and then jumping to its start.  It's
43 not important to understand exactly what the loader does, but if
44 you're interested, read on.  You should probably read along with the
45 loader's source.  You should also understand the basics of the
46 80@var{x}86 architecture as described by chapter 3, ``Basic Execution
47 Environment,'' of @bibref{IA32-v1}.
48
49 Because the PC BIOS loads the loader, the loader has to play by the
50 BIOS's rules.  In particular, the BIOS only loads 512 bytes (one disk
51 sector) into memory.  This is a severe restriction and it means that,
52 practically speaking, the loader has to be written in assembly
53 language.
54
55 The Pintos loader first initializes the CPU.  The first important part of
56 this is to enable the A20 line, that is, the CPU's address line
57 numbered 20.  For historical reasons, PCs boot with this address
58 line fixed at 0, which means that attempts to access memory beyond the
59 first 1 MB (2 raised to the 20th power) will fail.  Pintos wants to
60 access more memory than this, so we have to enable it.
61
62 Next, the loader asks the BIOS for the PC's memory size.  Again for
63 historical reasons, the function that we call in the BIOS to do this
64 can only detect up to 64 MB of RAM, so that's the practical limit that
65 Pintos can support.  The memory size is stashed away in a location in
66 the loader that the kernel can read after it boots.
67
68 Third, the loader creates a basic page table.  This page table maps
69 the 64 MB at the base of virtual memory (starting at virtual address
70 0) directly to the identical physical addresses.  It also maps the
71 same physical memory starting at virtual address
72 @code{LOADER_PHYS_BASE}, which defaults to @t{0xc0000000} (3 GB).  The
73 Pintos kernel only wants the latter mapping, but there's a
74 chicken-and-egg problem if we don't include the former: our current
75 virtual address is roughly @t{0x7c00}, the location where the BIOS
76 loaded us, and we can't jump to @t{0xc0007c00} until we turn on the
77 page table, but if we turn on the page table without jumping there,
78 then we've just pulled the rug out from under ourselves.
79
80 After the page table is initialized, we load the CPU's control
81 registers to turn on protected mode and paging, and then we set up the
82 segment registers.  We aren't yet equipped to handle interrupts in
83 protected mode, so we disable interrupts.
84
85 Finally it's time to load the kernel from disk.  We use a simple but
86 inflexible method to do this: we program the IDE disk
87 controller directly.  We assume that the kernel is stored starting
88 from the second sector of the first IDE disk (the first sector normally
89 contains the boot loader).  We also assume that the BIOS has
90 already set up the IDE controller for us.  We read
91 @code{KERNEL_LOAD_PAGES} pages of data (4 kB per page) from the disk directly
92 into virtual memory, starting @code{LOADER_KERN_BASE} bytes past
93 @code{LOADER_PHYS_BASE}, which by default means that we load the
94 kernel starting 1 MB into physical memory.
95
96 Then we jump to the start of the compiled kernel image.  Using the
97 ``linker script'' in @file{threads/kernel.lds.S}, the kernel has
98 arranged to begin with the assembly module
99 @file{threads/start.S}.  This assembly module just calls
100 @func{main}, which never returns.
101
102 There's one more trick: the Pintos kernel command line
103 is stored in the boot loader.  The @command{pintos} program actually
104 modifies a copy of the boot loader on disk each time it runs the kernel,
105 putting
106 in whatever command line arguments the user supplies to the kernel,
107 and then the kernel at boot time reads those arguments out of the boot
108 loader in memory.  This is not an elegant solution, but it is simple
109 and effective.
110
111 @node Kernel Initialization
112 @subsection Kernel Initialization
113
114 The kernel proper starts with the @func{main} function.  The
115 @func{main} function is written in C, as will be most of the code we
116 encounter in Pintos from here on out.
117
118 When @func{main} starts, the system is in a pretty raw state.  We're
119 in 32-bit protected mode with paging enabled, but hardly anything else is
120 ready.  Thus, the @func{main} function consists primarily of calls
121 into other Pintos modules' initialization functions.
122 These are usually named @func{@var{module}_init}, where
123 @var{module} is the module's name, @file{@var{module}.c} is the
124 module's source code, and @file{@var{module}.h} is the module's
125 header.
126
127 First we initialize kernel RAM in @func{ram_init}.  The first step
128 is to clear out the kernel's so-called ``BSS'' segment.  The BSS is a
129 segment that should be initialized to all zeros.  In most C
130 implementations, whenever you
131 declare a variable outside a function without providing an
132 initializer, that variable goes into the BSS.  Because it's all zeros, the
133 BSS isn't stored in the image that the loader brought into memory.  We
134 just use @func{memset} to zero it out.  The other task of
135 @func{ram_init} is to read out the machine's memory size from where
136 the loader stored it and put it into the @code{ram_pages} variable for
137 later use.
138
139 Next, @func{main} calls @func{read_command_line} to break the kernel command
140 line into arguments, then @func{parse_options} to read any options at
141 the beginning of the command line.  (Actions specified on the
142 command line execute later.)
143
144 @func{thread_init} initializes the thread system.  We will defer full
145 discussion to our discussion of Pintos threads below.  It is called so
146 early in initialization because a valid thread structure is a
147 prerequisite for acquiring a lock, and lock acquisition in turn is
148 important to other Pintos subsystems.  Then we initialize the console
149 and print a startup message to the console.
150
151 The next block of functions we call initializes the kernel's memory
152 system.  @func{palloc_init} sets up the kernel page allocator, which
153 doles out memory one or more pages at a time (@pxref{Page Allocator}).
154 @func{malloc_init} sets
155 up the allocator that handles allocations of arbitrary-size blocks of
156 memory (@pxref{Block Allocator}).
157 @func{paging_init} sets up a page table for the kernel (@pxref{Page
158 Table}).
159
160 In projects 2 and later, @func{main} also calls @func{tss_init} and
161 @func{gdt_init}.
162
163 The next set of calls initializes the interrupt system.
164 @func{intr_init} sets up the CPU's @dfn{interrupt descriptor table}
165 (IDT) to ready it for interrupt handling (@pxref{Interrupt
166 Infrastructure}), then @func{timer_init} and @func{kbd_init} prepare for
167 handling timer interrupts and keyboard interrupts, respectively. 
168 @func{input_init} sets up to merge serial and keyboard input into one
169 stream.  In
170 projects 2 and later, we also prepare to handle interrupts caused by
171 user programs using @func{exception_init} and @func{syscall_init}.
172
173 Now that interrupts are set up, we can start the scheduler
174 with @func{thread_start}, which creates the idle thread and enables
175 interrupts.
176 With interrupts enabled, interrupt-driven serial port I/O becomes
177 possible, so we use
178 @func{serial_init_queue} to switch to that mode.  Finally,
179 @func{timer_calibrate} calibrates the timer for accurate short delays.
180
181 If the file system is compiled in, as it will starting in project 2, we
182 initialize the disks with @func{disk_init}, then the
183 file system with @func{filesys_init}.
184
185 Boot is complete, so we print a message.
186
187 Function @func{run_actions} now parses and executes actions specified on
188 the kernel command line, such as @command{run} to run a test (in project
189 1) or a user program (in later projects).
190
191 Finally, if @option{-q} was specified on the kernel command line, we
192 call @func{power_off} to terminate the machine simulator.  Otherwise,
193 @func{main} calls @func{thread_exit}, which allows any other running
194 threads to continue running.
195
196 @node Threads
197 @section Threads
198
199 @menu
200 * struct thread::               
201 * Thread Functions::            
202 * Thread Switching::            
203 @end menu
204
205 @node struct thread
206 @subsection @code{struct thread}
207
208 The main Pintos data structure for threads is @struct{thread},
209 declared in @file{threads/thread.h}.
210
211 @deftp {Structure} {struct thread}
212 Represents a thread or a user process.  In the projects, you will have
213 to add your own members to @struct{thread}.  You may also change or
214 delete the definitions of existing members.
215
216 Every @struct{thread} occupies the beginning of its own page of
217 memory.  The rest of the page is used for the thread's stack, which
218 grows downward from the end of the page.  It looks like this:
219
220 @example
221 @group
222                   4 kB +---------------------------------+
223                        |          kernel stack           |
224                        |                |                |
225                        |                |                |
226                        |                V                |
227                        |         grows downward          |
228                        |                                 |
229                        |                                 |
230                        |                                 |
231                        |                                 |
232                        |                                 |
233                        |                                 |
234                        |                                 |
235                        |                                 |
236 sizeof (struct thread) +---------------------------------+
237                        |              magic              |
238                        |                :                |
239                        |                :                |
240                        |              status             |
241                        |               tid               |
242                   0 kB +---------------------------------+
243 @end group
244 @end example
245
246 This has two consequences.  First, @struct{thread} must not be allowed
247 to grow too big.  If it does, then there will not be enough room for the
248 kernel stack.  The base @struct{thread} is only a few bytes in size.  It
249 probably should stay well under 1 kB.
250
251 Second, kernel stacks must not be allowed to grow too large.  If a stack
252 overflows, it will corrupt the thread state.  Thus, kernel functions
253 should not allocate large structures or arrays as non-static local
254 variables.  Use dynamic allocation with @func{malloc} or
255 @func{palloc_get_page} instead (@pxref{Memory Allocation}).
256 @end deftp
257
258 @deftypecv {Member} {@struct{thread}} {tid_t} tid
259 The thread's thread identifier or @dfn{tid}.  Every thread must have a
260 tid that is unique over the entire lifetime of the kernel.  By
261 default, @code{tid_t} is a @code{typedef} for @code{int} and each new
262 thread receives the numerically next higher tid, starting from 1 for
263 the initial process.  You can change the type and the numbering scheme
264 if you like.
265 @end deftypecv
266
267 @deftypecv {Member} {@struct{thread}} {enum thread_status} status
268 @anchor{Thread States}
269 The thread's state, one of the following:
270
271 @defvr {Thread State} @code{THREAD_RUNNING}
272 The thread is running.  Exactly one thread is running at a given time.
273 @func{thread_current} returns the running thread.
274 @end defvr
275
276 @defvr {Thread State} @code{THREAD_READY}
277 The thread is ready to run, but it's not running right now.  The
278 thread could be selected to run the next time the scheduler is
279 invoked.  Ready threads are kept in a doubly linked list called
280 @code{ready_list}.
281 @end defvr
282
283 @defvr {Thread State} @code{THREAD_BLOCKED}
284 The thread is waiting for something, e.g.@: a lock to become
285 available, an interrupt to be invoked.  The thread won't be scheduled
286 again until it transitions to the @code{THREAD_READY} state with a
287 call to @func{thread_unblock}.  This is most conveniently done
288 indirectly, using one of the Pintos synchronization primitives that
289 block and unblock threads automatically (@pxref{Synchronization}).
290
291 There is no @i{a priori} way to tell what a blocked thread is waiting
292 for, but a backtrace can help (@pxref{Backtraces}).
293 @end defvr
294
295 @defvr {Thread State} @code{THREAD_DYING}
296 The thread will be destroyed by the scheduler after switching to the
297 next thread.
298 @end defvr
299 @end deftypecv
300
301 @deftypecv {Member} {@struct{thread}} {char} name[16]
302 The thread's name as a string, or at least the first few characters of
303 it.
304 @end deftypecv
305
306 @deftypecv {Member} {@struct{thread}} {uint8_t *} stack
307 Every thread has its own stack to keep track of its state.  When the
308 thread is running, the CPU's stack pointer register tracks the top of
309 the stack and this member is unused.  But when the CPU switches to
310 another thread, this member saves the thread's stack pointer.  No
311 other members are needed to save the thread's registers, because the
312 other registers that must be saved are saved on the stack.
313
314 When an interrupt occurs, whether in the kernel or a user program, an
315 @struct{intr_frame} is pushed onto the stack.  When the interrupt occurs
316 in a user program, the @struct{intr_frame} is always at the very top of
317 the page.  @xref{Interrupt Handling}, for more information.
318 @end deftypecv
319
320 @deftypecv {Member} {@struct{thread}} {int} priority
321 A thread priority, ranging from @code{PRI_MIN} (0) to @code{PRI_MAX}
322 (63).  Lower numbers correspond to lower priorities, so that
323 priority 0 is the lowest priority and priority 63 is the highest.
324 Pintos as provided ignores thread priorities, but you will implement
325 priority scheduling in project 1 (@pxref{Priority Scheduling}).
326 @end deftypecv
327
328 @deftypecv {Member} {@struct{thread}} {@struct{list_elem}} elem
329 A ``list element'' used to put the thread into doubly linked lists,
330 either @code{ready_list} (the list of threads ready to run) or a list of
331 threads waiting on a semaphore in @func{sema_down}.  It can do double
332 duty because a thread waiting on a semaphore is not ready, and vice
333 versa.
334 @end deftypecv
335
336 @deftypecv {Member} {@struct{thread}} {uint32_t *} pagedir
337 Only present in project 2 and later.  @xref{Page Tables}.
338 @end deftypecv
339
340 @deftypecv {Member} {@struct{thread}} {unsigned} magic
341 Always set to @code{THREAD_MAGIC}, which is just an arbitrary number defined
342 in @file{threads/thread.c}, and used to detect stack overflow.
343 @func{thread_current} checks that the @code{magic} member of the running
344 thread's @struct{thread} is set to @code{THREAD_MAGIC}.  Stack overflow
345 tends to change this value, triggering the assertion.  For greatest
346 benefit, as you add members to @struct{thread}, leave @code{magic} at
347 the end.
348 @end deftypecv
349
350 @node Thread Functions
351 @subsection Thread Functions
352
353 @file{threads/thread.c} implements several public functions for thread
354 support.  Let's take a look at the most useful:
355
356 @deftypefun void thread_init (void)
357 Called by @func{main} to initialize the thread system.  Its main
358 purpose is to create a @struct{thread} for Pintos's initial thread.
359 This is possible because the Pintos loader puts the initial
360 thread's stack at the top of a page, in the same position as any other
361 Pintos thread.
362
363 Before @func{thread_init} runs,
364 @func{thread_current} will fail because the running thread's
365 @code{magic} value is incorrect.  Lots of functions call
366 @func{thread_current} directly or indirectly, including
367 @func{lock_acquire} for locking a lock, so @func{thread_init} is
368 called early in Pintos initialization.
369 @end deftypefun
370
371 @deftypefun void thread_start (void)
372 Called by @func{main} to start the scheduler.  Creates the idle
373 thread, that is, the thread that is scheduled when no other thread is
374 ready.  Then enables interrupts, which as a side effect enables the
375 scheduler because the scheduler runs on return from the timer interrupt, using
376 @func{intr_yield_on_return} (@pxref{External Interrupt Handling}).
377 @end deftypefun
378
379 @deftypefun void thread_tick (void)
380 Called by the timer interrupt at each timer tick.  It keeps track of
381 thread statistics and triggers the scheduler when a time slice expires.
382 @end deftypefun
383
384 @deftypefun void thread_print_stats (void)
385 Called during Pintos shutdown to print thread statistics.
386 @end deftypefun
387
388 @deftypefun tid_t thread_create (const char *@var{name}, int @var{priority}, thread_func *@var{func}, void *@var{aux})
389 Creates and starts a new thread named @var{name} with the given
390 @var{priority}, returning the new thread's tid.  The thread executes
391 @var{func}, passing @var{aux} as the function's single argument.
392
393 @func{thread_create} allocates a page for the thread's
394 @struct{thread} and stack and initializes its members, then it sets
395 up a set of fake stack frames for it (@pxref{Thread Switching}).  The
396 thread is initialized in the blocked state, then unblocked just before
397 returning, which allows the new thread to
398 be scheduled (@pxref{Thread States}).
399
400 @deftp {Type} {void thread_func (void *@var{aux})}
401 This is the type of the function passed to @func{thread_create}, whose
402 @var{aux} argument is passed along as the function's argument.
403 @end deftp
404 @end deftypefun
405
406 @deftypefun void thread_block (void)
407 Transitions the running thread from the running state to the blocked
408 state (@pxref{Thread States}).  The thread will not run again until
409 @func{thread_unblock} is
410 called on it, so you'd better have some way arranged for that to happen.
411 Because @func{thread_block} is so low-level, you should prefer to use
412 one of the synchronization primitives instead (@pxref{Synchronization}).
413 @end deftypefun
414
415 @deftypefun void thread_unblock (struct thread *@var{thread})
416 Transitions @var{thread}, which must be in the blocked state, to the
417 ready state, allowing it to resume running (@pxref{Thread States}).
418 This is called when the event that the thread is waiting for occurs,
419 e.g.@: when the lock that 
420 the thread is waiting on becomes available.
421 @end deftypefun
422
423 @deftypefun {struct thread *} thread_current (void)
424 Returns the running thread.
425 @end deftypefun
426
427 @deftypefun {tid_t} thread_tid (void)
428 Returns the running thread's thread id.  Equivalent to
429 @code{thread_current ()->tid}.
430 @end deftypefun
431
432 @deftypefun {const char *} thread_name (void)
433 Returns the running thread's name.  Equivalent to @code{thread_current
434 ()->name}.
435 @end deftypefun
436
437 @deftypefun void thread_exit (void) @code{NO_RETURN}
438 Causes the current thread to exit.  Never returns, hence
439 @code{NO_RETURN} (@pxref{Function and Parameter Attributes}).
440 @end deftypefun
441
442 @deftypefun void thread_yield (void)
443 Yields the CPU to the scheduler, which picks a new thread to run.  The
444 new thread might be the current thread, so you can't depend on this
445 function to keep this thread from running for any particular length of
446 time.
447 @end deftypefun
448
449 @deftypefun int thread_get_priority (void)
450 @deftypefunx void thread_set_priority (int @var{new_priority})
451 Stub to set and get thread priority.  @xref{Priority Scheduling}.
452 @end deftypefun
453
454 @deftypefun int thread_get_nice (void)
455 @deftypefunx void thread_set_nice (int @var{new_nice})
456 @deftypefunx int thread_get_recent_cpu (void)
457 @deftypefunx int thread_get_load_avg (void)
458 Stubs for the advanced scheduler.  @xref{4.4BSD Scheduler}.
459 @end deftypefun
460
461 @node Thread Switching
462 @subsection Thread Switching
463
464 @func{schedule} is responsible for switching threads.  It
465 is internal to @file{threads/thread.c} and called only by the three
466 public thread functions that need to switch threads:
467 @func{thread_block}, @func{thread_exit}, and @func{thread_yield}.
468 Before any of these functions call @func{schedule}, they disable
469 interrupts (or ensure that they are already disabled) and then change
470 the running thread's state to something other than running.
471
472 @func{schedule} is short but tricky.  It records the
473 current thread in local variable @var{cur}, determines the next thread
474 to run as local variable @var{next} (by calling
475 @func{next_thread_to_run}), and then calls @func{switch_threads} to do
476 the actual thread switch.  The thread we switched to was also running
477 inside @func{switch_threads}, as are all the threads not currently
478 running, so the new thread now returns out of
479 @func{switch_threads}, returning the previously running thread.
480
481 @func{switch_threads} is an assembly language routine in
482 @file{threads/switch.S}.  It saves registers on the stack, saves the
483 CPU's current stack pointer in the current @struct{thread}'s @code{stack}
484 member, restores the new thread's @code{stack} into the CPU's stack
485 pointer, restores registers from the stack, and returns.
486
487 The rest of the scheduler is implemented in @func{schedule_tail}.  It
488 marks the new thread as running.  If the thread we just switched from
489 is in the dying state, then it also frees the page that contained the
490 dying thread's @struct{thread} and stack.  These couldn't be freed
491 prior to the thread switch because the switch needed to use it.
492
493 Running a thread for the first time is a special case.  When
494 @func{thread_create} creates a new thread, it goes through a fair
495 amount of trouble to get it started properly.  In particular, the new
496 thread hasn't started running yet, so there's no way for it to be
497 running inside @func{switch_threads} as the scheduler expects.  To
498 solve the problem, @func{thread_create} creates some fake stack frames
499 in the new thread's stack:
500
501 @itemize @bullet
502 @item
503 The topmost fake stack frame is for @func{switch_threads}, represented
504 by @struct{switch_threads_frame}.  The important part of this frame is
505 its @code{eip} member, the return address.  We point @code{eip} to
506 @func{switch_entry}, indicating it to be the function that called
507 @func{switch_entry}.
508
509 @item
510 The next fake stack frame is for @func{switch_entry}, an assembly
511 language routine in @file{threads/switch.S} that adjusts the stack
512 pointer,@footnote{This is because @func{switch_threads} takes
513 arguments on the stack and the 80@var{x}86 SVR4 calling convention
514 requires the caller, not the called function, to remove them when the
515 call is complete.  See @bibref{SysV-i386} chapter 3 for details.}
516 calls @func{schedule_tail} (this special case is why
517 @func{schedule_tail} is separate from @func{schedule}), and returns.
518 We fill in its stack frame so that it returns into
519 @func{kernel_thread}, a function in @file{threads/thread.c}.
520
521 @item
522 The final stack frame is for @func{kernel_thread}, which enables
523 interrupts and calls the thread's function (the function passed to
524 @func{thread_create}).  If the thread's function returns, it calls
525 @func{thread_exit} to terminate the thread.
526 @end itemize
527
528 @node Synchronization
529 @section Synchronization
530
531 If sharing of resources between threads is not handled in a careful,
532 controlled fashion, the result is usually a big mess.
533 This is especially the case in operating system kernels, where
534 faulty sharing can crash the entire machine.  Pintos provides several
535 synchronization primitives to help out.
536
537 @menu
538 * Disabling Interrupts::        
539 * Semaphores::                  
540 * Locks::                       
541 * Monitors::                    
542 * Optimization Barriers::             
543 @end menu
544
545 @node Disabling Interrupts
546 @subsection Disabling Interrupts
547
548 The crudest way to do synchronization is to disable interrupts, that
549 is, to temporarily prevent the CPU from responding to interrupts.  If
550 interrupts are off, no other thread will preempt the running thread,
551 because thread preemption is driven by the timer interrupt.  If
552 interrupts are on, as they normally are, then the running thread may
553 be preempted by another at any time, whether between two C statements
554 or even within the execution of one.
555
556 Incidentally, this means that Pintos is a ``preemptible kernel,'' that
557 is, kernel threads can be preempted at any time.  Traditional Unix
558 systems are ``nonpreemptible,'' that is, kernel threads can only be
559 preempted at points where they explicitly call into the scheduler.
560 (User programs can be preempted at any time in both models.)  As you
561 might imagine, preemptible kernels require more explicit
562 synchronization.
563
564 You should have little need to set the interrupt state directly.  Most
565 of the time you should use the other synchronization primitives
566 described in the following sections.  The main reason to disable
567 interrupts is to synchronize kernel threads with external interrupt
568 handlers, which cannot sleep and thus cannot use most other forms of
569 synchronization (@pxref{External Interrupt Handling}).
570
571 Some external interrupts cannot be postponed, even by disabling
572 interrupts.  These interrupts, called @dfn{non-maskable interrupts}
573 (NMIs), are supposed to be used only in emergencies, e.g.@: when the
574 computer is on fire.  Pintos does not handle non-maskable interrupts.
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 @subsection Semaphores
603
604 A @dfn{semaphore} is a nonnegative integer together with two operators
605 that manipulate it atomically, which are:
606
607 @itemize @bullet
608 @item
609 ``Down'' or ``P'': wait for the value to become positive, then
610 decrement it.
611
612 @item
613 ``Up'' or ``V'': increment the value (and wake up one waiting thread,
614 if any).
615 @end itemize
616
617 A semaphore initialized to 0 may be used to wait for an event
618 that will happen exactly once.  For example, suppose thread @var{A}
619 starts another thread @var{B} and wants to wait for @var{B} to signal
620 that some activity is complete.  @var{A} can create a semaphore
621 initialized to 0, pass it to @var{B} as it starts it, and then
622 ``down'' the semaphore.  When @var{B} finishes its activity, it
623 ``ups'' the semaphore.  This works regardless of whether @var{A}
624 ``downs'' the semaphore or @var{B} ``ups'' it first.
625
626 A semaphore initialized to 1 is typically used for controlling access
627 to a resource.  Before a block of code starts using the resource, it
628 ``downs'' the semaphore, then after it is done with the resource it
629 ``ups'' the resource.  In such a case a lock, described below, may be
630 more appropriate.
631
632 Semaphores can also be initialized to values larger than 1.  These are
633 rarely used.
634
635 Semaphores were invented by Edsger Dijkstra and first used in the THE
636 operating system (@bibref{Dijkstra}).
637
638 Pintos' semaphore type and operations are declared in
639 @file{threads/synch.h}.  
640
641 @deftp {Type} {struct semaphore}
642 Represents a semaphore.
643 @end deftp
644
645 @deftypefun void sema_init (struct semaphore *@var{sema}, unsigned @var{value})
646 Initializes @var{sema} as a new semaphore with the given initial
647 @var{value}.
648 @end deftypefun
649
650 @deftypefun void sema_down (struct semaphore *@var{sema})
651 Executes the ``down'' or ``P'' operation on @var{sema}, waiting for
652 its value to become positive and then decrementing it by one.
653 @end deftypefun
654
655 @deftypefun bool sema_try_down (struct semaphore *@var{sema})
656 Tries to execute the ``down'' or ``P'' operation on @var{sema},
657 without waiting.  Returns true if @var{sema}
658 was successfully decremented, or false if it was already
659 zero and thus could not be decremented without waiting.  Calling this
660 function in a
661 tight loop wastes CPU time, so use @func{sema_down} or find a
662 different approach instead.
663 @end deftypefun
664
665 @deftypefun void sema_up (struct semaphore *@var{sema})
666 Executes the ``up'' or ``V'' operation on @var{sema},
667 incrementing its value.  If any threads are waiting on
668 @var{sema}, wakes one of them up.
669
670 Unlike most synchronization primitives, @func{sema_up} may be called
671 inside an external interrupt handler (@pxref{External Interrupt
672 Handling}).
673 @end deftypefun
674
675 Semaphores are internally built out of disabling interrupt
676 (@pxref{Disabling Interrupts}) and thread blocking and unblocking
677 (@func{thread_block} and @func{thread_unblock}).  Each semaphore maintains
678 a list of waiting threads, using the linked list
679 implementation in @file{lib/kernel/list.c}.
680
681 @node Locks
682 @subsection Locks
683
684 A @dfn{lock} is like a semaphore with an initial value of 1
685 (@pxref{Semaphores}).  A lock's equivalent of ``up'' is called
686 ``release'', and the ``down'' operation is called ``acquire''.
687
688 Compared to a semaphore, a lock has one added restriction: only the
689 thread that acquires a lock, called the lock's ``owner'', is allowed to
690 release it.  If this restriction is a problem, it's a good sign that a
691 semaphore should be used, instead of a lock.
692
693 Locks in Pintos are not ``recursive,'' that is, it is an error for the
694 thread currently holding a lock to try to acquire that lock.
695
696 Lock types and functions are declared in @file{threads/synch.h}.
697
698 @deftp {Type} {struct lock}
699 Represents a lock.
700 @end deftp
701
702 @deftypefun void lock_init (struct lock *@var{lock})
703 Initializes @var{lock} as a new lock.
704 The lock is not initially owned by any thread.
705 @end deftypefun
706
707 @deftypefun void lock_acquire (struct lock *@var{lock})
708 Acquires @var{lock} for the current thread, first waiting for
709 any current owner to release it if necessary.
710 @end deftypefun
711
712 @deftypefun bool lock_try_acquire (struct lock *@var{lock})
713 Tries to acquire @var{lock} for use by the current thread, without
714 waiting.  Returns true if successful, false if the lock is already
715 owned.  Calling this function in a tight loop is a bad idea because it
716 wastes CPU time, so use @func{lock_acquire} instead.
717 @end deftypefun
718
719 @deftypefun void lock_release (struct lock *@var{lock})
720 Releases @var{lock}, which the current thread must own.
721 @end deftypefun
722
723 @deftypefun bool lock_held_by_current_thread (const struct lock *@var{lock})
724 Returns true if the running thread owns @var{lock},
725 false otherwise.
726 There is no function to test whether an arbitrary thread owns a lock,
727 because the answer could change before the caller could act on it.
728 @end deftypefun
729
730 @node Monitors
731 @subsection Monitors
732
733 A @dfn{monitor} is a higher-level form of synchronization than a
734 semaphore or a lock.  A monitor consists of data being synchronized,
735 plus a lock, called the @dfn{monitor lock}, and one or more
736 @dfn{condition variables}.  Before it accesses the protected data, a
737 thread first acquires the monitor lock.  It is then said to be ``in the
738 monitor''.  While in the monitor, the thread has control over all the
739 protected data, which it may freely examine or modify.  When access to
740 the protected data is complete, it releases the monitor lock.
741
742 Condition variables allow code in the monitor to wait for a condition to
743 become true.  Each condition variable is associated with an abstract
744 condition, e.g.@: ``some data has arrived for processing'' or ``over 10
745 seconds has passed since the user's last keystroke''.  When code in the
746 monitor needs to wait for a condition to become true, it ``waits'' on
747 the associated condition variable, which releases the lock and waits for
748 the condition to be signaled.  If, on the other hand, it has caused one
749 of these conditions to become true, it ``signals'' the condition to wake
750 up one waiter, or ``broadcasts'' the condition to wake all of them.
751
752 The theoretical framework for monitors was laid out by C.@: A.@: R.@:
753 Hoare (@bibref{Hoare}).  Their practical usage was later elaborated in a
754 paper on the Mesa operating system (@bibref{Lampson}).
755
756 Condition variable types and functions are declared in
757 @file{threads/synch.h}.
758
759 @deftp {Type} {struct condition}
760 Represents a condition variable.
761 @end deftp
762
763 @deftypefun void cond_init (struct condition *@var{cond})
764 Initializes @var{cond} as a new condition variable.
765 @end deftypefun
766
767 @deftypefun void cond_wait (struct condition *@var{cond}, struct lock *@var{lock})
768 Atomically releases @var{lock} (the monitor lock) and waits for
769 @var{cond} to be signaled by some other piece of code.  After
770 @var{cond} is signaled, reacquires @var{lock} before returning.
771 @var{lock} must be held before calling this function.
772
773 Sending a signal and waking up from a wait are not an atomic operation.
774 Thus, typically @func{cond_wait}'s caller must recheck the condition
775 after the wait completes and, if necessary, wait again.  See the next
776 section for an example.
777 @end deftypefun
778
779 @deftypefun void cond_signal (struct condition *@var{cond}, struct lock *@var{lock})
780 If any threads are waiting on @var{cond} (protected by monitor lock
781 @var{lock}), then this function wakes up one of them.  If no threads are
782 waiting, returns without performing any action.
783 @var{lock} must be held before calling this function.
784 @end deftypefun
785
786 @deftypefun void cond_broadcast (struct condition *@var{cond}, struct lock *@var{lock})
787 Wakes up all threads, if any, waiting on @var{cond} (protected by
788 monitor lock @var{lock}).  @var{lock} must be held before calling this
789 function.
790 @end deftypefun
791
792 @subsubsection Monitor Example
793
794 The classical example of a monitor is handling a buffer into which one
795 or more
796 ``producer'' threads write characters and out of which one or more
797 ``consumer'' threads read characters.  To implement this we need,
798 besides the monitor lock, two condition variables which we will call
799 @var{not_full} and @var{not_empty}:
800
801 @example
802 char buf[BUF_SIZE];     /* @r{Buffer.} */
803 size_t n = 0;           /* @r{0 <= n <= @var{BUF_SIZE}: # of characters in buffer.} */
804 size_t head = 0;        /* @r{@var{buf} index of next char to write (mod @var{BUF_SIZE}).} */
805 size_t tail = 0;        /* @r{@var{buf} index of next char to read (mod @var{BUF_SIZE}).} */
806 struct lock lock;       /* @r{Monitor lock.} */
807 struct condition not_empty; /* @r{Signaled when the buffer is not empty.} */
808 struct condition not_full; /* @r{Signaled when the buffer is not full.} */
809
810 @dots{}@r{initialize the locks and condition variables}@dots{}
811
812 void put (char ch) @{
813   lock_acquire (&lock);
814   while (n == BUF_SIZE)            /* @r{Can't add to @var{buf} as long as it's full.} */
815     cond_wait (&not_full, &lock);
816   buf[head++ % BUF_SIZE] = ch;     /* @r{Add @var{ch} to @var{buf}.} */
817   n++;
818   cond_signal (&not_empty, &lock); /* @r{@var{buf} can't be empty anymore.} */
819   lock_release (&lock);
820 @}
821
822 char get (void) @{
823   char ch;
824   lock_acquire (&lock);
825   while (n == 0)                  /* @r{Can't read @var{buf} as long as it's empty.} */
826     cond_wait (&not_empty, &lock);
827   ch = buf[tail++ % BUF_SIZE];    /* @r{Get @var{ch} from @var{buf}.} */
828   n--;
829   cond_signal (&not_full, &lock); /* @r{@var{buf} can't be full anymore.} */
830   lock_release (&lock);
831 @}
832 @end example
833
834 Note that @code{BUF_SIZE} must divide evenly into @code{SIZE_MAX + 1}
835 for the above code to be completely correct.  Otherwise, it will fail
836 the first time @code{head} wraps around to 0.  In practice,
837 @code{BUF_SIZE} would ordinarily be a power of 2.
838
839 @node Optimization Barriers
840 @subsection Optimization Barriers
841
842 @c We should try to come up with a better example.
843 @c Perhaps something with a linked list?
844
845 An @dfn{optimization barrier} is a special statement that prevents the
846 compiler from making assumptions about the state of memory across the
847 barrier.  The compiler will not reorder reads or writes of variables
848 across the barrier or assume that a variable's value is unmodified
849 across the barrier, except for local variables whose address is never
850 taken.  In Pintos, @file{threads/synch.h} defines the @code{barrier()}
851 macro as an optimization barrier.
852
853 One reason to use an optimization barrier is when data can change
854 asynchronously, without the compiler's knowledge, e.g.@: by another
855 thread or an interrupt handler.  The @func{too_many_loops} function in
856 @file{devices/timer.c} is an example.  This function starts out by
857 busy-waiting in a loop until a timer tick occurs:
858
859 @example
860 /* Wait for a timer tick. */
861 int64_t start = ticks;
862 while (ticks == start)
863   barrier ();
864 @end example
865
866 @noindent
867 Without an optimization barrier in the loop, the compiler could
868 conclude that the loop would never terminate, because @code{start} and
869 @code{ticks} start out equal and the loop itself never changes them.
870 It could then ``optimize'' the function into an infinite loop, which
871 would definitely be undesirable.
872
873 Optimization barriers can be used to avoid other compiler
874 optimizations.  The @func{busy_wait} function, also in
875 @file{devices/timer.c}, is an example.  It contains this loop:
876
877 @example
878 while (loops-- > 0)
879   barrier ();
880 @end example
881
882 @noindent
883 The goal of this loop is to busy-wait by counting @code{loops} down
884 from its original value to 0.  Without the barrier, the compiler could
885 delete the loop entirely, because it produces no useful output and has
886 no side effects.  The barrier forces the compiler to pretend that the
887 loop body has an important effect.
888
889 Finally, optimization barriers can be used to force the ordering of
890 memory reads or writes.  For example, suppose we add a ``feature''
891 that, whenever a timer interrupt occurs, the character in global
892 variable @code{timer_put_char} is printed on the console, but only if
893 global Boolean variable @code{timer_do_put} is true.  The best way to
894 set up @samp{x} to be printed is then to use an optimization barrier,
895 like this:
896
897 @example
898 timer_put_char = 'x';
899 barrier ();
900 timer_do_put = true;
901 @end example
902
903 Without the barrier, the code is buggy because the compiler is free to
904 reorder operations when it doesn't see a reason to keep them in the
905 same order.  In this case, the compiler doesn't know that the order of
906 assignments is important, so its optimizer is permitted to exchange
907 their order.  There's no telling whether it will actually do this, and
908 it is possible that passing the compiler different optimization flags
909 or using a different version of the compiler will produce different
910 behavior.
911
912 Another solution is to disable interrupts around the assignments.
913 This does not prevent reordering, but it prevents the interrupt
914 handler from intervening between the assignments.  It also has the
915 extra runtime cost of disabling and re-enabling interrupts:
916
917 @example
918 enum intr_level old_level = intr_disable ();
919 timer_put_char = 'x';
920 timer_do_put = true;
921 intr_set_level (old_level);
922 @end example
923
924 A second solution is to mark the declarations of
925 @code{timer_put_char} and @code{timer_do_put} as @samp{volatile}.  This
926 keyword tells the compiler that the variables are externally observable
927 and restricts its latitude for optimization.  However, the semantics of
928 @samp{volatile} are not well-defined, so it is not a good general
929 solution.  The base Pintos code does not use @samp{volatile} at all.
930
931 The following is @emph{not} a solution, because locks neither prevent
932 interrupts nor prevent the compiler from reordering the code within the
933 region where the lock is held:
934
935 @example
936 lock_acquire (&timer_lock);     /* INCORRECT CODE */
937 timer_put_char = 'x';
938 timer_do_put = true;
939 lock_release (&timer_lock);
940 @end example
941
942 The compiler treats invocation of any function defined externally,
943 that is, in another source file, as a limited form of optimization
944 barrier.  Specifically, the compiler assumes that any externally
945 defined function may access any statically or dynamically allocated
946 data and any local variable whose address is taken.  This often means
947 that explicit barriers can be omitted.  It is one reason that Pintos
948 contains few explicit barriers.
949
950 A function defined in the same source file, or in a header included by
951 the source file, cannot be relied upon as a optimization barrier.
952 This applies even to invocation of a function before its
953 definition, because the compiler may read and parse the entire source
954 file before performing optimization.
955
956 @node Interrupt Handling
957 @section Interrupt Handling
958
959 An @dfn{interrupt} notifies the CPU of some event.  Much of the work
960 of an operating system relates to interrupts in one way or another.
961 For our purposes, we classify interrupts into two broad categories:
962
963 @itemize @bullet
964 @item
965 @dfn{Internal interrupts}, that is, interrupts caused directly by CPU
966 instructions.  System calls, attempts at invalid memory access
967 (@dfn{page faults}), and attempts to divide by zero are some activities
968 that cause internal interrupts.  Because they are caused by CPU
969 instructions, internal interrupts are @dfn{synchronous} or synchronized
970 with CPU instructions.  @func{intr_disable} does not disable internal
971 interrupts.
972
973 @item
974 @dfn{External interrupts}, that is, interrupts originating outside the
975 CPU.  These interrupts come from hardware devices such as the system
976 timer, keyboard, serial ports, and disks.  External interrupts are
977 @dfn{asynchronous}, meaning that their delivery is not
978 synchronized with instruction execution.  Handling of external interrupts
979 can be postponed with @func{intr_disable} and related functions
980 (@pxref{Disabling Interrupts}).
981 @end itemize
982
983 The CPU treats both classes of interrupts largely the same way,
984 so Pintos has common infrastructure to handle both classes.
985 The following section describes this
986 common infrastructure.  The sections after that give the specifics of
987 external and internal interrupts.
988
989 If you haven't already read chapter 3, ``Basic Execution Environment,''
990 in @bibref{IA32-v1}, it is recommended that you do so now.  You might
991 also want to skim chapter 5, ``Interrupt and Exception Handling,'' in
992 @bibref{IA32-v3a}.
993
994 @menu
995 * Interrupt Infrastructure::    
996 * Internal Interrupt Handling::  
997 * External Interrupt Handling::  
998 @end menu
999
1000 @node Interrupt Infrastructure
1001 @subsection Interrupt Infrastructure
1002
1003 When an interrupt occurs, the CPU saves
1004 its most essential state on a stack and jumps to an interrupt
1005 handler routine.  The 80@var{x}86 architecture supports 256
1006 interrupts, numbered 0 through 255, each with an independent
1007 handler defined in an array called the @dfn{interrupt
1008 descriptor table} or IDT.
1009
1010 In Pintos, @func{intr_init} in @file{threads/interrupt.c} sets up the
1011 IDT so that each entry points to a unique entry point in
1012 @file{threads/intr-stubs.S} named @func{intr@var{NN}_stub}, where
1013 @var{NN} is the interrupt number in
1014 hexadecimal.  Because the CPU doesn't give
1015 us any other way to find out the interrupt number, this entry point
1016 pushes the interrupt number on the stack.  Then it jumps to
1017 @func{intr_entry}, which pushes all the registers that the processor
1018 didn't already push for us, and then calls @func{intr_handler}, which
1019 brings us back into C in @file{threads/interrupt.c}.
1020
1021 The main job of @func{intr_handler} is to call the function
1022 registered for handling the particular interrupt.  (If no
1023 function is registered, it dumps some information to the console and
1024 panics.)  It also does some extra processing for external
1025 interrupts (@pxref{External Interrupt Handling}).
1026
1027 When @func{intr_handler} returns, the assembly code in
1028 @file{threads/intr-stubs.S} restores all the CPU registers saved
1029 earlier and directs the CPU to return from the interrupt.
1030
1031 The following types and functions are common to all
1032 interrupts.
1033
1034 @deftp {Type} {void intr_handler_func (struct intr_frame *@var{frame})}
1035 This is how an interrupt handler function must be declared.  Its @var{frame}
1036 argument (see below) allows it to determine the cause of the interrupt
1037 and the state of the thread that was interrupted.
1038 @end deftp
1039
1040 @deftp {Type} {struct intr_frame}
1041 The stack frame of an interrupt handler, as saved by the CPU, the interrupt
1042 stubs, and @func{intr_entry}.  Its most interesting members are described
1043 below.
1044 @end deftp
1045
1046 @deftypecv {Member} {@struct{intr_frame}} uint32_t edi
1047 @deftypecvx {Member} {@struct{intr_frame}} uint32_t esi
1048 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ebp
1049 @deftypecvx {Member} {@struct{intr_frame}} uint32_t esp_dummy
1050 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ebx
1051 @deftypecvx {Member} {@struct{intr_frame}} uint32_t edx
1052 @deftypecvx {Member} {@struct{intr_frame}} uint32_t ecx
1053 @deftypecvx {Member} {@struct{intr_frame}} uint32_t eax
1054 @deftypecvx {Member} {@struct{intr_frame}} uint16_t es
1055 @deftypecvx {Member} {@struct{intr_frame}} uint16_t ds
1056 Register values in the interrupted thread, pushed by @func{intr_entry}.
1057 The @code{esp_dummy} value isn't actually used (refer to the
1058 description of @code{PUSHA} in @bibref{IA32-v2b} for details).
1059 @end deftypecv
1060
1061 @deftypecv {Member} {@struct{intr_frame}} uint32_t vec_no
1062 The interrupt vector number, ranging from 0 to 255.
1063 @end deftypecv
1064
1065 @deftypecv {Member} {@struct{intr_frame}} uint32_t error_code
1066 The ``error code'' pushed on the stack by the CPU for some internal
1067 interrupts.
1068 @end deftypecv
1069
1070 @deftypecv {Member} {@struct{intr_frame}} void (*eip) (void)
1071 The address of the next instruction to be executed by the interrupted
1072 thread.
1073 @end deftypecv
1074
1075 @deftypecv {Member} {@struct{intr_frame}} {void *} esp
1076 The interrupted thread's stack pointer.
1077 @end deftypecv
1078
1079 @deftypefun {const char *} intr_name (uint8_t @var{vec})
1080 Returns the name of the interrupt numbered @var{vec}, or
1081 @code{"unknown"} if the interrupt has no registered name.
1082 @end deftypefun
1083
1084 @node Internal Interrupt Handling
1085 @subsection Internal Interrupt Handling
1086
1087 Internal interrupts are caused directly by CPU instructions executed by
1088 the running kernel thread or user process (from project 2 onward).  An
1089 internal interrupt is therefore said to arise in a ``process context.''
1090
1091 In an internal interrupt's handler, it can make sense to examine the
1092 @struct{intr_frame} passed to the interrupt handler, or even to modify
1093 it.  When the interrupt returns, modifications in @struct{intr_frame}
1094 become changes to the calling thread or process's state.  For example,
1095 the Pintos system call handler returns a value to the user program by
1096 modifying the saved EAX register (@pxref{System Call Details}).
1097
1098 There are no special restrictions on what an internal interrupt
1099 handler can or can't do.  Generally they should run with interrupts
1100 enabled, just like other code, and so they can be preempted by other
1101 kernel threads.  Thus, they do need to synchronize with other threads
1102 on shared data and other resources (@pxref{Synchronization}).
1103
1104 Internal interrupt handlers can be invoked recursively.  For example,
1105 the system call handler might cause a page fault while attempting to
1106 read user memory.  Deep recursion would risk overflowing the limited
1107 kernel stack (@pxref{struct thread}), but should be unnecessary.
1108
1109 @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})
1110 Registers @var{handler} to be called when internal interrupt numbered
1111 @var{vec} is triggered.  Names the interrupt @var{name} for debugging
1112 purposes.
1113
1114 If @var{level} is @code{INTR_ON}, external interrupts will be processed
1115 normally during the interrupt handler's execution, which is normally
1116 desirable.  Specifying @code{INTR_OFF} will cause the CPU to disable
1117 external interrupts when it invokes the interrupt handler.  The effect
1118 is slightly different from calling @func{intr_disable} inside the
1119 handler, because that leaves a window of one or more CPU instructions in
1120 which external interrupts are still enabled.  This is important for the
1121 page fault handler; refer to the comments in @file{userprog/exception.c}
1122 for details.
1123
1124 @var{dpl} determines how the interrupt can be invoked.  If @var{dpl} is
1125 0, then the interrupt can be invoked only by kernel threads.  Otherwise
1126 @var{dpl} should be 3, which allows user processes to invoke the
1127 interrupt with an explicit INT instruction.  The value of @var{dpl}
1128 doesn't affect user processes' ability to invoke the interrupt
1129 indirectly, e.g.@: an invalid memory reference will cause a page fault
1130 regardless of @var{dpl}.
1131 @end deftypefun
1132
1133 @node External Interrupt Handling
1134 @subsection External Interrupt Handling
1135
1136 External interrupts are caused by events outside the CPU.
1137 They are asynchronous, so they can be invoked at any time that
1138 interrupts have not been disabled.  We say that an external interrupt
1139 runs in an ``interrupt context.''
1140
1141 In an external interrupt, the @struct{intr_frame} passed to the
1142 handler is not very meaningful.  It describes the state of the thread
1143 or process that was interrupted, but there is no way to predict which
1144 one that is.  It is possible, although rarely useful, to examine it, but
1145 modifying it is a recipe for disaster.
1146
1147 Only one external interrupt may be processed at a time.  Neither
1148 internal nor external interrupt may nest within an external interrupt
1149 handler.  Thus, an external interrupt's handler must run with interrupts
1150 disabled (@pxref{Disabling Interrupts}).
1151
1152 An external interrupt handler must not sleep or yield, which rules out
1153 calling @func{lock_acquire}, @func{thread_yield}, and many other
1154 functions.  Sleeping in interrupt context would effectively put the
1155 interrupted thread to sleep, too, until the interrupt handler was again
1156 scheduled and returned.  This would be unfair to the unlucky thread, and
1157 it would deadlock if the handler were waiting for the sleeping thread
1158 to, e.g., release a lock.
1159
1160 An external interrupt handler
1161 effectively monopolizes the machine and delays all other activities.
1162 Therefore, external interrupt handlers should complete as quickly as
1163 they can.  Anything that require much CPU time should instead run in a
1164 kernel thread, possibly one that the interrupt triggers using a
1165 synchronization primitive.
1166
1167 External interrupts are controlled by a
1168 pair of devices outside the CPU called @dfn{programmable interrupt
1169 controllers}, @dfn{PICs} for short.  When @func{intr_init} sets up the
1170 CPU's IDT, it also initializes the PICs for interrupt handling.  The
1171 PICs also must be ``acknowledged'' at the end of processing for each
1172 external interrupt.  @func{intr_handler} takes care of that by calling
1173 @func{pic_end_of_interrupt}, which properly signals the PICs.
1174
1175 The following functions relate to external
1176 interrupts.
1177
1178 @deftypefun void intr_register_ext (uint8_t @var{vec}, intr_handler_func *@var{handler}, const char *@var{name})
1179 Registers @var{handler} to be called when external interrupt numbered
1180 @var{vec} is triggered.  Names the interrupt @var{name} for debugging
1181 purposes.  The handler will run with interrupts disabled.
1182 @end deftypefun
1183
1184 @deftypefun bool intr_context (void)
1185 Returns true if we are running in an interrupt context, otherwise
1186 false.  Mainly used in functions that might sleep
1187 or that otherwise should not be called from interrupt context, in this
1188 form:
1189 @example
1190 ASSERT (!intr_context ());
1191 @end example
1192 @end deftypefun
1193
1194 @deftypefun void intr_yield_on_return (void)
1195 When called in an interrupt context, causes @func{thread_yield} to be
1196 called just before the interrupt returns.  Used
1197 in the timer interrupt handler when a thread's time slice expires, to
1198 cause a new thread to be scheduled.
1199 @end deftypefun
1200
1201 @node Memory Allocation
1202 @section Memory Allocation
1203
1204 Pintos contains two memory allocators, one that allocates memory in
1205 units of a page, and one that can allocate blocks of any size.
1206
1207 @menu
1208 * Page Allocator::              
1209 * Block Allocator::             
1210 @end menu
1211
1212 @node Page Allocator
1213 @subsection Page Allocator
1214
1215 The page allocator declared in @file{threads/palloc.h} allocates
1216 memory in units of a page.  It is most often used to allocate memory
1217 one page at a time, but it can also allocate multiple contiguous pages
1218 at once.
1219
1220 The page allocator divides the memory it allocates into two pools,
1221 called the kernel and user pools.  By default, each pool gets half of
1222 system memory, but this can be changed with the @option{-ul} kernel
1223 command line
1224 option (@pxref{Why PAL_USER?}).  An allocation request draws from one
1225 pool or the other.  If one pool becomes empty, the other may still
1226 have free pages.  The user pool should be used for allocating memory
1227 for user processes and the kernel pool for all other allocations.
1228 This will only become important starting with project 3.  Until then,
1229 all allocations should be made from the kernel pool.
1230
1231 Each pool's usage is tracked with a bitmap, one bit per page in
1232 the pool.  A request to allocate @var{n} pages scans the bitmap
1233 for @var{n} consecutive bits set to
1234 false, indicating that those pages are free, and then sets those bits
1235 to true to mark them as used.  This is a ``first fit'' allocation
1236 strategy (@pxref{Wilson}).
1237
1238 The page allocator is subject to fragmentation.  That is, it may not
1239 be possible to allocate @var{n} contiguous pages even though @var{n}
1240 or more pages are free, because the free pages are separated by used
1241 pages.  In fact, in pathological cases it may be impossible to
1242 allocate 2 contiguous pages even though half of the pool's pages are free.
1243 Single-page requests can't fail due to fragmentation, so
1244 requests for multiple contiguous pages should be limited as much as
1245 possible.
1246
1247 Pages may not be allocated from interrupt context, but they may be
1248 freed.
1249
1250 When a page is freed, all of its bytes are cleared to @t{0xcc}, as
1251 a debugging aid (@pxref{Debugging Tips}).
1252
1253 Page allocator types and functions are described below.
1254
1255 @deftypefun {void *} palloc_get_page (enum palloc_flags @var{flags})
1256 @deftypefunx {void *} palloc_get_multiple (enum palloc_flags @var{flags}, size_t @var{page_cnt})
1257 Obtains and returns one page, or @var{page_cnt} contiguous pages,
1258 respectively.  Returns a null pointer if the pages cannot be allocated.
1259
1260 The @var{flags} argument may be any combination of the following flags:
1261
1262 @defvr {Page Allocator Flag} @code{PAL_ASSERT}
1263 If the pages cannot be allocated, panic the kernel.  This is only
1264 appropriate during kernel initialization.  User processes
1265 should never be permitted to panic the kernel.
1266 @end defvr
1267
1268 @defvr {Page Allocator Flag} @code{PAL_ZERO}
1269 Zero all the bytes in the allocated pages before returning them.  If not
1270 set, the contents of newly allocated pages are unpredictable.
1271 @end defvr
1272
1273 @defvr {Page Allocator Flag} @code{PAL_USER}
1274 Obtain the pages from the user pool.  If not set, pages are allocated
1275 from the kernel pool.
1276 @end defvr
1277 @end deftypefun
1278
1279 @deftypefun void palloc_free_page (void *@var{page})
1280 @deftypefunx void palloc_free_multiple (void *@var{pages}, size_t @var{page_cnt})
1281 Frees one page, or @var{page_cnt} contiguous pages, respectively,
1282 starting at @var{pages}.  All of the pages must have been obtained using
1283 @func{palloc_get_page} or @func{palloc_get_multiple}.
1284 @end deftypefun
1285
1286 @node Block Allocator
1287 @subsection Block Allocator
1288
1289 The block allocator, declared in @file{threads/malloc.h}, can allocate
1290 blocks of any size.  It is layered on top of the page allocator
1291 described in the previous section.  Blocks returned by the block
1292 allocator are obtained from the kernel pool.
1293
1294 The block allocator uses two different strategies for allocating memory.
1295 The first strategy applies to blocks that are 1 kB or smaller
1296 (one-fourth of the page size).  These allocations are rounded up to the
1297 nearest power of 2, or 16 bytes, whichever is larger.  Then they are
1298 grouped into a page used only for allocations of that size.
1299
1300 The second strategy applies to blocks larger than 1 kB.
1301 These allocations (plus a small amount of overhead) are rounded up to
1302 the nearest page in size, and then the block allocator requests that
1303 number of contiguous pages from the page allocator.
1304
1305 In either case, the difference between the allocation requested size
1306 and the actual block size is wasted.  A real operating system would
1307 carefully tune its allocator to minimize this waste, but this is
1308 unimportant in an instructional system like Pintos.
1309
1310 As long as a page can be obtained from the page allocator, small
1311 allocations always succeed.  Most small allocations do not require a
1312 new page from the page allocator at all, because they are satisfied
1313 using part of a page already allocated.  However, large allocations
1314 always require calling into the page allocator, and any allocation
1315 that needs more than one contiguous page can fail due to fragmentation,
1316 as already discussed in the previous section.  Thus, you should
1317 minimize the number of large allocations in your code, especially
1318 those over approximately 4 kB each.
1319
1320 When a block is freed, all of its bytes are cleared to @t{0xcc}, as
1321 a debugging aid (@pxref{Debugging Tips}).
1322
1323 The block allocator may not be called from interrupt context.
1324
1325 The block allocator functions are described below.  Their interfaces are
1326 the same as the standard C library functions of the same names.
1327
1328 @deftypefun {void *} malloc (size_t @var{size})
1329 Obtains and returns a new block, from the kernel pool, at least
1330 @var{size} bytes long.  Returns a null pointer if @var{size} is zero or
1331 if memory is not available.
1332 @end deftypefun
1333
1334 @deftypefun {void *} calloc (size_t @var{a}, size_t @var{b})
1335 Obtains a returns a new block, from the kernel pool, at least
1336 @code{@var{a} * @var{b}} bytes long.  The block's contents will be
1337 cleared to zeros.  Returns a null pointer if @var{a} or @var{b} is zero
1338 or if insufficient memory is available.
1339 @end deftypefun
1340
1341 @deftypefun {void *} realloc (void *@var{block}, size_t @var{new_size})
1342 Attempts to resize @var{block} to @var{new_size} bytes, possibly moving
1343 it in the process.  If successful, returns the new block, in which case
1344 the old block must no longer be accessed.  On failure, returns a null
1345 pointer, and the old block remains valid.
1346
1347 A call with @var{block} null is equivalent to @func{malloc}.  A call
1348 with @var{new_size} zero is equivalent to @func{free}.
1349 @end deftypefun
1350
1351 @deftypefun void free (void *@var{block})
1352 Frees @var{block}, which must have been previously returned by
1353 @func{malloc}, @func{calloc}, or @func{realloc} (and not yet freed).
1354 @end deftypefun
1355
1356 @node Virtual Addresses
1357 @section Virtual Addresses
1358
1359 A 32-bit virtual address can be divided into a 20-bit @dfn{page number}
1360 and a 12-bit @dfn{page offset} (or just @dfn{offset}), like this:
1361
1362 @example
1363 @group
1364                31               12 11        0
1365               +-------------------+-----------+
1366               |    Page Number    |   Offset  |
1367               +-------------------+-----------+
1368                        Virtual Address
1369 @end group
1370 @end example
1371
1372 Header @file{threads/vaddr.h} defines these functions and macros for
1373 working with virtual addresses:
1374
1375 @defmac PGSHIFT
1376 @defmacx PGBITS
1377 The bit index (0) and number of bits (12) of the offset part of a
1378 virtual address, respectively.
1379 @end defmac
1380
1381 @defmac PGMASK
1382 A bit mask with the bits in the page offset set to 1, the rest set to 0
1383 (@t{0xfff}).
1384 @end defmac
1385
1386 @defmac PGSIZE
1387 The page size in bytes (4,096).
1388 @end defmac
1389
1390 @deftypefun unsigned pg_ofs (const void *@var{va})
1391 Extracts and returns the page offset in virtual address @var{va}.
1392 @end deftypefun
1393
1394 @deftypefun uintptr_t pg_no (const void *@var{va})
1395 Extracts and returns the page number in virtual address @var{va}.
1396 @end deftypefun
1397
1398 @deftypefun {void *} pg_round_down (const void *@var{va})
1399 Returns the start of the virtual page that @var{va} points within, that
1400 is, @var{va} with the page offset set to 0.
1401 @end deftypefun
1402
1403 @deftypefun {void *} pg_round_up (const void *@var{va})
1404 Returns @var{va} rounded up to the nearest page boundary.
1405 @end deftypefun
1406
1407 Virtual memory in Pintos is divided into two regions: user virtual
1408 memory and kernel virtual memory (@pxref{Virtual Memory Layout}).  The
1409 boundary between them is @code{PHYS_BASE}:
1410
1411 @defmac PHYS_BASE
1412 Base address of kernel virtual memory.  It defaults to @t{0xc0000000} (3
1413 GB), but it may be changed to any multiple of @t{0x10000000} from
1414 @t{0x80000000} to @t{0xf0000000}.
1415
1416 User virtual memory ranges from virtual address 0 up to
1417 @code{PHYS_BASE}.  Kernel virtual memory occupies the rest of the
1418 virtual address space, from @code{PHYS_BASE} up to 4 GB.
1419 @end defmac
1420
1421 @deftypefun {bool} is_user_vaddr (const void *@var{va})
1422 @deftypefunx {bool} is_kernel_vaddr (const void *@var{va})
1423 Returns true if @var{va} is a user or kernel virtual address,
1424 respectively, false otherwise.
1425 @end deftypefun
1426
1427 The 80@var{x}86 doesn't provide any way to directly access memory given
1428 a physical address.  This ability is often necessary in an operating
1429 system kernel, so Pintos works around it by mapping kernel virtual
1430 memory one-to-one to physical memory.  That is, virtual address
1431 @code{PHYS_BASE} accesses physical address 0, virtual address
1432 @code{PHYS_BASE} + @t{0x1234} accesses physical address @t{0x1234}, and
1433 so on up to the size of the machine's physical memory.  Thus, adding
1434 @code{PHYS_BASE} to a physical address obtains a kernel virtual address
1435 that accesses that address; conversely, subtracting @code{PHYS_BASE}
1436 from a kernel virtual address obtains the corresponding physical
1437 address.  Header @file{threads/vaddr.h} provides a pair of functions to
1438 do these translations:
1439
1440 @deftypefun {void *} ptov (uintptr_t @var{pa})
1441 Returns the kernel virtual address corresponding to physical address
1442 @var{pa}, which should be between 0 and the number of bytes of physical
1443 memory.
1444 @end deftypefun
1445
1446 @deftypefun {uintptr_t} vtop (void *@var{va})
1447 Returns the physical address corresponding to @var{va}, which must be a
1448 kernel virtual address.
1449 @end deftypefun
1450
1451 @node Page Table
1452 @section Page Table
1453
1454 The code in @file{pagedir.c} is an abstract interface to the 80@var{x}86
1455 hardware page table, also called a ``page directory'' by Intel processor
1456 documentation.  The page table interface uses a @code{uint32_t *} to
1457 represent a page table because this is convenient for accessing their
1458 internal structure.
1459
1460 The sections below describe the page table interface and internals.
1461
1462 @menu
1463 * Page Table Creation Destruction Activation::  
1464 * Page Tables Inspection and Updates::  
1465 * Page Table Accessed and Dirty Bits::  
1466 * Page Table Details::          
1467 @end menu
1468
1469 @node Page Table Creation Destruction Activation
1470 @subsection Creation, Destruction, and Activation
1471
1472 These functions create, destroy, and activate page tables.  The base
1473 Pintos code already calls these functions where necessary, so it should
1474 not be necessary to call them yourself.
1475
1476 @deftypefun {uint32_t *} pagedir_create (void)
1477 Creates and returns a new page table.  The new page table contains
1478 Pintos's normal kernel virtual page mappings, but no user virtual
1479 mappings.
1480
1481 Returns a null pointer if memory cannot be obtained.
1482 @end deftypefun
1483
1484 @deftypefun void pagedir_destroy (uint32_t *@var{pd})
1485 Frees all of the resources held by @var{pd}, including the page table
1486 itself and the frames that it maps.
1487 @end deftypefun
1488
1489 @deftypefun void pagedir_activate (uint32_t *@var{pd})
1490 Activates @var{pd}.  The active page table is the one used by the CPU to
1491 translate memory references.
1492 @end deftypefun
1493
1494 @node Page Tables Inspection and Updates
1495 @subsection Inspection and Updates
1496
1497 These functions examine or update the mappings from pages to frames
1498 encapsulated by a page table.  They work on both active and inactive
1499 page tables (that is, those for running and suspended processes),
1500 flushing the TLB as necessary.
1501
1502 @deftypefun bool pagedir_set_page (uint32_t *@var{pd}, void *@var{upage}, void *@var{kpage}, bool @var{writable})
1503 Adds to @var{pd} a mapping from user page @var{upage} to the frame identified
1504 by kernel virtual address @var{kpage}.  If @var{writable} is true, the
1505 page is mapped read/write; otherwise, it is mapped read-only.
1506
1507 User page @var{upage} must not already be mapped in @var{pd}.
1508
1509 Kernel page @var{kpage} should be a kernel virtual address obtained from
1510 the user pool with @code{palloc_get_page(PAL_USER)} (@pxref{Why
1511 PAL_USER?}).
1512
1513 Returns true if successful, false on failure.  Failure will occur if
1514 additional memory required for the page table cannot be obtained.
1515 @end deftypefun
1516
1517 @deftypefun {void *} pagedir_get_page (uint32_t *@var{pd}, const void *@var{uaddr})
1518 Looks up the frame mapped to @var{uaddr} in @var{pd}.  Returns the
1519 kernel virtual address for that frame, if @var{uaddr} is mapped, or a
1520 null pointer if it is not.
1521 @end deftypefun
1522
1523 @deftypefun void pagedir_clear_page (uint32_t *@var{pd}, void *@var{page})
1524 Marks @var{page} ``not present'' in @var{pd}.  Later accesses to
1525 the page will fault.
1526
1527 Other bits in the page table for @var{page} are preserved, permitting
1528 the accessed and dirty bits (see the next section) to be checked.
1529
1530 This function has no effect if @var{page} is not mapped.
1531 @end deftypefun
1532
1533 @node Page Table Accessed and Dirty Bits
1534 @subsection Accessed and Dirty Bits
1535
1536 80@var{x}86 hardware provides some assistance for implementing page
1537 replacement algorithms, through a pair of bits in the page table entry
1538 (PTE) for each page.  On any read or write to a page, the CPU sets the
1539 @dfn{accessed bit} to 1 in the page's PTE, and on any write, the CPU
1540 sets the @dfn{dirty bit} to 1.  The CPU never resets these bits to 0,
1541 but the OS may do so.
1542
1543 Proper interpretation of these bits requires understanding of
1544 @dfn{aliases}, that is, two (or more) pages that refer to the same
1545 frame.  When an aliased frame is accessed, the accessed and dirty bits
1546 are updated in only one page table entry (the one for the page used for
1547 access).  The accessed and dirty bits for the other aliases are not
1548 updated.
1549
1550 @xref{Accessed and Dirty Bits}, on applying these bits in implementing
1551 page replacement algorithms.
1552
1553 @deftypefun bool pagedir_is_dirty (uint32_t *@var{pd}, const void *@var{page})
1554 @deftypefunx bool pagedir_is_accessed (uint32_t *@var{pd}, const void *@var{page})
1555 Returns true if page directory @var{pd} contains a page table entry for
1556 @var{page} that is marked dirty (or accessed).  Otherwise,
1557 returns false.
1558 @end deftypefun
1559
1560 @deftypefun void pagedir_set_dirty (uint32_t *@var{pd}, const void *@var{page}, bool @var{value})
1561 @deftypefunx void pagedir_set_accessed (uint32_t *@var{pd}, const void *@var{page}, bool @var{value})
1562 If page directory @var{pd} has a page table entry for @var{page}, then
1563 its dirty (or accessed) bit is set to @var{value}.
1564 @end deftypefun
1565
1566 @node Page Table Details
1567 @subsection Page Table Details
1568
1569 The functions provided with Pintos are sufficient to implement the
1570 projects.  However, you may still find it worthwhile to understand the
1571 hardware page table format, so we'll go into a little detail in this
1572 section.
1573
1574 @menu
1575 * Page Table Structure::        
1576 * Page Table Entry Format::     
1577 * Page Directory Entry Format::  
1578 @end menu
1579
1580 @node Page Table Structure
1581 @subsubsection Structure
1582
1583 The top-level paging data structure is a page called the ``page
1584 directory'' (PD) arranged as an array of 1,024 32-bit page directory
1585 entries (PDEs), each of which represents 4 MB of virtual memory.  Each
1586 PDE may point to the physical address of another page called a
1587 ``page table'' (PT) arranged, similarly, as an array of 1,024
1588 32-bit page table entries (PTEs), each of which translates a single 4
1589 kB virtual page to a physical page.
1590
1591 Translation of a virtual address into a physical address follows
1592 the three-step process illustrated in the diagram
1593 below:@footnote{Actually, virtual to physical translation on the
1594 80@var{x}86 architecture occurs via an intermediate ``linear
1595 address,'' but Pintos (and most modern 80@var{x}86 OSes) set up the CPU
1596 so that linear and virtual addresses are one and the same.  Thus, you
1597 can effectively ignore this CPU feature.}
1598
1599 @enumerate 1
1600 @item
1601 The most-significant 10 bits of the virtual address (bits 22@dots{}31)
1602 index the page directory.  If the PDE is marked ``present,'' the
1603 physical address of a page table is read from the PDE thus obtained.
1604 If the PDE is marked ``not present'' then a page fault occurs.
1605
1606 @item
1607 The next 10 bits of the virtual address (bits 12@dots{}21) index
1608 the page table.  If the PTE is marked ``present,'' the physical
1609 address of a data page is read from the PTE thus obtained.  If the PTE
1610 is marked ``not present'' then a page fault occurs.
1611
1612 @item
1613 The least-significant 12 bits of the virtual address (bits 0@dots{}11)
1614 are added to the data page's physical base address, yielding the final
1615 physical address.
1616 @end enumerate
1617
1618 @example
1619 @group
1620  31                  22 21                  12 11                   0
1621 +----------------------+----------------------+----------------------+
1622 | Page Directory Index |   Page Table Index   |    Page Offset       |
1623 +----------------------+----------------------+----------------------+
1624              |                    |                     |
1625      _______/             _______/                _____/
1626     /                    /                       /
1627    /    Page Directory  /      Page Table       /    Data Page
1628   /     .____________. /     .____________.    /   .____________.
1629   |1,023|____________| |1,023|____________|    |   |____________|
1630   |1,022|____________| |1,022|____________|    |   |____________|
1631   |1,021|____________| |1,021|____________|    \__\|____________|
1632   |1,020|____________| |1,020|____________|       /|____________|
1633   |     |            | |     |            |        |            |
1634   |     |            | \____\|            |_       |            |
1635   |     |      .     |      /|      .     | \      |      .     |
1636   \____\|      .     |_      |      .     |  |     |      .     |
1637        /|      .     | \     |      .     |  |     |      .     |
1638         |      .     |  |    |      .     |  |     |      .     |
1639         |            |  |    |            |  |     |            |
1640         |____________|  |    |____________|  |     |____________|
1641        4|____________|  |   4|____________|  |     |____________|
1642        3|____________|  |   3|____________|  |     |____________|
1643        2|____________|  |   2|____________|  |     |____________|
1644        1|____________|  |   1|____________|  |     |____________|
1645        0|____________|  \__\0|____________|  \____\|____________|
1646                            /                      /
1647 @end group
1648 @end example
1649
1650 Pintos provides some macros and functions that are useful for working
1651 with raw page tables:
1652
1653 @defmac PTSHIFT
1654 @defmacx PTBITS
1655 The starting bit index (12) and number of bits (10), respectively, in a
1656 page table index.
1657 @end defmac
1658
1659 @defmac PTMASK
1660 A bit mask with the bits in the page table index set to 1 and the rest
1661 set to 0 (@t{0x3ff000}).
1662 @end defmac
1663
1664 @defmac PTSPAN
1665 The number of bytes of virtual address space that a single page table
1666 page covers (4,194,304 bytes, or 4 MB).
1667 @end defmac
1668
1669 @defmac PDSHIFT
1670 @defmacx PDBITS
1671 The starting bit index (22) and number of bits (10), respectively, in a
1672 page directory index.
1673 @end defmac
1674
1675 @defmac PDMASK
1676 A bit mask with the bits in the page directory index set to 1 and other
1677 bits set to 0 (@t{0xffc00000}).
1678 @end defmac
1679
1680 @deftypefun uintptr_t pd_no (const void *@var{va})
1681 @deftypefunx uintptr_t pt_no (const void *@var{va})
1682 Returns the page directory index or page table index, respectively, for
1683 virtual address @var{va}.  These functions are defined in
1684 @file{threads/pte.h}.
1685 @end deftypefun
1686
1687 @deftypefun unsigned pg_ofs (const void *@var{va})
1688 Returns the page offset for virtual address @var{va}.  This function is
1689 defined in @file{threads/vaddr.h}.
1690 @end deftypefun
1691
1692 @node Page Table Entry Format
1693 @subsubsection Page Table Entry Format
1694
1695 You do not need to understand the PTE format to do the Pintos
1696 projects, unless you wish to incorporate the page table into your
1697 supplemental page table (@pxref{Managing the Supplemental Page Table}).
1698
1699 The actual format of a page table entry is summarized below.  For
1700 complete information, refer to section 3.7, ``Page Translation Using
1701 32-Bit Physical Addressing,'' in @bibref{IA32-v3a}.
1702
1703 @example
1704 @group
1705  31                                   12 11 9      6 5     2 1 0
1706 +---------------------------------------+----+----+-+-+---+-+-+-+
1707 |           Physical Address            | AVL|    |D|A|   |U|W|P|
1708 +---------------------------------------+----+----+-+-+---+-+-+-+
1709 @end group
1710 @end example
1711
1712 Some more information on each bit is given below.  The names are
1713 @file{threads/pte.h} macros that represent the bits' values:
1714
1715 @defmac PTE_P
1716 Bit 0, the ``present'' bit.  When this bit is 1, the
1717 other bits are interpreted as described below.  When this bit is 0, any
1718 attempt to access the page will page fault.  The remaining bits are then
1719 not used by the CPU and may be used by the OS for any purpose.
1720 @end defmac
1721
1722 @defmac PTE_W
1723 Bit 1, the ``read/write'' bit.  When it is 1, the page
1724 is writable.  When it is 0, write attempts will page fault.
1725 @end defmac
1726
1727 @defmac PTE_U
1728 Bit 2, the ``user/supervisor'' bit.  When it is 1, user
1729 processes may access the page.  When it is 0, only the kernel may access
1730 the page (user accesses will page fault).
1731
1732 Pintos clears this bit in PTEs for kernel virtual memory, to prevent
1733 user processes from accessing them.
1734 @end defmac
1735  
1736 @defmac PTE_A
1737 Bit 5, the ``accessed'' bit.  @xref{Page Table Accessed
1738 and Dirty Bits}.
1739 @end defmac
1740
1741 @defmac PTE_D
1742 Bit 6, the ``dirty'' bit.  @xref{Page Table Accessed and
1743 Dirty Bits}.
1744 @end defmac
1745
1746 @defmac PTE_AVL
1747 Bits 9@dots{}11, available for operating system use.
1748 Pintos, as provided, does not use them and sets them to 0.
1749 @end defmac
1750
1751 @defmac PTE_ADDR
1752 Bits 12@dots{}31, the top 20 bits of the physical address of a frame.
1753 The low 12 bits of the frame's address are always 0.
1754 @end defmac
1755
1756 Other bits are either reserved or uninteresting in a Pintos context and
1757 should be set to@tie{}0.
1758
1759 Header @file{threads/pte.h} defines three functions for working with
1760 page table entries:
1761
1762 @deftypefun uint32_t pte_create_kernel (uint32_t *@var{page}, bool @var{writable})
1763 Returns a page table entry that points to @var{page}, which should be a
1764 kernel virtual address.  The PTE's present bit will be set.  It will be
1765 marked for kernel-only access.  If @var{writable} is true, the PTE will
1766 also be marked read/write; otherwise, it will be read-only.
1767 @end deftypefun
1768
1769 @deftypefun uint32_t pte_create_user (uint32_t *@var{page}, bool @var{writable})
1770 Returns a page table entry that points to @var{page}, which should be
1771 the kernel virtual address of a frame in the user pool (@pxref{Why
1772 PAL_USER?}).  The PTE's present bit will be set and it will be marked to
1773 allow user-mode access.  If @var{writable} is true, the PTE will also be
1774 marked read/write; otherwise, it will be read-only.
1775 @end deftypefun
1776
1777 @deftypefun {void *} pte_get_page (uint32_t @var{pte})
1778 Returns the kernel virtual address for the frame that @var{pte} points
1779 to.  The @var{pte} may be present or not-present; if it is not-present
1780 then the pointer returned is only meaningful if the address bits in the PTE
1781 actually represent a physical address.
1782 @end deftypefun
1783
1784 @node Page Directory Entry Format
1785 @subsubsection Page Directory Entry Format
1786
1787 Page directory entries have the same format as PTEs, except that the
1788 physical address points to a page table page instead of a frame.  Header
1789 @file{threads/pte.h} defines two functions for working with page
1790 directory entries:
1791
1792 @deftypefun uint32_t pde_create (uint32_t *@var{pt})
1793 Returns a page directory that points to @var{page}, which should be the
1794 kernel virtual address of a page table page.  The PDE's present bit will
1795 be set, it will be marked to allow user-mode access, and it will be
1796 marked read/write.
1797 @end deftypefun
1798
1799 @deftypefun {uint32_t *} pde_get_pt (uint32_t @var{pde})
1800 Returns the kernel virtual address for the page table page that
1801 @var{pde}, which must be marked present, points to.
1802 @end deftypefun
1803
1804 @node Hash Table
1805 @section Hash Table
1806
1807 Pintos provides a hash table data structure in @file{lib/kernel/hash.c}.
1808 To use it you will need to include its header file,
1809 @file{lib/kernel/hash.h}, with @code{#include <hash.h>}.
1810 No code provided with Pintos uses the hash table, which means that you
1811 are free to use it as is, modify its implementation for your own
1812 purposes, or ignore it, as you wish.
1813
1814 Most implementations of the virtual memory project use a hash table to
1815 translate pages to frames.  You may find other uses for hash tables as
1816 well.
1817
1818 @menu
1819 * Hash Data Types::             
1820 * Basic Hash Functions::        
1821 * Hash Search Functions::       
1822 * Hash Iteration Functions::    
1823 * Hash Table Example::          
1824 * Hash Auxiliary Data::         
1825 * Hash Synchronization::        
1826 @end menu
1827
1828 @node Hash Data Types
1829 @subsection Data Types
1830
1831 A hash table is represented by @struct{hash}.
1832
1833 @deftp {Type} {struct hash}
1834 Represents an entire hash table.  The actual members of @struct{hash}
1835 are ``opaque.''  That is, code that uses a hash table should not access
1836 @struct{hash} members directly, nor should it need to.  Instead, use
1837 hash table functions and macros.
1838 @end deftp
1839
1840 The hash table operates on elements of type @struct{hash_elem}.
1841
1842 @deftp {Type} {struct hash_elem}
1843 Embed a @struct{hash_elem} member in the structure you want to include
1844 in a hash table.  Like @struct{hash}, @struct{hash_elem} is opaque.
1845 All functions for operating on hash table elements actually take and
1846 return pointers to @struct{hash_elem}, not pointers to your hash table's
1847 real element type.
1848 @end deftp
1849
1850 You will often need to obtain a @struct{hash_elem} given a real element
1851 of the hash table, and vice versa.  Given a real element of the hash
1852 table, you may use the @samp{&} operator to obtain a pointer to its
1853 @struct{hash_elem}.  Use the @code{hash_entry()} macro to go the other
1854 direction.
1855
1856 @deftypefn {Macro} {@var{type} *} hash_entry (struct hash_elem *@var{elem}, @var{type}, @var{member})
1857 Returns a pointer to the structure that @var{elem}, a pointer to a
1858 @struct{hash_elem}, is embedded within.  You must provide @var{type},
1859 the name of the structure that @var{elem} is inside, and @var{member},
1860 the name of the member in @var{type} that @var{elem} points to.
1861
1862 For example, suppose @code{h} is a @code{struct hash_elem *} variable
1863 that points to a @struct{thread} member (of type @struct{hash_elem})
1864 named @code{h_elem}.  Then, @code{hash_entry@tie{}(h, struct thread, h_elem)}
1865 yields the address of the @struct{thread} that @code{h} points within.
1866 @end deftypefn
1867
1868 @xref{Hash Table Example}, for an example.
1869
1870 Each hash table element must contain a key, that is, data that
1871 identifies and distinguishes elements, which must be unique
1872 among elements in the hash table.  (Elements may
1873 also contain non-key data that need not be unique.)  While an element is
1874 in a hash table, its key data must not be changed.  Instead, if need be,
1875 remove the element from the hash table, modify its key, then reinsert
1876 the element.
1877
1878 For each hash table, you must write two functions that act on keys: a
1879 hash function and a comparison function.  These functions must match the
1880 following prototypes:
1881
1882 @deftp {Type} {unsigned hash_hash_func (const struct hash_elem *@var{element}, void *@var{aux})}
1883 Returns a hash of @var{element}'s data, as a value anywhere in the range
1884 of @code{unsigned int}.  The hash of an element should be a
1885 pseudo-random function of the element's key.  It must not depend on
1886 non-key data in the element or on any non-constant data other than the
1887 key.  Pintos provides the following functions as a suitable basis for
1888 hash functions.
1889
1890 @deftypefun unsigned hash_bytes (const void *@var{buf}, size_t *@var{size})
1891 Returns a hash of the @var{size} bytes starting at @var{buf}.  The
1892 implementation is the general-purpose
1893 @uref{http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash, Fowler-Noll-Vo
1894 hash} for 32-bit words.
1895 @end deftypefun
1896
1897 @deftypefun unsigned hash_string (const char *@var{s})
1898 Returns a hash of null-terminated string @var{s}.
1899 @end deftypefun
1900
1901 @deftypefun unsigned hash_int (int @var{i})
1902 Returns a hash of integer @var{i}.
1903 @end deftypefun
1904
1905 If your key is a single piece of data of an appropriate type, it is
1906 sensible for your hash function to directly return the output of one of
1907 these functions.  For multiple pieces of data, you may wish to combine
1908 the output of more than one call to them using, e.g., the @samp{^}
1909 (exclusive or)
1910 operator.  Finally, you may entirely ignore these functions and write
1911 your own hash function from scratch, but remember that your goal is to
1912 build an operating system kernel, not to design a hash function.
1913
1914 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1915 @end deftp
1916
1917 @deftp {Type} {bool hash_less_func (const struct hash_elem *@var{a}, const struct hash_elem *@var{b}, void *@var{aux})}
1918 Compares the keys stored in elements @var{a} and @var{b}.  Returns
1919 true if @var{a} is less than @var{b}, false if @var{a} is greater than
1920 or equal to @var{b}.
1921
1922 If two elements compare equal, then they must hash to equal values.
1923
1924 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1925 @end deftp
1926
1927 @xref{Hash Table Example}, for hash and comparison function examples.
1928
1929 A few functions accept a pointer to a third kind of
1930 function as an argument:
1931
1932 @deftp {Type} {void hash_action_func (struct hash_elem *@var{element}, void *@var{aux})}
1933 Performs some kind of action, chosen by the caller, on @var{element}.
1934
1935 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}.
1936 @end deftp
1937
1938 @node Basic Hash Functions
1939 @subsection Basic Functions
1940
1941 These functions create, destroy, and inspect hash tables.
1942
1943 @deftypefun bool hash_init (struct hash *@var{hash}, hash_hash_func *@var{hash_func}, hash_less_func *@var{less_func}, void *@var{aux})
1944 Initializes @var{hash} as a hash table with @var{hash_func} as hash
1945 function, @var{less_func} as comparison function, and @var{aux} as
1946 auxiliary data.
1947 Returns true if successful, false on failure.  @func{hash_init} calls
1948 @func{malloc} and fails if memory cannot be allocated.
1949
1950 @xref{Hash Auxiliary Data}, for an explanation of @var{aux}, which is
1951 most often a null pointer.
1952 @end deftypefun
1953
1954 @deftypefun void hash_clear (struct hash *@var{hash}, hash_action_func *@var{action})
1955 Removes all the elements from @var{hash}, which must have been
1956 previously initialized with @func{hash_init}.
1957
1958 If @var{action} is non-null, then it is called once for each element in
1959 the hash table, which gives the caller an opportunity to deallocate any
1960 memory or other resources used by the element.  For example, if the hash
1961 table elements are dynamically allocated using @func{malloc}, then
1962 @var{action} could @func{free} the element.  This is safe because
1963 @func{hash_clear} will not access the memory in a given hash element
1964 after calling @var{action} on it.  However, @var{action} must not call
1965 any function that may modify the hash table, such as @func{hash_insert}
1966 or @func{hash_delete}.
1967 @end deftypefun
1968
1969 @deftypefun void hash_destroy (struct hash *@var{hash}, hash_action_func *@var{action})
1970 If @var{action} is non-null, calls it for each element in the hash, with
1971 the same semantics as a call to @func{hash_clear}.  Then, frees the
1972 memory held by @var{hash}.  Afterward, @var{hash} must not be passed to
1973 any hash table function, absent an intervening call to @func{hash_init}.
1974 @end deftypefun
1975
1976 @deftypefun size_t hash_size (struct hash *@var{hash})
1977 Returns the number of elements currently stored in @var{hash}.
1978 @end deftypefun
1979
1980 @deftypefun bool hash_empty (struct hash *@var{hash})
1981 Returns true if @var{hash} currently contains no elements,
1982 false if @var{hash} contains at least one element.
1983 @end deftypefun
1984
1985 @node Hash Search Functions
1986 @subsection Search Functions
1987
1988 Each of these functions searches a hash table for an element that
1989 compares equal to one provided.  Based on the success of the search,
1990 they perform some action, such as inserting a new element into the hash
1991 table, or simply return the result of the search.
1992
1993 @deftypefun {struct hash_elem *} hash_insert (struct hash *@var{hash}, struct hash_elem *@var{element})
1994 Searches @var{hash} for an element equal to @var{element}.  If none is
1995 found, inserts @var{element} into @var{hash} and returns a null pointer.
1996 If the table already contains an element equal to @var{element}, it is
1997 returned without modifying @var{hash}.
1998 @end deftypefun
1999
2000 @deftypefun {struct hash_elem *} hash_replace (struct hash *@var{hash}, struct hash_elem *@var{element})
2001 Inserts @var{element} into @var{hash}.  Any element equal to
2002 @var{element} already in @var{hash} is removed.  Returns the element
2003 removed, or a null pointer if @var{hash} did not contain an element
2004 equal to @var{element}.
2005
2006 The caller is responsible for deallocating any resources associated with
2007 the returned element, as appropriate.  For example, if the hash table
2008 elements are dynamically allocated using @func{malloc}, then the caller
2009 must @func{free} the element after it is no longer needed.
2010 @end deftypefun
2011
2012 The element passed to the following functions is only used for hashing
2013 and comparison purposes.  It is never actually inserted into the hash
2014 table.  Thus, only key data in the element needs to be initialized, and
2015 other data in the element will not be used.  It often makes sense to
2016 declare an instance of the element type as a local variable, initialize
2017 the key data, and then pass the address of its @struct{hash_elem} to
2018 @func{hash_find} or @func{hash_delete}.  @xref{Hash Table Example}, for
2019 an example.  (Large structures should not be
2020 allocated as local variables.  @xref{struct thread}, for more
2021 information.)
2022
2023 @deftypefun {struct hash_elem *} hash_find (struct hash *@var{hash}, struct hash_elem *@var{element})
2024 Searches @var{hash} for an element equal to @var{element}.  Returns the
2025 element found, if any, or a null pointer otherwise.
2026 @end deftypefun
2027
2028 @deftypefun {struct hash_elem *} hash_delete (struct hash *@var{hash}, struct hash_elem *@var{element})
2029 Searches @var{hash} for an element equal to @var{element}.  If one is
2030 found, it is removed from @var{hash} and returned.  Otherwise, a null
2031 pointer is returned and @var{hash} is unchanged.
2032
2033 The caller is responsible for deallocating any resources associated with
2034 the returned element, as appropriate.  For example, if the hash table
2035 elements are dynamically allocated using @func{malloc}, then the caller
2036 must @func{free} the element after it is no longer needed.
2037 @end deftypefun
2038
2039 @node Hash Iteration Functions
2040 @subsection Iteration Functions
2041
2042 These functions allow iterating through the elements in a hash table.
2043 Two interfaces are supplied.  The first requires writing and supplying a
2044 @var{hash_action_func} to act on each element (@pxref{Hash Data Types}).
2045
2046 @deftypefun void hash_apply (struct hash *@var{hash}, hash_action_func *@var{action})
2047 Calls @var{action} once for each element in @var{hash}, in arbitrary
2048 order.  @var{action} must not call any function that may modify the hash
2049 table, such as @func{hash_insert} or @func{hash_delete}.  @var{action}
2050 must not modify key data in elements, although it may modify any other
2051 data.
2052 @end deftypefun
2053
2054 The second interface is based on an ``iterator'' data type.
2055 Idiomatically, iterators are used as follows:
2056
2057 @example
2058 struct hash_iterator i;
2059
2060 hash_first (&i, h);
2061 while (hash_next (&i))
2062   @{
2063     struct foo *f = hash_entry (hash_cur (&i), struct foo, elem);
2064     @r{@dots{}do something with @i{f}@dots{}}
2065   @}
2066 @end example
2067
2068 @deftp {Type} {struct hash_iterator}
2069 Represents a position within a hash table.  Calling any function that
2070 may modify a hash table, such as @func{hash_insert} or
2071 @func{hash_delete}, invalidates all iterators within that hash table.
2072
2073 Like @struct{hash} and @struct{hash_elem}, @struct{hash_elem} is opaque.
2074 @end deftp
2075
2076 @deftypefun void hash_first (struct hash_iterator *@var{iterator}, struct hash *@var{hash})
2077 Initializes @var{iterator} to just before the first element in
2078 @var{hash}.
2079 @end deftypefun
2080
2081 @deftypefun {struct hash_elem *} hash_next (struct hash_iterator *@var{iterator})
2082 Advances @var{iterator} to the next element in @var{hash}, and returns
2083 that element.  Returns a null pointer if no elements remain.  After
2084 @func{hash_next} returns null for @var{iterator}, calling it again
2085 yields undefined behavior.
2086 @end deftypefun
2087
2088 @deftypefun {struct hash_elem *} hash_cur (struct hash_iterator *@var{iterator})
2089 Returns the value most recently returned by @func{hash_next} for
2090 @var{iterator}.  Yields undefined behavior after @func{hash_first} has
2091 been called on @var{iterator} but before @func{hash_next} has been
2092 called for the first time.
2093 @end deftypefun
2094
2095 @node Hash Table Example
2096 @subsection Hash Table Example
2097
2098 Suppose you have a structure, called @struct{page}, that you
2099 want to put into a hash table.  First, define @struct{page} to include a
2100 @struct{hash_elem} member:
2101
2102 @example
2103 struct page
2104   @{
2105     struct hash_elem hash_elem; /* @r{Hash table element.} */
2106     void *addr;                 /* @r{Virtual address.} */
2107     /* @r{@dots{}other members@dots{}} */
2108   @};
2109 @end example
2110
2111 We write a hash function and a comparison function using @var{addr} as
2112 the key.  A pointer can be hashed based on its bytes, and the @samp{<}
2113 operator works fine for comparing pointers:
2114
2115 @example
2116 /* @r{Returns a hash value for page @var{p}.} */
2117 unsigned
2118 page_hash (const struct hash_elem *p_, void *aux UNUSED)
2119 @{
2120   const struct page *p = hash_entry (p_, struct page, hash_elem);
2121   return hash_bytes (&p->addr, sizeof p->addr);
2122 @}
2123
2124 /* @r{Returns true if page @var{a} precedes page @var{b}.} */
2125 bool
2126 page_less (const struct hash_elem *a_, const struct hash_elem *b_,
2127            void *aux UNUSED)
2128 @{
2129   const struct page *a = hash_entry (a_, struct page, hash_elem);
2130   const struct page *b = hash_entry (b_, struct page, hash_elem);
2131
2132   return a->addr < b->addr;
2133 @}
2134 @end example
2135
2136 @noindent
2137 (The use of @code{UNUSED} in these functions' prototypes suppresses a
2138 warning that @var{aux} is unused.  @xref{Function and Parameter
2139 Attributes}, for information about @code{UNUSED}.  @xref{Hash Auxiliary
2140 Data}, for an explanation of @var{aux}.)
2141
2142 Then, we can create a hash table like this:
2143
2144 @example
2145 struct hash pages;
2146
2147 hash_init (&pages, page_hash, page_less, NULL);
2148 @end example
2149
2150 Now we can manipulate the hash table we've created.  If @code{@var{p}}
2151 is a pointer to a @struct{page}, we can insert it into the hash table
2152 with:
2153
2154 @example
2155 hash_insert (&pages, &p->hash_elem);
2156 @end example
2157
2158 @noindent If there's a chance that @var{pages} might already contain a
2159 page with the same @var{addr}, then we should check @func{hash_insert}'s
2160 return value.
2161
2162 To search for an element in the hash table, use @func{hash_find}.  This
2163 takes a little setup, because @func{hash_find} takes an element to
2164 compare against.  Here's a function that will find and return a page
2165 based on a virtual address, assuming that @var{pages} is defined at file
2166 scope:
2167
2168 @example
2169 /* @r{Returns the page containing the given virtual @var{address},}
2170    @r{or a null pointer if no such page exists.} */
2171 struct page *
2172 page_lookup (const void *address)
2173 @{
2174   struct page p;
2175   struct hash_elem *e;
2176
2177   p.addr = address;
2178   e = hash_find (&pages, &p.hash_elem);
2179   return e != NULL ? hash_entry (e, struct page, hash_elem) : NULL;
2180 @}
2181 @end example
2182
2183 @noindent
2184 @struct{page} is allocated as a local variable here on the assumption
2185 that it is fairly small.  Large structures should not be allocated as
2186 local variables.  @xref{struct thread}, for more information.
2187
2188 A similar function could delete a page by address using
2189 @func{hash_delete}.
2190
2191 @node Hash Auxiliary Data
2192 @subsection Auxiliary Data
2193
2194 In simple cases like the example above, there's no need for the
2195 @var{aux} parameters.  In these cases, just pass a null pointer to
2196 @func{hash_init} for @var{aux} and ignore the values passed to the hash
2197 function and comparison functions.  (You'll get a compiler warning if
2198 you don't use the @var{aux} parameter, but you can turn that off with
2199 the @code{UNUSED} macro, as shown in the example, or you can just ignore
2200 it.)
2201
2202 @var{aux} is useful when you have some property of the data in the
2203 hash table is both constant and needed for hashing or comparison,
2204 but not stored in the data items themselves.  For example, if
2205 the items in a hash table are fixed-length strings, but the items
2206 themselves don't indicate what that fixed length is, you could pass
2207 the length as an @var{aux} parameter.
2208
2209 @node Hash Synchronization
2210 @subsection Synchronization
2211
2212 The hash table does not do any internal synchronization.  It is the
2213 caller's responsibility to synchronize calls to hash table functions.
2214 In general, any number of functions that examine but do not modify the
2215 hash table, such as @func{hash_find} or @func{hash_next}, may execute
2216 simultaneously.  However, these function cannot safely execute at the
2217 same time as any function that may modify a given hash table, such as
2218 @func{hash_insert} or @func{hash_delete}, nor may more than one function
2219 that can modify a given hash table execute safely at once.
2220
2221 It is also the caller's responsibility to synchronize access to data in
2222 hash table elements.  How to synchronize access to this data depends on
2223 how it is designed and organized, as with any other data structure.
2224