1 Index: src/Makefile.build
2 diff -u src/Makefile.build~ src/Makefile.build
3 --- src/Makefile.build~
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/file.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~
19 +++ src/devices/timer.c
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. */
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 /* Sleeps for approximately TICKS timer ticks. Interrupts must
58 timer_sleep (int64_t ticks)
60 - int64_t start = timer_ticks ();
61 + struct thread *t = thread_current ();
63 + /* Schedule our wake-up time. */
64 + t->wakeup_time = timer_ticks () + ticks;
66 + /* Atomically insert the current thread into the wait list. */
67 ASSERT (intr_get_level () == INTR_ON);
68 - while (timer_elapsed (start) < ticks)
71 + list_insert_ordered (&wait_list, &t->timer_elem,
72 + compare_threads_by_wakeup_time, NULL);
76 + sema_down (&t->timer_sema);
79 /* Sleeps for approximately MS milliseconds. Interrupts must be
80 @@ -132,6 +158,16 @@ timer_interrupt (struct intr_frame *args
85 + while (!list_empty (&wait_list))
87 + struct thread *t = list_entry (list_front (&wait_list),
88 + struct thread, timer_elem);
89 + if (ticks < t->wakeup_time)
91 + sema_up (&t->timer_sema);
92 + list_pop_front (&wait_list);
96 /* Returns true if LOOPS iterations waits for more than one timer
97 Index: src/threads/init.c
98 diff -u src/threads/init.c~ src/threads/init.c
99 --- src/threads/init.c~
100 +++ src/threads/init.c
102 #include "filesys/filesys.h"
103 #include "filesys/fsutil.h"
105 +#include "vm/frame.h"
106 +#include "vm/swap.h"
108 /* Amount of physical memory, in 4 kB pages. */
110 @@ -124,6 +126,9 @@ main (void)
111 filesys_init (format_filesys);
117 printf ("Boot complete.\n");
119 /* Run actions specified on kernel command line. */
120 Index: src/threads/interrupt.c
121 diff -u src/threads/interrupt.c~ src/threads/interrupt.c
122 --- src/threads/interrupt.c~
123 +++ src/threads/interrupt.c
124 @@ -354,6 +354,8 @@ intr_handler (struct intr_frame *frame)
125 in_external_intr = true;
126 yield_on_return = false;
129 + thread_current ()->user_esp = frame->esp;
131 /* Invoke the interrupt's handler.
132 If there is no handler, invoke the unexpected interrupt
133 Index: src/threads/thread.c
134 diff -u src/threads/thread.c~ src/threads/thread.c
135 --- src/threads/thread.c~
136 +++ src/threads/thread.c
138 #include "threads/vaddr.h"
140 #include "userprog/process.h"
141 +#include "userprog/syscall.h"
144 /* Random value for struct thread's `magic' member.
145 @@ -55,7 +56,8 @@ static void kernel_thread (thread_func *
146 static void idle (void *aux UNUSED);
147 static struct thread *running_thread (void);
148 static struct thread *next_thread_to_run (void);
149 -static void init_thread (struct thread *, const char *name, int priority);
150 +static void init_thread (struct thread *, const char *name, int priority,
152 static bool is_thread (struct thread *) UNUSED;
153 static void *alloc_frame (struct thread *, size_t size);
154 static void schedule (void);
155 @@ -82,9 +84,8 @@ thread_init (void)
157 /* Set up a thread structure for the running thread. */
158 initial_thread = running_thread ();
159 - init_thread (initial_thread, "main", PRI_DEFAULT);
160 + init_thread (initial_thread, "main", PRI_DEFAULT, 0);
161 initial_thread->status = THREAD_RUNNING;
162 - initial_thread->tid = allocate_tid ();
165 /* Starts preemptive thread scheduling by enabling interrupts.
166 @@ -159,8 +160,8 @@ thread_create (const char *name, int pri
169 /* Initialize thread. */
170 - init_thread (t, name, priority);
171 - tid = t->tid = allocate_tid ();
172 + init_thread (t, name, priority, allocate_tid ());
175 /* Stack frame for kernel_thread(). */
176 kf = alloc_frame (t, sizeof *kf);
177 @@ -253,16 +254,19 @@ thread_tid (void)
181 + struct thread *t = thread_current ();
183 ASSERT (!intr_context ());
191 /* Just set our status to dying and schedule another process.
192 We will be destroyed during the call to schedule_tail(). */
194 - thread_current ()->status = THREAD_DYING;
195 + t->status = THREAD_DYING;
199 @@ -406,17 +410,28 @@ is_thread (struct thread *t)
200 /* Does basic initialization of T as a blocked thread named
203 -init_thread (struct thread *t, const char *name, int priority)
204 +init_thread (struct thread *t, const char *name, int priority, tid_t tid)
207 ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
208 ASSERT (name != NULL);
210 memset (t, 0, sizeof *t);
212 t->status = THREAD_BLOCKED;
213 strlcpy (t->name, name, sizeof t->name);
214 t->stack = (uint8_t *) t + PGSIZE;
215 t->priority = priority;
217 + t->wait_status = NULL;
218 + list_init (&t->children);
219 + sema_init (&t->timer_sema, 0);
222 + t->bin_file = NULL;
223 + list_init (&t->fds);
224 + list_init (&t->mappings);
225 + t->next_handle = 2;
226 t->magic = THREAD_MAGIC;
229 Index: src/threads/thread.h
230 diff -u src/threads/thread.h~ src/threads/thread.h
231 --- src/threads/thread.h~
232 +++ src/threads/thread.h
234 #define THREADS_THREAD_H
240 +#include "threads/synch.h"
242 /* States in a thread's life cycle. */
244 @@ -89,18 +91,49 @@ struct thread
245 uint8_t *stack; /* Saved stack pointer. */
246 int priority; /* Priority. */
248 + /* Owned by process.c. */
249 + int exit_code; /* Exit code. */
250 + struct wait_status *wait_status; /* This process's completion status. */
251 + struct list children; /* Completion status of children. */
253 /* Shared between thread.c and synch.c. */
254 struct list_elem elem; /* List element. */
258 + int64_t wakeup_time; /* Time to wake this thread up. */
259 + struct list_elem timer_elem; /* Element in timer_wait_list. */
260 + struct semaphore timer_sema; /* Semaphore. */
262 /* Owned by userprog/process.c. */
263 uint32_t *pagedir; /* Page directory. */
265 + struct hash *pages; /* Page table. */
266 + struct file *bin_file; /* The binary executable. */
268 + /* Owned by syscall.c. */
269 + struct list fds; /* List of file descriptors. */
270 + struct list mappings; /* Memory-mapped files. */
271 + int next_handle; /* Next handle value. */
272 + void *user_esp; /* User's stack pointer. */
274 /* Owned by thread.c. */
275 unsigned magic; /* Detects stack overflow. */
278 +/* Tracks the completion of a process.
279 + Reference held by both the parent, in its `children' list,
280 + and by the child, in its `wait_status' pointer. */
283 + struct list_elem elem; /* `children' list element. */
284 + struct lock lock; /* Protects ref_cnt. */
285 + int ref_cnt; /* 2=child and parent both alive,
286 + 1=either child or parent alive,
287 + 0=child and parent both dead. */
288 + tid_t tid; /* Child thread id. */
289 + int exit_code; /* Child exit code, if dead. */
290 + struct semaphore dead; /* 1=child alive, 0=child dead. */
293 /* If false (default), use round-robin scheduler.
294 If true, use multi-level feedback queue scheduler.
295 Controlled by kernel command-line options "-o mlfqs".
296 Index: src/userprog/exception.c
297 diff -u src/userprog/exception.c~ src/userprog/exception.c
298 --- src/userprog/exception.c~
299 +++ src/userprog/exception.c
301 #include "userprog/gdt.h"
302 #include "threads/interrupt.h"
303 #include "threads/thread.h"
304 +#include "vm/page.h"
306 /* Number of page faults processed. */
307 static long long page_fault_cnt;
308 @@ -148,9 +149,14 @@ page_fault (struct intr_frame *f)
309 write = (f->error_code & PF_W) != 0;
310 user = (f->error_code & PF_U) != 0;
312 - /* To implement virtual memory, delete the rest of the function
313 - body, and replace it with code that brings in the page to
314 - which fault_addr refers. */
315 + /* Allow the pager to try to handle it. */
316 + if (user && not_present)
318 + if (!page_in (fault_addr))
323 printf ("Page fault at %p: %s error %s page in %s context.\n",
325 not_present ? "not present" : "rights violation",
326 Index: src/userprog/pagedir.c
327 diff -u src/userprog/pagedir.c~ src/userprog/pagedir.c
328 --- src/userprog/pagedir.c~
329 +++ src/userprog/pagedir.c
330 @@ -35,15 +35,7 @@ pagedir_destroy (uint32_t *pd)
331 ASSERT (pd != base_page_dir);
332 for (pde = pd; pde < pd + pd_no (PHYS_BASE); pde++)
335 - uint32_t *pt = pde_get_pt (*pde);
338 - for (pte = pt; pte < pt + PGSIZE / sizeof *pte; pte++)
340 - palloc_free_page (pte_get_page (*pte));
341 - palloc_free_page (pt);
343 + palloc_free_page (pde_get_pt (*pde));
344 palloc_free_page (pd);
347 Index: src/userprog/process.c
348 diff -u src/userprog/process.c~ src/userprog/process.c
349 --- src/userprog/process.c~
350 +++ src/userprog/process.c
352 #include "threads/flags.h"
353 #include "threads/init.h"
354 #include "threads/interrupt.h"
355 +#include "threads/malloc.h"
356 #include "threads/palloc.h"
357 #include "threads/thread.h"
358 #include "threads/vaddr.h"
359 +#include "vm/page.h"
360 +#include "vm/frame.h"
362 static thread_func start_process NO_RETURN;
363 -static bool load (const char *cmdline, void (**eip) (void), void **esp);
364 +static bool load (const char *cmd_line, void (**eip) (void), void **esp);
366 +/* Data structure shared between process_execute() in the
367 + invoking thread and start_process() in the newly invoked
371 + const char *file_name; /* Program to load. */
372 + struct semaphore load_done; /* "Up"ed when loading complete. */
373 + struct wait_status *wait_status; /* Child process. */
374 + bool success; /* Program successfully loaded? */
377 /* Starts a new thread running a user program loaded from
378 FILE_NAME. The new thread may be scheduled (and may even exit)
379 @@ -28,29 +42,37 @@ static bool load (const char *cmdline, v
381 process_execute (const char *file_name)
384 + struct exec_info exec;
385 + char thread_name[16];
389 - /* Make a copy of FILE_NAME.
390 - Otherwise there's a race between the caller and load(). */
391 - fn_copy = palloc_get_page (0);
392 - if (fn_copy == NULL)
394 - strlcpy (fn_copy, file_name, PGSIZE);
395 + /* Initialize exec_info. */
396 + exec.file_name = file_name;
397 + sema_init (&exec.load_done, 0);
399 /* Create a new thread to execute FILE_NAME. */
400 - tid = thread_create (file_name, PRI_DEFAULT, start_process, fn_copy);
401 - if (tid == TID_ERROR)
402 - palloc_free_page (fn_copy);
403 + strlcpy (thread_name, file_name, sizeof thread_name);
404 + strtok_r (thread_name, " ", &save_ptr);
405 + tid = thread_create (thread_name, PRI_DEFAULT, start_process, &exec);
406 + if (tid != TID_ERROR)
408 + sema_down (&exec.load_done);
410 + list_push_back (&thread_current ()->children, &exec.wait_status->elem);
418 /* A thread function that loads a user process and starts it
421 -start_process (void *file_name_)
422 +start_process (void *exec_)
424 - char *file_name = file_name_;
425 + struct exec_info *exec = exec_;
426 struct intr_frame if_;
429 @@ -59,10 +81,28 @@ start_process (void *file_name_)
430 if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
432 if_.eflags = FLAG_IF | FLAG_MBS;
433 - success = load (file_name, &if_.eip, &if_.esp);
434 + success = load (exec->file_name, &if_.eip, &if_.esp);
436 + /* Allocate wait_status. */
439 + exec->wait_status = thread_current ()->wait_status
440 + = malloc (sizeof *exec->wait_status);
441 + success = exec->wait_status != NULL;
444 - /* If load failed, quit. */
445 - palloc_free_page (file_name);
446 + /* Initialize wait_status. */
449 + lock_init (&exec->wait_status->lock);
450 + exec->wait_status->ref_cnt = 2;
451 + exec->wait_status->tid = thread_current ()->tid;
452 + sema_init (&exec->wait_status->dead, 0);
455 + /* Notify parent thread and clean up. */
456 + exec->success = success;
457 + sema_up (&exec->load_done);
461 @@ -76,18 +116,47 @@ start_process (void *file_name_)
465 +/* Releases one reference to CS and, if it is now unreferenced,
468 +release_child (struct wait_status *cs)
472 + lock_acquire (&cs->lock);
473 + new_ref_cnt = --cs->ref_cnt;
474 + lock_release (&cs->lock);
476 + if (new_ref_cnt == 0)
480 /* Waits for thread TID to die and returns its exit status. If
481 it was terminated by the kernel (i.e. killed due to an
482 exception), returns -1. If TID is invalid or if it was not a
483 child of the calling process, or if process_wait() has already
484 been successfully called for the given TID, returns -1
485 - immediately, without waiting.
487 - This function will be implemented in problem 2-2. For now, it
489 + immediately, without waiting. */
491 -process_wait (tid_t child_tid UNUSED)
492 +process_wait (tid_t child_tid)
494 + struct thread *cur = thread_current ();
495 + struct list_elem *e;
497 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
500 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
501 + if (cs->tid == child_tid)
505 + sema_down (&cs->dead);
506 + exit_code = cs->exit_code;
507 + release_child (cs);
514 @@ -96,8 +165,35 @@ void
517 struct thread *cur = thread_current ();
518 + struct list_elem *e, *next;
521 + printf ("%s: exit(%d)\n", cur->name, cur->exit_code);
523 + /* Notify parent that we're dead. */
524 + if (cur->wait_status != NULL)
526 + struct wait_status *cs = cur->wait_status;
527 + cs->exit_code = cur->exit_code;
528 + sema_up (&cs->dead);
529 + release_child (cs);
532 + /* Free entries of children list. */
533 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
536 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
537 + next = list_remove (e);
538 + release_child (cs);
541 + /* Destroy the page hash table. */
544 + /* Close executable (and allow writes). */
545 + file_close (cur->bin_file);
547 /* Destroy the current process's page directory and switch back
548 to the kernel-only page directory. */
550 @@ -194,7 +290,7 @@ struct Elf32_Phdr
551 #define PF_W 2 /* Writable. */
552 #define PF_R 4 /* Readable. */
554 -static bool setup_stack (void **esp);
555 +static bool setup_stack (const char *cmd_line, void **esp);
556 static bool validate_segment (const struct Elf32_Phdr *, struct file *);
557 static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
558 uint32_t read_bytes, uint32_t zero_bytes,
559 @@ -205,13 +301,15 @@ static bool load_segment (struct file *f
560 and its initial stack pointer into *ESP.
561 Returns true if successful, false otherwise. */
563 -load (const char *file_name, void (**eip) (void), void **esp)
564 +load (const char *cmd_line, void (**eip) (void), void **esp)
566 struct thread *t = thread_current ();
567 + char file_name[NAME_MAX + 2];
568 struct Elf32_Ehdr ehdr;
569 struct file *file = NULL;
571 bool success = false;
575 /* Allocate and activate page directory. */
576 @@ -220,13 +318,28 @@ load (const char *file_name, void (**eip)
580 + /* Create page hash table. */
581 + t->pages = malloc (sizeof *t->pages);
582 + if (t->pages == NULL)
584 + hash_init (t->pages, page_hash, page_less, NULL);
586 + /* Extract file_name from command line. */
587 + while (*cmd_line == ' ')
589 + strlcpy (file_name, cmd_line, sizeof file_name);
590 + cp = strchr (file_name, ' ');
594 /* Open executable file. */
595 - file = filesys_open (file_name);
596 + t->bin_file = file = filesys_open (file_name);
599 printf ("load: %s: open failed\n", file_name);
602 + file_deny_write (t->bin_file);
604 /* Read and verify executable header. */
605 if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
606 @@ -301,7 +414,7 @@ load (const char *file_name, void (**eip)
610 - if (!setup_stack (esp))
611 + if (!setup_stack (cmd_line, esp))
615 @@ -311,14 +424,11 @@ load (const char *file_name, void (**eip)
618 /* We arrive here whether the load is successful or not. */
623 /* load() helpers. */
625 -static bool install_page (void *upage, void *kpage, bool writable);
627 /* Checks whether PHDR describes a valid, loadable segment in
628 FILE and returns true if so, false otherwise. */
630 @@ -387,79 +497,127 @@ load_segment (struct file *file, off_t o
631 ASSERT (pg_ofs (upage) == 0);
632 ASSERT (ofs % PGSIZE == 0);
634 - file_seek (file, ofs);
635 while (read_bytes > 0 || zero_bytes > 0)
637 - /* Calculate how to fill this page.
638 - We will read PAGE_READ_BYTES bytes from FILE
639 - and zero the final PAGE_ZERO_BYTES bytes. */
640 size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
641 size_t page_zero_bytes = PGSIZE - page_read_bytes;
643 - /* Get a page of memory. */
644 - uint8_t *kpage = palloc_get_page (PAL_USER);
646 + struct page *p = page_allocate (upage, !writable);
650 - /* Load this page. */
651 - if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
653 - palloc_free_page (kpage);
656 - memset (kpage + page_read_bytes, 0, page_zero_bytes);
658 - /* Add the page to the process's address space. */
659 - if (!install_page (upage, kpage, writable))
660 + if (page_read_bytes > 0)
662 - palloc_free_page (kpage);
665 + p->file_offset = ofs;
666 + p->file_bytes = page_read_bytes;
670 read_bytes -= page_read_bytes;
671 zero_bytes -= page_zero_bytes;
672 + ofs += page_read_bytes;
678 -/* Create a minimal stack by mapping a zeroed page at the top of
679 - user virtual memory. */
680 +/* Reverse the order of the ARGC pointers to char in ARGV. */
682 +reverse (int argc, char **argv)
684 + for (; argc > 1; argc -= 2, argv++)
686 + char *tmp = argv[0];
687 + argv[0] = argv[argc - 1];
688 + argv[argc - 1] = tmp;
692 +/* Pushes the SIZE bytes in BUF onto the stack in KPAGE, whose
693 + page-relative stack pointer is *OFS, and then adjusts *OFS
694 + appropriately. The bytes pushed are rounded to a 32-bit
697 + If successful, returns a pointer to the newly pushed object.
698 + On failure, returns a null pointer. */
700 +push (uint8_t *kpage, size_t *ofs, const void *buf, size_t size)
702 + size_t padsize = ROUND_UP (size, sizeof (uint32_t));
703 + if (*ofs < padsize)
707 + memcpy (kpage + *ofs + (padsize - size), buf, size);
708 + return kpage + *ofs + (padsize - size);
711 +/* Sets up command line arguments in KPAGE, which will be mapped
712 + to UPAGE in user space. The command line arguments are taken
713 + from CMD_LINE, separated by spaces. Sets *ESP to the initial
714 + stack pointer for the process. */
716 -setup_stack (void **esp)
717 +init_cmd_line (uint8_t *kpage, uint8_t *upage, const char *cmd_line,
721 - bool success = false;
722 + size_t ofs = PGSIZE;
723 + char *const null = NULL;
724 + char *cmd_line_copy;
725 + char *karg, *saveptr;
729 + /* Push command line string. */
730 + cmd_line_copy = push (kpage, &ofs, cmd_line, strlen (cmd_line) + 1);
731 + if (cmd_line_copy == NULL)
734 + if (push (kpage, &ofs, &null, sizeof null) == NULL)
737 - kpage = palloc_get_page (PAL_USER | PAL_ZERO);
739 + /* Parse command line into arguments
740 + and push them in reverse order. */
742 + for (karg = strtok_r (cmd_line_copy, " ", &saveptr); karg != NULL;
743 + karg = strtok_r (NULL, " ", &saveptr))
745 - success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
749 - palloc_free_page (kpage);
750 + void *uarg = upage + (karg - (char *) kpage);
751 + if (push (kpage, &ofs, &uarg, sizeof uarg) == NULL)
757 + /* Reverse the order of the command line arguments. */
758 + argv = (char **) (upage + ofs);
759 + reverse (argc, (char **) (kpage + ofs));
761 + /* Push argv, argc, "return address". */
762 + if (push (kpage, &ofs, &argv, sizeof argv) == NULL
763 + || push (kpage, &ofs, &argc, sizeof argc) == NULL
764 + || push (kpage, &ofs, &null, sizeof null) == NULL)
767 + /* Set initial stack pointer. */
768 + *esp = upage + ofs;
772 -/* Adds a mapping from user virtual address UPAGE to kernel
773 - virtual address KPAGE to the page table.
774 - If WRITABLE is true, the user process may modify the page;
775 - otherwise, it is read-only.
776 - UPAGE must not already be mapped.
777 - KPAGE should probably be a page obtained from the user pool
778 - with palloc_get_page().
779 - Returns true on success, false if UPAGE is already mapped or
780 - if memory allocation fails. */
781 +/* Create a minimal stack for T by mapping a page at the
782 + top of user virtual memory. Fills in the page using CMD_LINE
783 + and sets *ESP to the stack pointer. */
785 -install_page (void *upage, void *kpage, bool writable)
786 +setup_stack (const char *cmd_line, void **esp)
788 - struct thread *t = thread_current ();
790 - /* Verify that there's not already a page at that virtual
791 - address, then map our page there. */
792 - return (pagedir_get_page (t->pagedir, upage) == NULL
793 - && pagedir_set_page (t->pagedir, upage, kpage, writable));
794 + struct page *page = page_allocate (((uint8_t *) PHYS_BASE) - PGSIZE, false);
797 + page->frame = frame_alloc_and_lock (page);
798 + if (page->frame != NULL)
801 + page->read_only = false;
802 + page->private = false;
803 + ok = init_cmd_line (page->frame->base, page->addr, cmd_line, esp);
804 + frame_unlock (page->frame);
810 Index: src/userprog/syscall.c
811 diff -u src/userprog/syscall.c~ src/userprog/syscall.c
812 --- src/userprog/syscall.c~
813 +++ src/userprog/syscall.c
815 #include "userprog/syscall.h"
818 #include <syscall-nr.h>
819 +#include "userprog/process.h"
820 +#include "userprog/pagedir.h"
821 +#include "devices/input.h"
822 +#include "filesys/directory.h"
823 +#include "filesys/filesys.h"
824 +#include "filesys/file.h"
825 +#include "threads/init.h"
826 #include "threads/interrupt.h"
827 +#include "threads/malloc.h"
828 +#include "threads/palloc.h"
829 #include "threads/thread.h"
831 +#include "threads/vaddr.h"
832 +#include "vm/page.h"
835 +static int sys_halt (void);
836 +static int sys_exit (int status);
837 +static int sys_exec (const char *ufile);
838 +static int sys_wait (tid_t);
839 +static int sys_create (const char *ufile, unsigned initial_size);
840 +static int sys_remove (const char *ufile);
841 +static int sys_open (const char *ufile);
842 +static int sys_filesize (int handle);
843 +static int sys_read (int handle, void *udst_, unsigned size);
844 +static int sys_write (int handle, void *usrc_, unsigned size);
845 +static int sys_seek (int handle, unsigned position);
846 +static int sys_tell (int handle);
847 +static int sys_close (int handle);
848 +static int sys_mmap (int handle, void *addr);
849 +static int sys_munmap (int mapping);
851 static void syscall_handler (struct intr_frame *);
852 +static void copy_in (void *, const void *, size_t);
854 +static struct lock fs_lock;
859 intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
860 + lock_init (&fs_lock);
863 +/* System call handler. */
865 +syscall_handler (struct intr_frame *f)
867 + typedef int syscall_function (int, int, int);
869 + /* A system call. */
872 + size_t arg_cnt; /* Number of arguments. */
873 + syscall_function *func; /* Implementation. */
876 + /* Table of system calls. */
877 + static const struct syscall syscall_table[] =
879 + {0, (syscall_function *) sys_halt},
880 + {1, (syscall_function *) sys_exit},
881 + {1, (syscall_function *) sys_exec},
882 + {1, (syscall_function *) sys_wait},
883 + {2, (syscall_function *) sys_create},
884 + {1, (syscall_function *) sys_remove},
885 + {1, (syscall_function *) sys_open},
886 + {1, (syscall_function *) sys_filesize},
887 + {3, (syscall_function *) sys_read},
888 + {3, (syscall_function *) sys_write},
889 + {2, (syscall_function *) sys_seek},
890 + {1, (syscall_function *) sys_tell},
891 + {1, (syscall_function *) sys_close},
892 + {2, (syscall_function *) sys_mmap},
893 + {1, (syscall_function *) sys_munmap},
896 + const struct syscall *sc;
900 + /* Get the system call. */
901 + copy_in (&call_nr, f->esp, sizeof call_nr);
902 + if (call_nr >= sizeof syscall_table / sizeof *syscall_table)
904 + sc = syscall_table + call_nr;
906 + /* Get the system call arguments. */
907 + ASSERT (sc->arg_cnt <= sizeof args / sizeof *args);
908 + memset (args, 0, sizeof args);
909 + copy_in (args, (uint32_t *) f->esp + 1, sizeof *args * sc->arg_cnt);
911 + /* Execute the system call,
912 + and set the return value. */
913 + f->eax = sc->func (args[0], args[1], args[2]);
916 +/* Copies SIZE bytes from user address USRC to kernel address
918 + Call thread_exit() if any of the user accesses are invalid. */
920 -syscall_handler (struct intr_frame *f UNUSED)
921 +copy_in (void *dst_, const void *usrc_, size_t size)
923 + uint8_t *dst = dst_;
924 + const uint8_t *usrc = usrc_;
928 + size_t chunk_size = PGSIZE - pg_ofs (usrc);
929 + if (chunk_size > size)
932 + if (!page_lock (usrc, false))
934 + memcpy (dst, usrc, chunk_size);
935 + page_unlock (usrc);
938 + usrc += chunk_size;
939 + size -= chunk_size;
943 +/* Creates a copy of user string US in kernel memory
944 + and returns it as a page that must be freed with
945 + palloc_free_page().
946 + Truncates the string at PGSIZE bytes in size.
947 + Call thread_exit() if any of the user accesses are invalid. */
949 +copy_in_string (const char *us)
955 + ks = palloc_get_page (0);
962 + upage = pg_round_down (us);
963 + if (!page_lock (upage, false))
966 + for (; us < upage + PGSIZE; us++)
968 + ks[length++] = *us;
971 + page_unlock (upage);
974 + else if (length >= PGSIZE)
975 + goto too_long_error;
978 + page_unlock (upage);
982 + page_unlock (upage);
984 + palloc_free_page (ks);
988 +/* Halt system call. */
995 +/* Exit system call. */
997 +sys_exit (int exit_code)
999 + thread_current ()->exit_code = exit_code;
1004 +/* Exec system call. */
1006 +sys_exec (const char *ufile)
1009 + char *kfile = copy_in_string (ufile);
1011 + lock_acquire (&fs_lock);
1012 + tid = process_execute (kfile);
1013 + lock_release (&fs_lock);
1015 + palloc_free_page (kfile);
1020 +/* Wait system call. */
1022 +sys_wait (tid_t child)
1024 + return process_wait (child);
1027 +/* Create system call. */
1029 +sys_create (const char *ufile, unsigned initial_size)
1031 + char *kfile = copy_in_string (ufile);
1034 + lock_acquire (&fs_lock);
1035 + ok = filesys_create (kfile, initial_size);
1036 + lock_release (&fs_lock);
1038 + palloc_free_page (kfile);
1043 +/* Remove system call. */
1045 +sys_remove (const char *ufile)
1047 + char *kfile = copy_in_string (ufile);
1050 + lock_acquire (&fs_lock);
1051 + ok = filesys_remove (kfile);
1052 + lock_release (&fs_lock);
1054 + palloc_free_page (kfile);
1059 +/* A file descriptor, for binding a file handle to a file. */
1060 +struct file_descriptor
1062 + struct list_elem elem; /* List element. */
1063 + struct file *file; /* File. */
1064 + int handle; /* File handle. */
1067 +/* Open system call. */
1069 +sys_open (const char *ufile)
1071 + char *kfile = copy_in_string (ufile);
1072 + struct file_descriptor *fd;
1075 + fd = malloc (sizeof *fd);
1078 + lock_acquire (&fs_lock);
1079 + fd->file = filesys_open (kfile);
1080 + if (fd->file != NULL)
1082 + struct thread *cur = thread_current ();
1083 + handle = fd->handle = cur->next_handle++;
1084 + list_push_front (&cur->fds, &fd->elem);
1088 + lock_release (&fs_lock);
1091 + palloc_free_page (kfile);
1095 +/* Returns the file descriptor associated with the given handle.
1096 + Terminates the process if HANDLE is not associated with an
1098 +static struct file_descriptor *
1099 +lookup_fd (int handle)
1101 + struct thread *cur = thread_current ();
1102 + struct list_elem *e;
1104 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds);
1105 + e = list_next (e))
1107 + struct file_descriptor *fd;
1108 + fd = list_entry (e, struct file_descriptor, elem);
1109 + if (fd->handle == handle)
1116 +/* Filesize system call. */
1118 +sys_filesize (int handle)
1120 + struct file_descriptor *fd = lookup_fd (handle);
1123 + lock_acquire (&fs_lock);
1124 + size = file_length (fd->file);
1125 + lock_release (&fs_lock);
1130 +/* Read system call. */
1132 +sys_read (int handle, void *udst_, unsigned size)
1134 - printf ("system call!\n");
1135 + uint8_t *udst = udst_;
1136 + struct file_descriptor *fd;
1137 + int bytes_read = 0;
1139 + fd = lookup_fd (handle);
1142 + /* How much to read into this page? */
1143 + size_t page_left = PGSIZE - pg_ofs (udst);
1144 + size_t read_amt = size < page_left ? size : page_left;
1147 + /* Read from file into page. */
1148 + if (handle != STDIN_FILENO)
1150 + if (!page_lock (udst, true))
1152 + lock_acquire (&fs_lock);
1153 + retval = file_read (fd->file, udst, read_amt);
1154 + lock_release (&fs_lock);
1155 + page_unlock (udst);
1161 + for (i = 0; i < read_amt; i++)
1163 + char c = input_getc ();
1164 + if (!page_lock (udst, true))
1167 + page_unlock (udst);
1169 + bytes_read = read_amt;
1172 + /* Check success. */
1175 + if (bytes_read == 0)
1179 + bytes_read += retval;
1180 + if (retval != (off_t) read_amt)
1182 + /* Short read, so we're done. */
1191 + return bytes_read;
1194 +/* Write system call. */
1196 +sys_write (int handle, void *usrc_, unsigned size)
1198 + uint8_t *usrc = usrc_;
1199 + struct file_descriptor *fd = NULL;
1200 + int bytes_written = 0;
1202 + /* Lookup up file descriptor. */
1203 + if (handle != STDOUT_FILENO)
1204 + fd = lookup_fd (handle);
1208 + /* How much bytes to write to this page? */
1209 + size_t page_left = PGSIZE - pg_ofs (usrc);
1210 + size_t write_amt = size < page_left ? size : page_left;
1213 + /* Write from page into file. */
1214 + if (!page_lock (usrc, false))
1216 + lock_acquire (&fs_lock);
1217 + if (handle == STDOUT_FILENO)
1219 + putbuf ((char *) usrc, write_amt);
1220 + retval = write_amt;
1223 + retval = file_write (fd->file, usrc, write_amt);
1224 + lock_release (&fs_lock);
1225 + page_unlock (usrc);
1227 + /* Handle return value. */
1230 + if (bytes_written == 0)
1231 + bytes_written = -1;
1234 + bytes_written += retval;
1236 + /* If it was a short write we're done. */
1237 + if (retval != (off_t) write_amt)
1245 + return bytes_written;
1248 +/* Seek system call. */
1250 +sys_seek (int handle, unsigned position)
1252 + struct file_descriptor *fd = lookup_fd (handle);
1254 + lock_acquire (&fs_lock);
1255 + if ((off_t) position >= 0)
1256 + file_seek (fd->file, position);
1257 + lock_release (&fs_lock);
1262 +/* Tell system call. */
1264 +sys_tell (int handle)
1266 + struct file_descriptor *fd = lookup_fd (handle);
1267 + unsigned position;
1269 + lock_acquire (&fs_lock);
1270 + position = file_tell (fd->file);
1271 + lock_release (&fs_lock);
1276 +/* Close system call. */
1278 +sys_close (int handle)
1280 + struct file_descriptor *fd = lookup_fd (handle);
1281 + lock_acquire (&fs_lock);
1282 + file_close (fd->file);
1283 + lock_release (&fs_lock);
1284 + list_remove (&fd->elem);
1289 +/* Binds a mapping id to a region of memory and a file. */
1292 + struct list_elem elem; /* List element. */
1293 + int handle; /* Mapping id. */
1294 + struct file *file; /* File. */
1295 + uint8_t *base; /* Start of memory mapping. */
1296 + size_t page_cnt; /* Number of pages mapped. */
1299 +/* Returns the file descriptor associated with the given handle.
1300 + Terminates the process if HANDLE is not associated with a
1301 + memory mapping. */
1302 +static struct mapping *
1303 +lookup_mapping (int handle)
1305 + struct thread *cur = thread_current ();
1306 + struct list_elem *e;
1308 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1309 + e = list_next (e))
1311 + struct mapping *m = list_entry (e, struct mapping, elem);
1312 + if (m->handle == handle)
1319 +/* Remove mapping M from the virtual address space,
1320 + writing back any pages that have changed. */
1322 +unmap (struct mapping *m)
1324 + list_remove (&m->elem);
1325 + while (m->page_cnt-- > 0)
1327 + page_deallocate (m->base);
1328 + m->base += PGSIZE;
1330 + file_close (m->file);
1334 +/* Mmap system call. */
1336 +sys_mmap (int handle, void *addr)
1338 + struct file_descriptor *fd = lookup_fd (handle);
1339 + struct mapping *m = malloc (sizeof *m);
1343 + if (m == NULL || addr == NULL || pg_ofs (addr) != 0)
1346 + m->handle = thread_current ()->next_handle++;
1347 + lock_acquire (&fs_lock);
1348 + m->file = file_reopen (fd->file);
1349 + lock_release (&fs_lock);
1350 + if (m->file == NULL)
1357 + list_push_front (&thread_current ()->mappings, &m->elem);
1360 + lock_acquire (&fs_lock);
1361 + length = file_length (m->file);
1362 + lock_release (&fs_lock);
1363 + while (length > 0)
1365 + struct page *p = page_allocate ((uint8_t *) addr + offset, false);
1371 + p->private = false;
1372 + p->file = m->file;
1373 + p->file_offset = offset;
1374 + p->file_bytes = length >= PGSIZE ? PGSIZE : length;
1375 + offset += p->file_bytes;
1376 + length -= p->file_bytes;
1383 +/* Munmap system call. */
1385 +sys_munmap (int mapping)
1387 + unmap (lookup_mapping (mapping));
1391 +/* On thread exit, close all open files and unmap all mappings. */
1393 +syscall_exit (void)
1395 + struct thread *cur = thread_current ();
1396 + struct list_elem *e, *next;
1398 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds); e = next)
1400 + struct file_descriptor *fd = list_entry (e, struct file_descriptor, elem);
1401 + next = list_next (e);
1402 + lock_acquire (&fs_lock);
1403 + file_close (fd->file);
1404 + lock_release (&fs_lock);
1408 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1411 + struct mapping *m = list_entry (e, struct mapping, elem);
1412 + next = list_next (e);
1416 Index: src/userprog/syscall.h
1417 diff -u src/userprog/syscall.h~ src/userprog/syscall.h
1418 --- src/userprog/syscall.h~
1419 +++ src/userprog/syscall.h
1421 #define USERPROG_SYSCALL_H
1423 void syscall_init (void);
1424 +void syscall_exit (void);
1426 #endif /* userprog/syscall.h */
1427 Index: src/vm/frame.c
1428 diff -u src/vm/frame.c~ src/vm/frame.c
1432 +#include "vm/frame.h"
1434 +#include "vm/page.h"
1435 +#include "devices/timer.h"
1436 +#include "threads/init.h"
1437 +#include "threads/malloc.h"
1438 +#include "threads/palloc.h"
1439 +#include "threads/synch.h"
1440 +#include "threads/vaddr.h"
1442 +static struct frame *frames;
1443 +static size_t frame_cnt;
1445 +static struct lock scan_lock;
1446 +static size_t hand;
1448 +/* Initialize the frame manager. */
1454 + lock_init (&scan_lock);
1456 + frames = malloc (sizeof *frames * ram_pages);
1457 + if (frames == NULL)
1458 + PANIC ("out of memory allocating page frames");
1460 + while ((base = palloc_get_page (PAL_USER)) != NULL)
1462 + struct frame *f = &frames[frame_cnt++];
1463 + lock_init (&f->lock);
1469 +/* Tries to allocate and lock a frame for PAGE.
1470 + Returns the frame if successful, false on failure. */
1471 +static struct frame *
1472 +try_frame_alloc_and_lock (struct page *page)
1476 + lock_acquire (&scan_lock);
1478 + /* Find a free frame. */
1479 + for (i = 0; i < frame_cnt; i++)
1481 + struct frame *f = &frames[i];
1482 + if (!lock_try_acquire (&f->lock))
1484 + if (f->page == NULL)
1487 + lock_release (&scan_lock);
1490 + lock_release (&f->lock);
1493 + /* No free frame. Find a frame to evict. */
1494 + for (i = 0; i < frame_cnt * 2; i++)
1496 + /* Get a frame. */
1497 + struct frame *f = &frames[hand];
1498 + if (++hand >= frame_cnt)
1501 + if (!lock_try_acquire (&f->lock))
1504 + if (f->page == NULL)
1507 + lock_release (&scan_lock);
1511 + if (page_accessed_recently (f->page))
1513 + lock_release (&f->lock);
1517 + lock_release (&scan_lock);
1519 + /* Evict this frame. */
1520 + if (!page_out (f->page))
1522 + lock_release (&f->lock);
1530 + lock_release (&scan_lock);
1535 +/* Tries really hard to allocate and lock a frame for PAGE.
1536 + Returns the frame if successful, false on failure. */
1538 +frame_alloc_and_lock (struct page *page)
1542 + for (try = 0; try < 3; try++)
1544 + struct frame *f = try_frame_alloc_and_lock (page);
1547 + ASSERT (lock_held_by_current_thread (&f->lock));
1550 + timer_msleep (1000);
1556 +/* Locks P's frame into memory, if it has one.
1557 + Upon return, p->frame will not change until P is unlocked. */
1559 +frame_lock (struct page *p)
1561 + /* A frame can be asynchronously removed, but never inserted. */
1562 + struct frame *f = p->frame;
1565 + lock_acquire (&f->lock);
1566 + if (f != p->frame)
1568 + lock_release (&f->lock);
1569 + ASSERT (p->frame == NULL);
1574 +/* Releases frame F for use by another page.
1575 + F must be locked for use by the current process.
1576 + Any data in F is lost. */
1578 +frame_free (struct frame *f)
1580 + ASSERT (lock_held_by_current_thread (&f->lock));
1583 + lock_release (&f->lock);
1586 +/* Unlocks frame F, allowing it to be evicted.
1587 + F must be locked for use by the current process. */
1589 +frame_unlock (struct frame *f)
1591 + ASSERT (lock_held_by_current_thread (&f->lock));
1592 + lock_release (&f->lock);
1594 Index: src/vm/frame.h
1595 diff -u src/vm/frame.h~ src/vm/frame.h
1602 +#include <stdbool.h>
1603 +#include "threads/synch.h"
1605 +/* A physical frame. */
1608 + struct lock lock; /* Prevent simultaneous access. */
1609 + void *base; /* Kernel virtual base address. */
1610 + struct page *page; /* Mapped process page, if any. */
1613 +void frame_init (void);
1615 +struct frame *frame_alloc_and_lock (struct page *);
1616 +void frame_lock (struct page *);
1618 +void frame_free (struct frame *);
1619 +void frame_unlock (struct frame *);
1621 +#endif /* vm/frame.h */
1622 Index: src/vm/page.c
1623 diff -u src/vm/page.c~ src/vm/page.c
1627 +#include "vm/page.h"
1629 +#include <string.h>
1630 +#include "vm/frame.h"
1631 +#include "vm/swap.h"
1632 +#include "filesys/file.h"
1633 +#include "threads/malloc.h"
1634 +#include "threads/thread.h"
1635 +#include "userprog/pagedir.h"
1636 +#include "threads/vaddr.h"
1638 +/* Maximum size of process stack, in bytes. */
1639 +#define STACK_MAX (1024 * 1024)
1641 +/* Destroys a page, which must be in the current process's
1642 + page table. Used as a callback for hash_destroy(). */
1644 +destroy_page (struct hash_elem *p_, void *aux UNUSED)
1646 + struct page *p = hash_entry (p_, struct page, hash_elem);
1649 + frame_free (p->frame);
1653 +/* Destroys the current process's page table. */
1657 + struct hash *h = thread_current ()->pages;
1659 + hash_destroy (h, destroy_page);
1662 +/* Returns the page containing the given virtual ADDRESS,
1663 + or a null pointer if no such page exists.
1664 + Allocates stack pages as necessary. */
1665 +static struct page *
1666 +page_for_addr (const void *address)
1668 + if (address < PHYS_BASE)
1671 + struct hash_elem *e;
1673 + /* Find existing page. */
1674 + p.addr = (void *) pg_round_down (address);
1675 + e = hash_find (thread_current ()->pages, &p.hash_elem);
1677 + return hash_entry (e, struct page, hash_elem);
1679 + /* No page. Expand stack? */
1680 + if (address >= PHYS_BASE - STACK_MAX
1681 + && address >= thread_current ()->user_esp - 32)
1682 + return page_allocate ((void *) address, false);
1687 +/* Locks a frame for page P and pages it in.
1688 + Returns true if successful, false on failure. */
1690 +do_page_in (struct page *p)
1692 + /* Get a frame for the page. */
1693 + p->frame = frame_alloc_and_lock (p);
1694 + if (p->frame == NULL)
1697 + /* Copy data into the frame. */
1698 + if (p->sector != (disk_sector_t) -1)
1700 + /* Get data from swap. */
1703 + else if (p->file != NULL)
1705 + /* Get data from file. */
1706 + off_t read_bytes = file_read_at (p->file, p->frame->base,
1707 + p->file_bytes, p->file_offset);
1708 + off_t zero_bytes = PGSIZE - read_bytes;
1709 + memset (p->frame->base + read_bytes, 0, zero_bytes);
1710 + if (read_bytes != p->file_bytes)
1711 + printf ("bytes read (%"PROTd") != bytes requested (%"PROTd")\n",
1712 + read_bytes, p->file_bytes);
1716 + /* Provide all-zero page. */
1717 + memset (p->frame->base, 0, PGSIZE);
1723 +/* Faults in the page containing FAULT_ADDR.
1724 + Returns true if successful, false on failure. */
1726 +page_in (void *fault_addr)
1731 + /* Can't handle page faults without a hash table. */
1732 + if (thread_current ()->pages == NULL)
1735 + p = page_for_addr (fault_addr);
1740 + if (p->frame == NULL)
1742 + if (!do_page_in (p))
1745 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1747 + /* Install frame into page table. */
1748 + success = pagedir_set_page (thread_current ()->pagedir, p->addr,
1749 + p->frame->base, !p->read_only);
1751 + /* Release frame. */
1752 + frame_unlock (p->frame);
1758 + P must have a locked frame.
1759 + Return true if successful, false on failure. */
1761 +page_out (struct page *p)
1766 + ASSERT (p->frame != NULL);
1767 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1769 + /* Mark page not present in page table, forcing accesses by the
1770 + process to fault. This must happen before checking the
1771 + dirty bit, to prevent a race with the process dirtying the
1773 + pagedir_clear_page (p->thread->pagedir, p->addr);
1775 + /* Has the frame been modified? */
1776 + dirty = pagedir_is_dirty (p->thread->pagedir, p->addr);
1778 + /* Write frame contents to disk if necessary. */
1779 + if (p->file != NULL)
1784 + ok = swap_out (p);
1786 + ok = file_write_at (p->file, p->frame->base, p->file_bytes,
1787 + p->file_offset) == p->file_bytes;
1793 + ok = swap_out (p);
1796 + //memset (p->frame->base, 0xcc, PGSIZE);
1802 +/* Returns true if page P's data has been accessed recently,
1804 + P must have a frame locked into memory. */
1806 +page_accessed_recently (struct page *p)
1808 + bool was_accessed;
1810 + ASSERT (p->frame != NULL);
1811 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1813 + was_accessed = pagedir_is_accessed (p->thread->pagedir, p->addr);
1815 + pagedir_set_accessed (p->thread->pagedir, p->addr, false);
1816 + return was_accessed;
1819 +/* Adds a mapping for user virtual address VADDR to the page hash
1820 + table. Fails if VADDR is already mapped or if memory
1821 + allocation fails. */
1823 +page_allocate (void *vaddr, bool read_only)
1825 + struct thread *t = thread_current ();
1826 + struct page *p = malloc (sizeof *p);
1829 + p->addr = pg_round_down (vaddr);
1831 + p->read_only = read_only;
1832 + p->private = !read_only;
1836 + p->sector = (disk_sector_t) -1;
1839 + p->file_offset = 0;
1840 + p->file_bytes = 0;
1842 + p->thread = thread_current ();
1844 + if (hash_insert (t->pages, &p->hash_elem) != NULL)
1846 + /* Already mapped. */
1854 +/* Evicts the page containing address VADDR
1855 + and removes it from the page table. */
1857 +page_deallocate (void *vaddr)
1859 + struct page *p = page_for_addr (vaddr);
1860 + ASSERT (p != NULL);
1864 + struct frame *f = p->frame;
1865 + if (p->file && !p->private)
1869 + hash_delete (thread_current ()->pages, &p->hash_elem);
1873 +/* Returns a hash value for the page that E refers to. */
1875 +page_hash (const struct hash_elem *e, void *aux UNUSED)
1877 + const struct page *p = hash_entry (e, struct page, hash_elem);
1878 + return ((uintptr_t) p->addr) >> PGBITS;
1881 +/* Returns true if page A precedes page B. */
1883 +page_less (const struct hash_elem *a_, const struct hash_elem *b_,
1886 + const struct page *a = hash_entry (a_, struct page, hash_elem);
1887 + const struct page *b = hash_entry (b_, struct page, hash_elem);
1889 + return a->addr < b->addr;
1892 +/* Tries to lock the page containing ADDR into physical memory.
1893 + If WILL_WRITE is true, the page must be writeable;
1894 + otherwise it may be read-only.
1895 + Returns true if successful, false on failure. */
1897 +page_lock (const void *addr, bool will_write)
1899 + struct page *p = page_for_addr (addr);
1900 + if (p == NULL || (p->read_only && will_write))
1904 + if (p->frame == NULL)
1905 + return (do_page_in (p)
1906 + && pagedir_set_page (thread_current ()->pagedir, p->addr,
1907 + p->frame->base, !p->read_only));
1912 +/* Unlocks a page locked with page_lock(). */
1914 +page_unlock (const void *addr)
1916 + struct page *p = page_for_addr (addr);
1917 + ASSERT (p != NULL);
1918 + frame_unlock (p->frame);
1920 Index: src/vm/page.h
1921 diff -u src/vm/page.h~ src/vm/page.h
1929 +#include "devices/disk.h"
1930 +#include "filesys/off_t.h"
1931 +#include "threads/synch.h"
1933 +/* Virtual page. */
1936 + /* Immutable members. */
1937 + void *addr; /* User virtual address. */
1938 + bool read_only; /* Read-only page? */
1939 + struct thread *thread; /* Owning thread. */
1941 + /* Accessed only in owning process context. */
1942 + struct hash_elem hash_elem; /* struct thread `pages' hash element. */
1944 + /* Set only in owning process context with frame->frame_lock held.
1945 + Cleared only with scan_lock and frame->frame_lock held. */
1946 + struct frame *frame; /* Page frame. */
1948 + /* Swap information, protected by frame->frame_lock. */
1949 + disk_sector_t sector; /* Starting sector of swap area, or -1. */
1951 + /* Memory-mapped file information, protected by frame->frame_lock. */
1952 + bool private; /* False to write back to file,
1953 + true to write back to swap. */
1954 + struct file *file; /* File. */
1955 + off_t file_offset; /* Offset in file. */
1956 + off_t file_bytes; /* Bytes to read/write, 1...PGSIZE. */
1959 +void page_exit (void);
1961 +struct page *page_allocate (void *, bool read_only);
1962 +void page_deallocate (void *vaddr);
1964 +bool page_in (void *fault_addr);
1965 +bool page_out (struct page *);
1966 +bool page_accessed_recently (struct page *);
1968 +bool page_lock (const void *, bool will_write);
1969 +void page_unlock (const void *);
1971 +hash_hash_func page_hash;
1972 +hash_less_func page_less;
1974 +#endif /* vm/page.h */
1975 Index: src/vm/swap.c
1976 diff -u src/vm/swap.c~ src/vm/swap.c
1980 +#include "vm/swap.h"
1981 +#include <bitmap.h>
1984 +#include "vm/frame.h"
1985 +#include "vm/page.h"
1986 +#include "devices/disk.h"
1987 +#include "threads/synch.h"
1988 +#include "threads/vaddr.h"
1990 +/* The swap disk. */
1991 +static struct disk *swap_disk;
1993 +/* Used swap pages. */
1994 +static struct bitmap *swap_bitmap;
1996 +/* Protects swap_bitmap. */
1997 +static struct lock swap_lock;
1999 +/* Number of sectors per page. */
2000 +#define PAGE_SECTORS (PGSIZE / DISK_SECTOR_SIZE)
2002 +/* Sets up swap. */
2006 + swap_disk = disk_get (1, 1);
2007 + if (swap_disk == NULL)
2009 + printf ("no swap disk--swap disabled\n");
2010 + swap_bitmap = bitmap_create (0);
2013 + swap_bitmap = bitmap_create (disk_size (swap_disk) / PAGE_SECTORS);
2014 + if (swap_bitmap == NULL)
2015 + PANIC ("couldn't create swap bitmap");
2016 + lock_init (&swap_lock);
2019 +/* Swaps in page P, which must have a locked frame
2020 + (and be swapped out). */
2022 +swap_in (struct page *p)
2026 + ASSERT (p->frame != NULL);
2027 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
2028 + ASSERT (p->sector != (disk_sector_t) -1);
2030 + for (i = 0; i < PAGE_SECTORS; i++)
2031 + disk_read (swap_disk, p->sector + i,
2032 + p->frame->base + i * DISK_SECTOR_SIZE);
2033 + bitmap_reset (swap_bitmap, p->sector / PAGE_SECTORS);
2034 + p->sector = (disk_sector_t) -1;
2037 +/* Swaps out page P, which must have a locked frame. */
2039 +swap_out (struct page *p)
2044 + ASSERT (p->frame != NULL);
2045 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
2047 + lock_acquire (&swap_lock);
2048 + slot = bitmap_scan_and_flip (swap_bitmap, 0, 1, false);
2049 + lock_release (&swap_lock);
2050 + if (slot == BITMAP_ERROR)
2053 + p->sector = slot * PAGE_SECTORS;
2054 + for (i = 0; i < PAGE_SECTORS; i++)
2055 + disk_write (swap_disk, p->sector + i,
2056 + p->frame->base + i * DISK_SECTOR_SIZE);
2058 + p->private = false;
2060 + p->file_offset = 0;
2061 + p->file_bytes = 0;
2065 Index: src/vm/swap.h
2066 diff -u src/vm/swap.h~ src/vm/swap.h
2071 +#define VM_SWAP_H 1
2073 +#include <stdbool.h>
2076 +void swap_init (void);
2077 +void swap_in (struct page *);
2078 +bool swap_out (struct page *);
2080 +#endif /* vm/swap.h */