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