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