1 Index: src/Makefile.build
2 diff -u src/Makefile.build~ src/Makefile.build
3 --- src/Makefile.build~ 2005-06-18 20:20:47.000000000 -0700
4 +++ src/Makefile.build 2006-04-08 18:52:50.000000000 -0700
5 @@ -53,7 +53,9 @@ userprog_SRC += userprog/gdt.c # GDT in
6 userprog_SRC += userprog/tss.c # TSS management.
8 # No virtual memory code yet.
9 -#vm_SRC = vm/filename.c # Some file.
15 filesys_SRC = filesys/filesys.c # Filesystem core.
16 Index: src/devices/timer.c
17 diff -u src/devices/timer.c~ src/devices/timer.c
18 --- src/devices/timer.c~ 2005-07-06 13:45:36.000000000 -0700
19 +++ src/devices/timer.c 2006-04-08 18:52:50.000000000 -0700
20 @@ -23,6 +23,9 @@ static volatile int64_t ticks;
21 Initialized by timer_calibrate(). */
22 static unsigned loops_per_tick;
24 +/* Threads waiting in timer_sleep(). */
25 +static struct list wait_list;
27 static intr_handler_func timer_interrupt;
28 static bool too_many_loops (unsigned loops);
29 static void busy_wait (int64_t loops);
30 @@ -43,6 +46,8 @@ timer_init (void)
31 outb (0x40, count >> 8);
33 intr_register_ext (0x20, timer_interrupt, "8254 Timer");
35 + list_init (&wait_list);
38 /* Calibrates loops_per_tick, used to implement brief delays. */
39 @@ -87,15 +92,36 @@ timer_elapsed (int64_t then)
40 return timer_ticks () - then;
43 +/* Compares two threads based on their wake-up times. */
45 +compare_threads_by_wakeup_time (const struct list_elem *a_,
46 + const struct list_elem *b_,
49 + const struct thread *a = list_entry (a_, struct thread, timer_elem);
50 + const struct thread *b = list_entry (b_, struct thread, timer_elem);
52 + return a->wakeup_time < b->wakeup_time;
55 /* Suspends execution for approximately TICKS timer ticks. */
57 timer_sleep (int64_t ticks)
59 - int64_t start = timer_ticks ();
60 + struct thread *t = thread_current ();
62 + /* Schedule our wake-up time. */
63 + t->wakeup_time = timer_ticks () + ticks;
65 + /* Atomically insert the current thread into the wait list. */
66 ASSERT (intr_get_level () == INTR_ON);
67 - while (timer_elapsed (start) < ticks)
70 + list_insert_ordered (&wait_list, &t->timer_elem,
71 + compare_threads_by_wakeup_time, NULL);
75 + sema_down (&t->timer_sema);
78 /* Suspends execution for approximately MS milliseconds. */
79 @@ -132,6 +158,16 @@ timer_interrupt (struct intr_frame *args
84 + while (!list_empty (&wait_list))
86 + struct thread *t = list_entry (list_front (&wait_list),
87 + struct thread, timer_elem);
88 + if (ticks < t->wakeup_time)
90 + sema_up (&t->timer_sema);
91 + list_pop_front (&wait_list);
95 /* Returns true if LOOPS iterations waits for more than one timer
96 Index: src/threads/init.c
97 diff -u src/threads/init.c~ src/threads/init.c
98 --- src/threads/init.c~ 2006-01-29 13:32:55.000000000 -0800
99 +++ src/threads/init.c 2006-04-08 18:52:50.000000000 -0700
101 #include "filesys/filesys.h"
102 #include "filesys/fsutil.h"
104 +#include "vm/frame.h"
105 +#include "vm/swap.h"
107 /* Amount of physical memory, in 4 kB pages. */
109 @@ -124,6 +126,9 @@ main (void)
110 filesys_init (format_filesys);
116 printf ("Boot complete.\n");
118 /* Run actions specified on kernel command line. */
119 Index: src/threads/interrupt.c
120 diff -u src/threads/interrupt.c~ src/threads/interrupt.c
121 --- src/threads/interrupt.c~ 2006-01-29 13:32:55.000000000 -0800
122 +++ src/threads/interrupt.c 2006-04-08 18:52:50.000000000 -0700
123 @@ -354,6 +354,8 @@ intr_handler (struct intr_frame *frame)
124 in_external_intr = true;
125 yield_on_return = false;
128 + thread_current ()->user_esp = frame->esp;
130 /* Invoke the interrupt's handler.
131 If there is no handler, invoke the unexpected interrupt
132 Index: src/threads/thread.c
133 diff -u src/threads/thread.c~ src/threads/thread.c
134 --- src/threads/thread.c~ 2006-04-08 12:09:39.000000000 -0700
135 +++ src/threads/thread.c 2006-04-08 18:52:50.000000000 -0700
137 #include "threads/synch.h"
139 #include "userprog/process.h"
140 +#include "userprog/syscall.h"
143 /* Random value for struct thread's `magic' member.
144 @@ -55,7 +56,8 @@ static void kernel_thread (thread_func *
145 static void idle (void *aux UNUSED);
146 static struct thread *running_thread (void);
147 static struct thread *next_thread_to_run (void);
148 -static void init_thread (struct thread *, const char *name, int priority);
149 +static void init_thread (struct thread *, const char *name, int priority,
151 static bool is_thread (struct thread *) UNUSED;
152 static void *alloc_frame (struct thread *, size_t size);
153 static void schedule (void);
154 @@ -82,9 +84,8 @@ thread_init (void)
156 /* Set up a thread structure for the running thread. */
157 initial_thread = running_thread ();
158 - init_thread (initial_thread, "main", PRI_DEFAULT);
159 + init_thread (initial_thread, "main", PRI_DEFAULT, 0);
160 initial_thread->status = THREAD_RUNNING;
161 - initial_thread->tid = allocate_tid ();
164 /* Starts preemptive thread scheduling by enabling interrupts.
165 @@ -159,8 +160,8 @@ thread_create (const char *name, int pri
168 /* Initialize thread. */
169 - init_thread (t, name, priority);
170 - tid = t->tid = allocate_tid ();
171 + init_thread (t, name, priority, allocate_tid ());
174 /* Stack frame for kernel_thread(). */
175 kf = alloc_frame (t, sizeof *kf);
176 @@ -253,16 +254,19 @@ thread_tid (void)
180 + struct thread *t = thread_current ();
182 ASSERT (!intr_context ());
190 /* Just set our status to dying and schedule another process.
191 We will be destroyed during the call to schedule_tail(). */
193 - thread_current ()->status = THREAD_DYING;
194 + t->status = THREAD_DYING;
198 @@ -406,17 +410,28 @@ is_thread (struct thread *t)
199 /* Does basic initialization of T as a blocked thread named
202 -init_thread (struct thread *t, const char *name, int priority)
203 +init_thread (struct thread *t, const char *name, int priority, tid_t tid)
206 ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
207 ASSERT (name != NULL);
209 memset (t, 0, sizeof *t);
211 t->status = THREAD_BLOCKED;
212 strlcpy (t->name, name, sizeof t->name);
213 t->stack = (uint8_t *) t + PGSIZE;
214 t->priority = priority;
216 + t->wait_status = NULL;
217 + list_init (&t->children);
218 + sema_init (&t->timer_sema, 0);
221 + t->bin_file = NULL;
222 + list_init (&t->fds);
223 + list_init (&t->mappings);
224 + t->next_handle = 2;
225 t->magic = THREAD_MAGIC;
228 Index: src/threads/thread.h
229 diff -u src/threads/thread.h~ src/threads/thread.h
230 --- src/threads/thread.h~ 2005-06-18 20:21:21.000000000 -0700
231 +++ src/threads/thread.h 2006-04-08 18:52:50.000000000 -0700
233 #define THREADS_THREAD_H
239 +#include "threads/synch.h"
241 /* States in a thread's life cycle. */
243 @@ -89,18 +91,49 @@ struct thread
244 uint8_t *stack; /* Saved stack pointer. */
245 int priority; /* Priority. */
247 + /* Owned by process.c. */
248 + int exit_code; /* Exit code. */
249 + struct wait_status *wait_status; /* This process's completion status. */
250 + struct list children; /* Completion status of children. */
252 /* Shared between thread.c and synch.c. */
253 struct list_elem elem; /* List element. */
257 + int64_t wakeup_time; /* Time to wake this thread up. */
258 + struct list_elem timer_elem; /* Element in timer_wait_list. */
259 + struct semaphore timer_sema; /* Semaphore. */
261 /* Owned by userprog/process.c. */
262 uint32_t *pagedir; /* Page directory. */
264 + struct hash *pages; /* Page table. */
265 + struct file *bin_file; /* The binary executable. */
267 + /* Owned by syscall.c. */
268 + struct list fds; /* List of file descriptors. */
269 + struct list mappings; /* Memory-mapped files. */
270 + int next_handle; /* Next handle value. */
271 + void *user_esp; /* User's stack pointer. */
273 /* Owned by thread.c. */
274 unsigned magic; /* Detects stack overflow. */
277 +/* Tracks the completion of a process.
278 + Reference held by both the parent, in its `children' list,
279 + and by the child, in its `wait_status' pointer. */
282 + struct list_elem elem; /* `children' list element. */
283 + struct lock lock; /* Protects ref_cnt. */
284 + int ref_cnt; /* 2=child and parent both alive,
285 + 1=either child or parent alive,
286 + 0=child and parent both dead. */
287 + tid_t tid; /* Child thread id. */
288 + int exit_code; /* Child exit code, if dead. */
289 + struct semaphore dead; /* 1=child alive, 0=child dead. */
292 void thread_init (void);
293 void thread_start (void);
295 Index: src/userprog/exception.c
296 diff -u src/userprog/exception.c~ src/userprog/exception.c
297 --- src/userprog/exception.c~ 2006-01-29 13:32:56.000000000 -0800
298 +++ src/userprog/exception.c 2006-04-08 18:52:50.000000000 -0700
300 #include "userprog/gdt.h"
301 #include "threads/interrupt.h"
302 #include "threads/thread.h"
303 +#include "vm/page.h"
305 /* Number of page faults processed. */
306 static long long page_fault_cnt;
307 @@ -148,9 +149,14 @@ page_fault (struct intr_frame *f)
308 write = (f->error_code & PF_W) != 0;
309 user = (f->error_code & PF_U) != 0;
311 - /* To implement virtual memory, delete the rest of the function
312 - body, and replace it with code that brings in the page to
313 - which fault_addr refers. */
314 + /* Allow the pager to try to handle it. */
315 + if (user && not_present)
317 + if (!page_in (fault_addr))
322 printf ("Page fault at %p: %s error %s page in %s context.\n",
324 not_present ? "not present" : "rights violation",
325 Index: src/userprog/pagedir.c
326 diff -u src/userprog/pagedir.c~ src/userprog/pagedir.c
327 --- src/userprog/pagedir.c~ 2006-01-29 13:32:56.000000000 -0800
328 +++ src/userprog/pagedir.c 2006-04-08 18:52:50.000000000 -0700
329 @@ -35,15 +35,7 @@ pagedir_destroy (uint32_t *pd)
330 ASSERT (pd != base_page_dir);
331 for (pde = pd; pde < pd + pd_no (PHYS_BASE); pde++)
334 - uint32_t *pt = pde_get_pt (*pde);
337 - for (pte = pt; pte < pt + PGSIZE / sizeof *pte; pte++)
339 - palloc_free_page (pte_get_page (*pte));
340 - palloc_free_page (pt);
342 + palloc_free_page (pde_get_pt (*pde));
343 palloc_free_page (pd);
346 Index: src/userprog/process.c
347 diff -u src/userprog/process.c~ src/userprog/process.c
348 --- src/userprog/process.c~ 2006-04-08 19:37:00.000000000 -0700
349 +++ src/userprog/process.c 2006-04-08 19:35:29.000000000 -0700
351 #include "threads/init.h"
352 #include "threads/interrupt.h"
353 +#include "threads/malloc.h"
354 #include "threads/palloc.h"
355 #include "threads/thread.h"
356 #include "threads/vaddr.h"
357 +#include "vm/page.h"
358 +#include "vm/frame.h"
360 static thread_func execute_thread NO_RETURN;
361 -static bool load (const char *cmdline, void (**eip) (void), void **esp);
362 +static bool load (const char *cmd_line, void (**eip) (void), void **esp);
364 +/* Data structure shared between process_execute() in the
365 + invoking thread and execute_thread() in the newly invoked
369 + const char *filename; /* Program to load. */
370 + struct semaphore load_done; /* "Up"ed when loading complete. */
371 + struct wait_status *wait_status; /* Child process. */
372 + bool success; /* Program successfully loaded? */
375 /* Starts a new thread running a user program loaded from
376 FILENAME. The new thread may be scheduled (and may even exit)
377 @@ -28,29 +42,37 @@ static bool load (const char *cmdline, v
379 process_execute (const char *filename)
382 + struct exec_info exec;
383 + char thread_name[16];
387 - /* Make a copy of FILENAME.
388 - Otherwise there's a race between the caller and load(). */
389 - fn_copy = palloc_get_page (0);
390 - if (fn_copy == NULL)
392 - strlcpy (fn_copy, filename, PGSIZE);
393 + /* Initialize exec_info. */
394 + exec.filename = filename;
395 + sema_init (&exec.load_done, 0);
397 /* Create a new thread to execute FILENAME. */
398 - tid = thread_create (filename, PRI_DEFAULT, execute_thread, fn_copy);
399 - if (tid == TID_ERROR)
400 - palloc_free_page (fn_copy);
401 + strlcpy (thread_name, filename, sizeof thread_name);
402 + strtok_r (thread_name, " ", &save_ptr);
403 + tid = thread_create (thread_name, PRI_DEFAULT, execute_thread, &exec);
404 + if (tid != TID_ERROR)
406 + sema_down (&exec.load_done);
408 + list_push_back (&thread_current ()->children, &exec.wait_status->elem);
416 /* A thread function that loads a user process and starts it
419 -execute_thread (void *filename_)
420 +execute_thread (void *exec_)
422 - char *filename = filename_;
423 + struct exec_info *exec = exec_;
424 struct intr_frame if_;
427 @@ -59,10 +81,28 @@ execute_thread (void *filename_)
428 if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
430 if_.eflags = FLAG_IF | FLAG_MBS;
431 - success = load (filename, &if_.eip, &if_.esp);
432 + success = load (exec->filename, &if_.eip, &if_.esp);
434 + /* Allocate wait_status. */
437 + exec->wait_status = thread_current ()->wait_status
438 + = malloc (sizeof *exec->wait_status);
439 + success = exec->wait_status != NULL;
442 - /* If load failed, quit. */
443 - palloc_free_page (filename);
444 + /* Initialize wait_status. */
447 + lock_init (&exec->wait_status->lock);
448 + exec->wait_status->ref_cnt = 2;
449 + exec->wait_status->tid = thread_current ()->tid;
450 + sema_init (&exec->wait_status->dead, 0);
453 + /* Notify parent thread and clean up. */
454 + exec->success = success;
455 + sema_up (&exec->load_done);
459 @@ -76,18 +116,47 @@ execute_thread (void *filename_)
463 +/* Releases one reference to CS and, if it is now unreferenced,
466 +release_child (struct wait_status *cs)
470 + lock_acquire (&cs->lock);
471 + new_ref_cnt = --cs->ref_cnt;
472 + lock_release (&cs->lock);
474 + if (new_ref_cnt == 0)
478 /* Waits for thread TID to die and returns its exit status. If
479 it was terminated by the kernel (i.e. killed due to an
480 exception), returns -1. If TID is invalid or if it was not a
481 child of the calling process, or if process_wait() has already
482 been successfully called for the given TID, returns -1
483 - immediately, without waiting.
485 - This function will be implemented in problem 2-2. For now, it
487 + immediately, without waiting. */
489 -process_wait (tid_t child_tid UNUSED)
490 +process_wait (tid_t child_tid)
492 + struct thread *cur = thread_current ();
493 + struct list_elem *e;
495 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
498 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
499 + if (cs->tid == child_tid)
503 + sema_down (&cs->dead);
504 + exit_code = cs->exit_code;
505 + release_child (cs);
512 @@ -96,8 +165,35 @@ void
515 struct thread *cur = thread_current ();
516 + struct list_elem *e, *next;
519 + printf ("%s: exit(%d)\n", cur->name, cur->exit_code);
521 + /* Notify parent that we're dead. */
522 + if (cur->wait_status != NULL)
524 + struct wait_status *cs = cur->wait_status;
525 + cs->exit_code = cur->exit_code;
526 + sema_up (&cs->dead);
527 + release_child (cs);
530 + /* Free entries of children list. */
531 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
534 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
535 + next = list_remove (e);
536 + release_child (cs);
539 + /* Destroy the page hash table. */
542 + /* Close executable (and allow writes). */
543 + file_close (cur->bin_file);
545 /* Destroy the current process's page directory and switch back
546 to the kernel-only page directory. */
548 @@ -194,7 +290,7 @@ struct Elf32_Phdr
549 #define PF_W 2 /* Writable. */
550 #define PF_R 4 /* Readable. */
552 -static bool setup_stack (void **esp);
553 +static bool setup_stack (const char *cmd_line, void **esp);
554 static bool validate_segment (const struct Elf32_Phdr *, struct file *);
555 static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
556 uint32_t read_bytes, uint32_t zero_bytes,
557 @@ -205,13 +301,15 @@ static bool load_segment (struct file *f
558 and its initial stack pointer into *ESP.
559 Returns true if successful, false otherwise. */
561 -load (const char *filename, void (**eip) (void), void **esp)
562 +load (const char *cmd_line, void (**eip) (void), void **esp)
564 struct thread *t = thread_current ();
565 + char filename[NAME_MAX + 2];
566 struct Elf32_Ehdr ehdr;
567 struct file *file = NULL;
569 bool success = false;
573 /* Allocate and activate page directory. */
574 @@ -220,13 +318,28 @@ load (const char *filename, void (**eip)
578 + /* Create page hash table. */
579 + t->pages = malloc (sizeof *t->pages);
580 + if (t->pages == NULL)
582 + hash_init (t->pages, page_hash, page_less, NULL);
584 + /* Extract filename from command line. */
585 + while (*cmd_line == ' ')
587 + strlcpy (filename, cmd_line, sizeof filename);
588 + cp = strchr (filename, ' ');
592 /* Open executable file. */
593 - file = filesys_open (filename);
594 + t->bin_file = file = filesys_open (filename);
597 printf ("load: %s: open failed\n", filename);
600 + file_deny_write (t->bin_file);
602 /* Read and verify executable header. */
603 if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
604 @@ -301,7 +414,7 @@ load (const char *filename, void (**eip)
608 - if (!setup_stack (esp))
609 + if (!setup_stack (cmd_line, esp))
613 @@ -311,14 +424,11 @@ load (const char *filename, void (**eip)
616 /* We arrive here whether the load is successful or not. */
621 /* load() helpers. */
623 -static bool install_page (void *upage, void *kpage, bool writable);
625 /* Checks whether PHDR describes a valid, loadable segment in
626 FILE and returns true if so, false otherwise. */
628 @@ -387,79 +497,127 @@ load_segment (struct file *file, off_t o
629 ASSERT (pg_ofs (upage) == 0);
630 ASSERT (ofs % PGSIZE == 0);
632 - file_seek (file, ofs);
633 while (read_bytes > 0 || zero_bytes > 0)
635 - /* Calculate how to fill this page.
636 - We will read PAGE_READ_BYTES bytes from FILE
637 - and zero the final PAGE_ZERO_BYTES bytes. */
638 size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
639 size_t page_zero_bytes = PGSIZE - page_read_bytes;
641 - /* Get a page of memory. */
642 - uint8_t *kpage = palloc_get_page (PAL_USER);
644 + struct page *p = page_allocate (upage, !writable);
648 - /* Load this page. */
649 - if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
651 - palloc_free_page (kpage);
654 - memset (kpage + page_read_bytes, 0, page_zero_bytes);
656 - /* Add the page to the process's address space. */
657 - if (!install_page (upage, kpage, writable))
658 + if (page_read_bytes > 0)
660 - palloc_free_page (kpage);
663 + p->file_offset = ofs;
664 + p->file_bytes = page_read_bytes;
668 read_bytes -= page_read_bytes;
669 zero_bytes -= page_zero_bytes;
670 + ofs += page_read_bytes;
676 -/* Create a minimal stack by mapping a zeroed page at the top of
677 - user virtual memory. */
678 +/* Reverse the order of the ARGC pointers to char in ARGV. */
680 +reverse (int argc, char **argv)
682 + for (; argc > 1; argc -= 2, argv++)
684 + char *tmp = argv[0];
685 + argv[0] = argv[argc - 1];
686 + argv[argc - 1] = tmp;
690 +/* Pushes the SIZE bytes in BUF onto the stack in KPAGE, whose
691 + page-relative stack pointer is *OFS, and then adjusts *OFS
692 + appropriately. The bytes pushed are rounded to a 32-bit
695 + If successful, returns a pointer to the newly pushed object.
696 + On failure, returns a null pointer. */
698 +push (uint8_t *kpage, size_t *ofs, const void *buf, size_t size)
700 + size_t padsize = ROUND_UP (size, sizeof (uint32_t));
701 + if (*ofs < padsize)
705 + memcpy (kpage + *ofs + (padsize - size), buf, size);
706 + return kpage + *ofs + (padsize - size);
709 +/* Sets up command line arguments in KPAGE, which will be mapped
710 + to UPAGE in user space. The command line arguments are taken
711 + from CMD_LINE, separated by spaces. Sets *ESP to the initial
712 + stack pointer for the process. */
714 -setup_stack (void **esp)
715 +init_cmd_line (uint8_t *kpage, uint8_t *upage, const char *cmd_line,
719 - bool success = false;
720 + size_t ofs = PGSIZE;
721 + char *const null = NULL;
722 + char *cmd_line_copy;
723 + char *karg, *saveptr;
727 + /* Push command line string. */
728 + cmd_line_copy = push (kpage, &ofs, cmd_line, strlen (cmd_line) + 1);
729 + if (cmd_line_copy == NULL)
732 + if (push (kpage, &ofs, &null, sizeof null) == NULL)
735 - kpage = palloc_get_page (PAL_USER | PAL_ZERO);
737 + /* Parse command line into arguments
738 + and push them in reverse order. */
740 + for (karg = strtok_r (cmd_line_copy, " ", &saveptr); karg != NULL;
741 + karg = strtok_r (NULL, " ", &saveptr))
743 - success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
747 - palloc_free_page (kpage);
748 + void *uarg = upage + (karg - (char *) kpage);
749 + if (push (kpage, &ofs, &uarg, sizeof uarg) == NULL)
755 + /* Reverse the order of the command line arguments. */
756 + argv = (char **) (upage + ofs);
757 + reverse (argc, (char **) (kpage + ofs));
759 + /* Push argv, argc, "return address". */
760 + if (push (kpage, &ofs, &argv, sizeof argv) == NULL
761 + || push (kpage, &ofs, &argc, sizeof argc) == NULL
762 + || push (kpage, &ofs, &null, sizeof null) == NULL)
765 + /* Set initial stack pointer. */
766 + *esp = upage + ofs;
770 -/* Adds a mapping from user virtual address UPAGE to kernel
771 - virtual address KPAGE to the page table.
772 - If WRITABLE is true, the user process may modify the page;
773 - otherwise, it is read-only.
774 - UPAGE must not already be mapped.
775 - KPAGE should probably be a page obtained from the user pool
776 - with palloc_get_page().
777 - Returns true on success, false if UPAGE is already mapped or
778 - if memory allocation fails. */
779 +/* Create a minimal stack for T by mapping a page at the
780 + top of user virtual memory. Fills in the page using CMD_LINE
781 + and sets *ESP to the stack pointer. */
783 -install_page (void *upage, void *kpage, bool writable)
784 +setup_stack (const char *cmd_line, void **esp)
786 - struct thread *t = thread_current ();
788 - /* Verify that there's not already a page at that virtual
789 - address, then map our page there. */
790 - return (pagedir_get_page (t->pagedir, upage) == NULL
791 - && pagedir_set_page (t->pagedir, upage, kpage, writable));
792 + struct page *page = page_allocate (((uint8_t *) PHYS_BASE) - PGSIZE, false);
795 + page->frame = frame_alloc_and_lock (page);
796 + if (page->frame != NULL)
799 + page->read_only = false;
800 + page->private = false;
801 + ok = init_cmd_line (page->frame->base, page->addr, cmd_line, esp);
802 + frame_unlock (page->frame);
808 Index: src/userprog/syscall.c
809 diff -u src/userprog/syscall.c~ src/userprog/syscall.c
810 --- src/userprog/syscall.c~ 2005-06-18 20:21:21.000000000 -0700
811 +++ src/userprog/syscall.c 2006-04-08 19:36:04.000000000 -0700
813 #include "userprog/syscall.h"
816 #include <syscall-nr.h>
817 +#include "userprog/process.h"
818 +#include "userprog/pagedir.h"
819 +#include "devices/kbd.h"
820 +#include "filesys/directory.h"
821 +#include "filesys/filesys.h"
822 +#include "filesys/file.h"
823 +#include "threads/init.h"
824 #include "threads/interrupt.h"
825 +#include "threads/malloc.h"
826 +#include "threads/palloc.h"
827 #include "threads/thread.h"
828 +#include "threads/vaddr.h"
830 +#include "vm/page.h"
833 +static int sys_halt (void);
834 +static int sys_exit (int status);
835 +static int sys_exec (const char *ufile);
836 +static int sys_wait (tid_t);
837 +static int sys_create (const char *ufile, unsigned initial_size);
838 +static int sys_remove (const char *ufile);
839 +static int sys_open (const char *ufile);
840 +static int sys_filesize (int handle);
841 +static int sys_read (int handle, void *udst_, unsigned size);
842 +static int sys_write (int handle, void *usrc_, unsigned size);
843 +static int sys_seek (int handle, unsigned position);
844 +static int sys_tell (int handle);
845 +static int sys_close (int handle);
846 +static int sys_mmap (int handle, void *addr);
847 +static int sys_munmap (int mapping);
849 static void syscall_handler (struct intr_frame *);
851 +static void copy_in (void *, const void *, size_t);
856 intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
859 +/* System call handler. */
861 +syscall_handler (struct intr_frame *f)
863 + typedef int syscall_function (int, int, int);
865 + /* A system call. */
868 + size_t arg_cnt; /* Number of arguments. */
869 + syscall_function *func; /* Implementation. */
872 + /* Table of system calls. */
873 + static const struct syscall syscall_table[] =
875 + {0, (syscall_function *) sys_halt},
876 + {1, (syscall_function *) sys_exit},
877 + {1, (syscall_function *) sys_exec},
878 + {1, (syscall_function *) sys_wait},
879 + {2, (syscall_function *) sys_create},
880 + {1, (syscall_function *) sys_remove},
881 + {1, (syscall_function *) sys_open},
882 + {1, (syscall_function *) sys_filesize},
883 + {3, (syscall_function *) sys_read},
884 + {3, (syscall_function *) sys_write},
885 + {2, (syscall_function *) sys_seek},
886 + {1, (syscall_function *) sys_tell},
887 + {1, (syscall_function *) sys_close},
888 + {2, (syscall_function *) sys_mmap},
889 + {1, (syscall_function *) sys_munmap},
892 + const struct syscall *sc;
896 + /* Get the system call. */
897 + copy_in (&call_nr, f->esp, sizeof call_nr);
898 + if (call_nr >= sizeof syscall_table / sizeof *syscall_table)
900 + sc = syscall_table + call_nr;
902 + /* Get the system call arguments. */
903 + ASSERT (sc->arg_cnt <= sizeof args / sizeof *args);
904 + memset (args, 0, sizeof args);
905 + copy_in (args, (uint32_t *) f->esp + 1, sizeof *args * sc->arg_cnt);
907 + /* Execute the system call,
908 + and set the return value. */
909 + f->eax = sc->func (args[0], args[1], args[2]);
912 +/* Copies SIZE bytes from user address USRC to kernel address
914 + Call thread_exit() if any of the user accesses are invalid. */
916 -syscall_handler (struct intr_frame *f UNUSED)
917 +copy_in (void *dst_, const void *usrc_, size_t size)
919 + uint8_t *dst = dst_;
920 + const uint8_t *usrc = usrc_;
924 + size_t chunk_size = PGSIZE - pg_ofs (usrc);
925 + if (chunk_size > size)
928 + if (!page_lock (usrc, false))
930 + memcpy (dst, usrc, chunk_size);
931 + page_unlock (usrc);
934 + usrc += chunk_size;
935 + size -= chunk_size;
939 +/* Creates a copy of user string US in kernel memory
940 + and returns it as a page that must be freed with
941 + palloc_free_page().
942 + Truncates the string at PGSIZE bytes in size.
943 + Call thread_exit() if any of the user accesses are invalid. */
945 +copy_in_string (const char *us)
951 + ks = palloc_get_page (0);
958 + upage = pg_round_down (us);
959 + if (!page_lock (upage, false))
962 + for (; us < upage + PGSIZE; us++)
964 + ks[length++] = *us;
967 + page_unlock (upage);
970 + else if (length >= PGSIZE)
971 + goto too_long_error;
974 + page_unlock (upage);
978 + page_unlock (upage);
980 + palloc_free_page (ks);
984 +/* Halt system call. */
991 +/* Exit system call. */
993 +sys_exit (int exit_code)
995 + thread_current ()->exit_code = exit_code;
1000 +/* Exec system call. */
1002 +sys_exec (const char *ufile)
1005 + char *kfile = copy_in_string (ufile);
1007 + tid = process_execute (kfile);
1009 + palloc_free_page (kfile);
1014 +/* Wait system call. */
1016 +sys_wait (tid_t child)
1018 + return process_wait (child);
1021 +/* Create system call. */
1023 +sys_create (const char *ufile, unsigned initial_size)
1025 + char *kfile = copy_in_string (ufile);
1026 + bool ok = filesys_create (kfile, initial_size);
1027 + palloc_free_page (kfile);
1032 +/* Remove system call. */
1034 +sys_remove (const char *ufile)
1036 + char *kfile = copy_in_string (ufile);
1037 + bool ok = filesys_remove (kfile);
1038 + palloc_free_page (kfile);
1043 +/* A file descriptor, for binding a file handle to a file. */
1044 +struct file_descriptor
1046 + struct list_elem elem; /* List element. */
1047 + struct file *file; /* File. */
1048 + int handle; /* File handle. */
1051 +/* Open system call. */
1053 +sys_open (const char *ufile)
1055 + char *kfile = copy_in_string (ufile);
1056 + struct file_descriptor *fd;
1059 + fd = malloc (sizeof *fd);
1062 + fd->file = filesys_open (kfile);
1063 + if (fd->file != NULL)
1065 + struct thread *cur = thread_current ();
1066 + handle = fd->handle = cur->next_handle++;
1067 + list_push_front (&cur->fds, &fd->elem);
1073 + palloc_free_page (kfile);
1077 +/* Returns the file descriptor associated with the given handle.
1078 + Terminates the process if HANDLE is not associated with an
1080 +static struct file_descriptor *
1081 +lookup_fd (int handle)
1083 + struct thread *cur = thread_current ();
1084 + struct list_elem *e;
1086 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds);
1087 + e = list_next (e))
1089 + struct file_descriptor *fd;
1090 + fd = list_entry (e, struct file_descriptor, elem);
1091 + if (fd->handle == handle)
1098 +/* Filesize system call. */
1100 +sys_filesize (int handle)
1102 + struct file_descriptor *fd = lookup_fd (handle);
1105 + size = file_length (fd->file);
1110 +/* Read system call. */
1112 +sys_read (int handle, void *udst_, unsigned size)
1114 - printf ("system call!\n");
1115 + uint8_t *udst = udst_;
1116 + struct file_descriptor *fd;
1117 + int bytes_read = 0;
1119 + /* Look up file descriptor. */
1120 + if (handle != STDIN_FILENO)
1121 + fd = lookup_fd (handle);
1125 + /* How much to read into this page? */
1126 + size_t page_left = PGSIZE - pg_ofs (udst);
1127 + size_t read_amt = size < page_left ? size : page_left;
1130 + /* Check that touching this page is okay. */
1131 + if (!page_lock (udst, true))
1134 + /* Read from file into page. */
1135 + if (handle != STDIN_FILENO)
1137 + retval = file_read (fd->file, udst, read_amt);
1140 + if (bytes_read == 0)
1144 + bytes_read += retval;
1150 + for (i = 0; i < read_amt; i++)
1151 + udst[i] = kbd_getc ();
1152 + bytes_read = read_amt;
1155 + /* Release page. */
1156 + page_unlock (udst);
1158 + /* If it was a short read we're done. */
1159 + if (retval != (off_t) read_amt)
1167 + return bytes_read;
1170 +/* Write system call. */
1172 +sys_write (int handle, void *usrc_, unsigned size)
1174 + uint8_t *usrc = usrc_;
1175 + struct file_descriptor *fd = NULL;
1176 + int bytes_written = 0;
1178 + /* Lookup up file descriptor. */
1179 + if (handle != STDOUT_FILENO)
1180 + fd = lookup_fd (handle);
1184 + /* How much bytes to write to this page? */
1185 + size_t page_left = PGSIZE - pg_ofs (usrc);
1186 + size_t write_amt = size < page_left ? size : page_left;
1189 + /* Check that we can touch this user page. */
1190 + if (!page_lock (usrc, false))
1193 + /* Do the write. */
1194 + if (handle == STDOUT_FILENO)
1196 + putbuf ((char *) usrc, write_amt);
1197 + retval = write_amt;
1200 + retval = file_write (fd->file, usrc, write_amt);
1202 + /* Release user page. */
1203 + page_unlock (usrc);
1205 + /* Handle return value. */
1208 + if (bytes_written == 0)
1209 + bytes_written = -1;
1212 + bytes_written += retval;
1214 + /* If it was a short write we're done. */
1215 + if (retval != (off_t) write_amt)
1223 + return bytes_written;
1226 +/* Seek system call. */
1228 +sys_seek (int handle, unsigned position)
1230 + if ((off_t) position >= 0)
1231 + file_seek (lookup_fd (handle)->file, position);
1235 +/* Tell system call. */
1237 +sys_tell (int handle)
1239 + return file_tell (lookup_fd (handle)->file);
1242 +/* Close system call. */
1244 +sys_close (int handle)
1246 + struct file_descriptor *fd = lookup_fd (handle);
1247 + file_close (fd->file);
1248 + list_remove (&fd->elem);
1253 +/* Binds a mapping id to a region of memory and a file. */
1256 + struct list_elem elem; /* List element. */
1257 + int handle; /* Mapping id. */
1258 + struct file *file; /* File. */
1259 + uint8_t *base; /* Start of memory mapping. */
1260 + size_t page_cnt; /* Number of pages mapped. */
1263 +/* Returns the file descriptor associated with the given handle.
1264 + Terminates the process if HANDLE is not associated with a
1265 + memory mapping. */
1266 +static struct mapping *
1267 +lookup_mapping (int handle)
1269 + struct thread *cur = thread_current ();
1270 + struct list_elem *e;
1272 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1273 + e = list_next (e))
1275 + struct mapping *m = list_entry (e, struct mapping, elem);
1276 + if (m->handle == handle)
1283 +/* Remove mapping M from the virtual address space,
1284 + writing back any pages that have changed. */
1286 +unmap (struct mapping *m)
1288 + list_remove (&m->elem);
1289 + while (m->page_cnt-- > 0)
1291 + page_deallocate (m->base);
1292 + m->base += PGSIZE;
1294 + file_close (m->file);
1298 +/* Mmap system call. */
1300 +sys_mmap (int handle, void *addr)
1302 + struct file_descriptor *fd = lookup_fd (handle);
1303 + struct mapping *m = malloc (sizeof *m);
1307 + if (m == NULL || addr == NULL || pg_ofs (addr) != 0)
1310 + m->handle = thread_current ()->next_handle++;
1311 + m->file = file_reopen (fd->file);
1312 + if (m->file == NULL)
1319 + list_push_front (&thread_current ()->mappings, &m->elem);
1322 + length = file_length (m->file);
1323 + while (length > 0)
1325 + struct page *p = page_allocate ((uint8_t *) addr + offset, false);
1331 + p->private = false;
1332 + p->file = m->file;
1333 + p->file_offset = offset;
1334 + p->file_bytes = length >= PGSIZE ? PGSIZE : length;
1335 + offset += p->file_bytes;
1336 + length -= p->file_bytes;
1343 +/* Munmap system call. */
1345 +sys_munmap (int mapping)
1347 + unmap (lookup_mapping (mapping));
1351 +/* On thread exit, close all open files and unmap all mappings. */
1353 +syscall_exit (void)
1355 + struct thread *cur = thread_current ();
1356 + struct list_elem *e, *next;
1358 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds); e = next)
1360 + struct file_descriptor *fd = list_entry (e, struct file_descriptor, elem);
1361 + next = list_next (e);
1362 + file_close (fd->file);
1366 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1369 + struct mapping *m = list_entry (e, struct mapping, elem);
1370 + next = list_next (e);
1374 Index: src/userprog/syscall.h
1375 diff -u src/userprog/syscall.h~ src/userprog/syscall.h
1376 --- src/userprog/syscall.h~ 2004-09-05 22:38:45.000000000 -0700
1377 +++ src/userprog/syscall.h 2006-04-08 18:52:50.000000000 -0700
1379 #define USERPROG_SYSCALL_H
1381 void syscall_init (void);
1382 +void syscall_exit (void);
1384 #endif /* userprog/syscall.h */
1385 Index: src/vm/frame.c
1386 diff -u src/vm/frame.c~ src/vm/frame.c
1387 --- src/vm/frame.c~ 1969-12-31 16:00:00.000000000 -0800
1388 +++ src/vm/frame.c 2006-04-08 18:52:50.000000000 -0700
1390 +#include "vm/frame.h"
1392 +#include "vm/page.h"
1393 +#include "devices/timer.h"
1394 +#include "threads/init.h"
1395 +#include "threads/malloc.h"
1396 +#include "threads/palloc.h"
1397 +#include "threads/synch.h"
1398 +#include "threads/vaddr.h"
1400 +static struct frame *frames;
1401 +static size_t frame_cnt;
1403 +static struct lock scan_lock;
1404 +static size_t hand;
1406 +/* Initialize the frame manager. */
1412 + lock_init (&scan_lock);
1414 + frames = malloc (sizeof *frames * ram_pages);
1415 + if (frames == NULL)
1416 + PANIC ("out of memory allocating page frames");
1418 + while ((base = palloc_get_page (PAL_USER)) != NULL)
1420 + struct frame *f = &frames[frame_cnt++];
1421 + lock_init (&f->lock);
1427 +/* Tries to allocate and lock a frame for PAGE.
1428 + Returns the frame if successful, false on failure. */
1429 +static struct frame *
1430 +try_frame_alloc_and_lock (struct page *page)
1434 + lock_acquire (&scan_lock);
1436 + /* Find a free frame. */
1437 + for (i = 0; i < frame_cnt; i++)
1439 + struct frame *f = &frames[i];
1440 + if (!lock_try_acquire (&f->lock))
1442 + if (f->page == NULL)
1445 + lock_release (&scan_lock);
1448 + lock_release (&f->lock);
1451 + /* No free frame. Find a frame to evict. */
1452 + for (i = 0; i < frame_cnt * 2; i++)
1454 + /* Get a frame. */
1455 + struct frame *f = &frames[hand];
1456 + if (++hand >= frame_cnt)
1459 + if (!lock_try_acquire (&f->lock))
1462 + if (f->page == NULL)
1465 + lock_release (&scan_lock);
1469 + if (page_accessed_recently (f->page))
1471 + lock_release (&f->lock);
1475 + lock_release (&scan_lock);
1477 + /* Evict this frame. */
1478 + if (!page_out (f->page))
1480 + lock_release (&f->lock);
1488 + lock_release (&scan_lock);
1493 +/* Tries really hard to allocate and lock a frame for PAGE.
1494 + Returns the frame if successful, false on failure. */
1496 +frame_alloc_and_lock (struct page *page)
1500 + for (try = 0; try < 3; try++)
1502 + struct frame *f = try_frame_alloc_and_lock (page);
1505 + ASSERT (lock_held_by_current_thread (&f->lock));
1508 + timer_msleep (1000);
1514 +/* Locks P's frame into memory, if it has one.
1515 + Upon return, p->frame will not change until P is unlocked. */
1517 +frame_lock (struct page *p)
1519 + /* A frame can be asynchronously removed, but never inserted. */
1520 + struct frame *f = p->frame;
1523 + lock_acquire (&f->lock);
1524 + if (f != p->frame)
1526 + lock_release (&f->lock);
1527 + ASSERT (p->frame == NULL);
1532 +/* Releases frame F for use by another page.
1533 + F must be locked for use by the current process.
1534 + Any data in F is lost. */
1536 +frame_free (struct frame *f)
1538 + ASSERT (lock_held_by_current_thread (&f->lock));
1541 + lock_release (&f->lock);
1544 +/* Unlocks frame F, allowing it to be evicted.
1545 + F must be locked for use by the current process. */
1547 +frame_unlock (struct frame *f)
1549 + ASSERT (lock_held_by_current_thread (&f->lock));
1550 + lock_release (&f->lock);
1552 Index: src/vm/frame.h
1553 diff -u src/vm/frame.h~ src/vm/frame.h
1554 --- src/vm/frame.h~ 1969-12-31 16:00:00.000000000 -0800
1555 +++ src/vm/frame.h 2006-04-08 18:52:50.000000000 -0700
1560 +#include <stdbool.h>
1561 +#include "threads/synch.h"
1563 +/* A physical frame. */
1566 + struct lock lock; /* Prevent simultaneous access. */
1567 + void *base; /* Kernel virtual base address. */
1568 + struct page *page; /* Mapped process page, if any. */
1571 +void frame_init (void);
1573 +struct frame *frame_alloc_and_lock (struct page *);
1574 +void frame_lock (struct page *);
1576 +void frame_free (struct frame *);
1577 +void frame_unlock (struct frame *);
1579 +#endif /* vm/frame.h */
1580 Index: src/vm/page.c
1581 diff -u src/vm/page.c~ src/vm/page.c
1582 --- src/vm/page.c~ 1969-12-31 16:00:00.000000000 -0800
1583 +++ src/vm/page.c 2006-04-08 18:52:50.000000000 -0700
1585 +#include "vm/page.h"
1587 +#include <string.h>
1588 +#include "vm/frame.h"
1589 +#include "vm/swap.h"
1590 +#include "filesys/file.h"
1591 +#include "threads/malloc.h"
1592 +#include "threads/thread.h"
1593 +#include "userprog/pagedir.h"
1594 +#include "threads/vaddr.h"
1596 +/* Maximum size of process stack, in bytes. */
1597 +#define STACK_MAX (1024 * 1024)
1599 +/* Destroys a page, which must be in the current process's
1600 + page table. Used as a callback for hash_destroy(). */
1602 +destroy_page (struct hash_elem *p_, void *aux UNUSED)
1604 + struct page *p = hash_entry (p_, struct page, hash_elem);
1607 + frame_free (p->frame);
1611 +/* Destroys the current process's page table. */
1615 + struct hash *h = thread_current ()->pages;
1617 + hash_destroy (h, destroy_page);
1620 +/* Returns the page containing the given virtual ADDRESS,
1621 + or a null pointer if no such page exists.
1622 + Allocates stack pages as necessary. */
1623 +static struct page *
1624 +page_for_addr (const void *address)
1626 + if (address < PHYS_BASE)
1629 + struct hash_elem *e;
1631 + /* Find existing page. */
1632 + p.addr = (void *) pg_round_down (address);
1633 + e = hash_find (thread_current ()->pages, &p.hash_elem);
1635 + return hash_entry (e, struct page, hash_elem);
1637 + /* No page. Expand stack? */
1638 + if (address >= PHYS_BASE - STACK_MAX
1639 + && address >= thread_current ()->user_esp - 32)
1640 + return page_allocate ((void *) address, false);
1645 +/* Locks a frame for page P and pages it in.
1646 + Returns true if successful, false on failure. */
1648 +do_page_in (struct page *p)
1650 + /* Get a frame for the page. */
1651 + p->frame = frame_alloc_and_lock (p);
1652 + if (p->frame == NULL)
1655 + /* Copy data into the frame. */
1656 + if (p->sector != (disk_sector_t) -1)
1658 + /* Get data from swap. */
1661 + else if (p->file != NULL)
1663 + /* Get data from file. */
1664 + off_t read_bytes = file_read_at (p->file, p->frame->base,
1665 + p->file_bytes, p->file_offset);
1666 + off_t zero_bytes = PGSIZE - read_bytes;
1667 + memset (p->frame->base + read_bytes, 0, zero_bytes);
1668 + if (read_bytes != p->file_bytes)
1669 + printf ("bytes read (%"PROTd") != bytes requested (%"PROTd")\n",
1670 + read_bytes, p->file_bytes);
1674 + /* Provide all-zero page. */
1675 + memset (p->frame->base, 0, PGSIZE);
1681 +/* Faults in the page containing FAULT_ADDR.
1682 + Returns true if successful, false on failure. */
1684 +page_in (void *fault_addr)
1689 + /* Can't handle page faults without a hash table. */
1690 + if (thread_current ()->pages == NULL)
1693 + p = page_for_addr (fault_addr);
1698 + if (p->frame == NULL)
1700 + if (!do_page_in (p))
1703 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1705 + /* Install frame into page table. */
1706 + success = pagedir_set_page (thread_current ()->pagedir, p->addr,
1707 + p->frame->base, !p->read_only);
1709 + /* Release frame. */
1710 + frame_unlock (p->frame);
1716 + P must have a locked frame.
1717 + Return true if successful, false on failure. */
1719 +page_out (struct page *p)
1724 + ASSERT (p->frame != NULL);
1725 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1727 + /* Mark page not present in page table, forcing accesses by the
1728 + process to fault. This must happen before checking the
1729 + dirty bit, to prevent a race with the process dirtying the
1731 + pagedir_clear_page (p->thread->pagedir, p->addr);
1733 + /* Has the frame been modified? */
1734 + dirty = pagedir_is_dirty (p->thread->pagedir, p->addr);
1736 + /* Write frame contents to disk if necessary. */
1737 + if (p->file != NULL)
1742 + ok = swap_out (p);
1744 + ok = file_write_at (p->file, p->frame->base, p->file_bytes,
1745 + p->file_offset) == p->file_bytes;
1751 + ok = swap_out (p);
1754 + //memset (p->frame->base, 0xcc, PGSIZE);
1760 +/* Returns true if page P's data has been accessed recently,
1762 + P must have a frame locked into memory. */
1764 +page_accessed_recently (struct page *p)
1766 + bool was_accessed;
1768 + ASSERT (p->frame != NULL);
1769 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1771 + was_accessed = pagedir_is_accessed (p->thread->pagedir, p->addr);
1773 + pagedir_set_accessed (p->thread->pagedir, p->addr, false);
1774 + return was_accessed;
1777 +/* Adds a mapping for user virtual address VADDR to the page hash
1778 + table. Fails if VADDR is already mapped or if memory
1779 + allocation fails. */
1781 +page_allocate (void *vaddr, bool read_only)
1783 + struct thread *t = thread_current ();
1784 + struct page *p = malloc (sizeof *p);
1787 + p->addr = pg_round_down (vaddr);
1789 + p->read_only = read_only;
1790 + p->private = !read_only;
1794 + p->sector = (disk_sector_t) -1;
1797 + p->file_offset = 0;
1798 + p->file_bytes = 0;
1800 + p->thread = thread_current ();
1802 + if (hash_insert (t->pages, &p->hash_elem) != NULL)
1804 + /* Already mapped. */
1812 +/* Evicts the page containing address VADDR
1813 + and removes it from the page table. */
1815 +page_deallocate (void *vaddr)
1817 + struct page *p = page_for_addr (vaddr);
1818 + ASSERT (p != NULL);
1822 + struct frame *f = p->frame;
1823 + if (p->file && !p->private)
1827 + hash_delete (thread_current ()->pages, &p->hash_elem);
1831 +/* Returns a hash value for the page that E refers to. */
1833 +page_hash (const struct hash_elem *e, void *aux UNUSED)
1835 + const struct page *p = hash_entry (e, struct page, hash_elem);
1836 + return ((uintptr_t) p->addr) >> PGBITS;
1839 +/* Returns true if page A precedes page B. */
1841 +page_less (const struct hash_elem *a_, const struct hash_elem *b_,
1844 + const struct page *a = hash_entry (a_, struct page, hash_elem);
1845 + const struct page *b = hash_entry (b_, struct page, hash_elem);
1847 + return a->addr < b->addr;
1850 +/* Tries to lock the page containing ADDR into physical memory.
1851 + If WILL_WRITE is true, the page must be writeable;
1852 + otherwise it may be read-only.
1853 + Returns true if successful, false on failure. */
1855 +page_lock (const void *addr, bool will_write)
1857 + struct page *p = page_for_addr (addr);
1858 + if (p == NULL || (p->read_only && will_write))
1862 + if (p->frame == NULL)
1863 + return (do_page_in (p)
1864 + && pagedir_set_page (thread_current ()->pagedir, p->addr,
1865 + p->frame->base, !p->read_only));
1870 +/* Unlocks a page locked with page_lock(). */
1872 +page_unlock (const void *addr)
1874 + struct page *p = page_for_addr (addr);
1875 + ASSERT (p != NULL);
1876 + frame_unlock (p->frame);
1878 Index: src/vm/page.h
1879 diff -u src/vm/page.h~ src/vm/page.h
1880 --- src/vm/page.h~ 1969-12-31 16:00:00.000000000 -0800
1881 +++ src/vm/page.h 2006-04-08 18:52:50.000000000 -0700
1887 +#include "devices/disk.h"
1888 +#include "filesys/off_t.h"
1889 +#include "threads/synch.h"
1891 +/* Virtual page. */
1894 + /* Immutable members. */
1895 + void *addr; /* User virtual address. */
1896 + bool read_only; /* Read-only page? */
1897 + struct thread *thread; /* Owning thread. */
1899 + /* Accessed only in owning process context. */
1900 + struct hash_elem hash_elem; /* struct thread `pages' hash element. */
1902 + /* Set only in owning process context with frame->frame_lock held.
1903 + Cleared only with scan_lock and frame->frame_lock held. */
1904 + struct frame *frame; /* Page frame. */
1906 + /* Swap information, protected by frame->frame_lock. */
1907 + disk_sector_t sector; /* Starting sector of swap area, or -1. */
1909 + /* Memory-mapped file information, protected by frame->frame_lock. */
1910 + bool private; /* False to write back to file,
1911 + true to write back to swap. */
1912 + struct file *file; /* File. */
1913 + off_t file_offset; /* Offset in file. */
1914 + off_t file_bytes; /* Bytes to read/write, 1...PGSIZE. */
1917 +void page_exit (void);
1919 +struct page *page_allocate (void *, bool read_only);
1920 +void page_deallocate (void *vaddr);
1922 +bool page_in (void *fault_addr);
1923 +bool page_out (struct page *);
1924 +bool page_accessed_recently (struct page *);
1926 +bool page_lock (const void *, bool will_write);
1927 +void page_unlock (const void *);
1929 +hash_hash_func page_hash;
1930 +hash_less_func page_less;
1932 +#endif /* vm/page.h */
1933 Index: src/vm/swap.c
1934 diff -u src/vm/swap.c~ src/vm/swap.c
1935 --- src/vm/swap.c~ 1969-12-31 16:00:00.000000000 -0800
1936 +++ src/vm/swap.c 2006-04-08 18:52:50.000000000 -0700
1938 +#include "vm/swap.h"
1939 +#include <bitmap.h>
1942 +#include "vm/frame.h"
1943 +#include "vm/page.h"
1944 +#include "devices/disk.h"
1945 +#include "threads/synch.h"
1946 +#include "threads/vaddr.h"
1948 +/* The swap disk. */
1949 +static struct disk *swap_disk;
1951 +/* Used swap pages. */
1952 +static struct bitmap *swap_bitmap;
1954 +/* Protects swap_bitmap. */
1955 +static struct lock swap_lock;
1957 +/* Number of sectors per page. */
1958 +#define PAGE_SECTORS (PGSIZE / DISK_SECTOR_SIZE)
1960 +/* Sets up swap. */
1964 + swap_disk = disk_get (1, 1);
1965 + if (swap_disk == NULL)
1967 + printf ("no swap disk--swap disabled\n");
1968 + swap_bitmap = bitmap_create (0);
1971 + swap_bitmap = bitmap_create (disk_size (swap_disk) / PAGE_SECTORS);
1972 + if (swap_bitmap == NULL)
1973 + PANIC ("couldn't create swap bitmap");
1974 + lock_init (&swap_lock);
1977 +/* Swaps in page P, which must have a locked frame
1978 + (and be swapped out). */
1980 +swap_in (struct page *p)
1984 + ASSERT (p->frame != NULL);
1985 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1986 + ASSERT (p->sector != (disk_sector_t) -1);
1988 + for (i = 0; i < PAGE_SECTORS; i++)
1989 + disk_read (swap_disk, p->sector + i,
1990 + p->frame->base + i * DISK_SECTOR_SIZE);
1991 + bitmap_reset (swap_bitmap, p->sector / PAGE_SECTORS);
1992 + p->sector = (disk_sector_t) -1;
1995 +/* Swaps out page P, which must have a locked frame. */
1997 +swap_out (struct page *p)
2002 + ASSERT (p->frame != NULL);
2003 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
2005 + lock_acquire (&swap_lock);
2006 + slot = bitmap_scan_and_flip (swap_bitmap, 0, 1, false);
2007 + lock_release (&swap_lock);
2008 + if (slot == BITMAP_ERROR)
2011 + p->sector = slot * PAGE_SECTORS;
2012 + for (i = 0; i < PAGE_SECTORS; i++)
2013 + disk_write (swap_disk, p->sector + i,
2014 + p->frame->base + i * DISK_SECTOR_SIZE);
2016 + p->private = false;
2018 + p->file_offset = 0;
2019 + p->file_bytes = 0;
2023 Index: src/vm/swap.h
2024 diff -u src/vm/swap.h~ src/vm/swap.h
2025 --- src/vm/swap.h~ 1969-12-31 16:00:00.000000000 -0800
2026 +++ src/vm/swap.h 2006-04-08 18:52:50.000000000 -0700
2029 +#define VM_SWAP_H 1
2031 +#include <stdbool.h>
2034 +void swap_init (void);
2035 +void swap_in (struct page *);
2036 +bool swap_out (struct page *);
2038 +#endif /* vm/swap.h */