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 @@ -288,10 +289,11 @@ thread_tid (void)
181 ASSERT (!intr_context ());
188 /* Remove thread from all threads list, set our status to dying,
189 @@ -406,17 +410,28 @@ is_thread (struct thread *t)
190 /* Does basic initialization of T as a blocked thread named
193 -init_thread (struct thread *t, const char *name, int priority)
194 +init_thread (struct thread *t, const char *name, int priority, tid_t tid)
197 ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
198 ASSERT (name != NULL);
200 memset (t, 0, sizeof *t);
202 t->status = THREAD_BLOCKED;
203 strlcpy (t->name, name, sizeof t->name);
204 t->stack = (uint8_t *) t + PGSIZE;
205 t->priority = priority;
207 + t->wait_status = NULL;
208 + list_init (&t->children);
209 + sema_init (&t->timer_sema, 0);
212 + t->bin_file = NULL;
213 + list_init (&t->fds);
214 + list_init (&t->mappings);
215 + t->next_handle = 2;
216 t->magic = THREAD_MAGIC;
219 Index: src/threads/thread.h
220 diff -u src/threads/thread.h~ src/threads/thread.h
221 --- src/threads/thread.h~
222 +++ src/threads/thread.h
224 #define THREADS_THREAD_H
230 +#include "threads/synch.h"
232 /* States in a thread's life cycle. */
234 @@ -89,18 +91,49 @@ struct thread
235 uint8_t *stack; /* Saved stack pointer. */
236 int priority; /* Priority. */
238 + /* Owned by process.c. */
239 + int exit_code; /* Exit code. */
240 + struct wait_status *wait_status; /* This process's completion status. */
241 + struct list children; /* Completion status of children. */
243 /* Shared between thread.c and synch.c. */
244 struct list_elem elem; /* List element. */
248 + int64_t wakeup_time; /* Time to wake this thread up. */
249 + struct list_elem timer_elem; /* Element in timer_wait_list. */
250 + struct semaphore timer_sema; /* Semaphore. */
252 /* Owned by userprog/process.c. */
253 uint32_t *pagedir; /* Page directory. */
255 + struct hash *pages; /* Page table. */
256 + struct file *bin_file; /* The binary executable. */
258 + /* Owned by syscall.c. */
259 + struct list fds; /* List of file descriptors. */
260 + struct list mappings; /* Memory-mapped files. */
261 + int next_handle; /* Next handle value. */
262 + void *user_esp; /* User's stack pointer. */
264 /* Owned by thread.c. */
265 unsigned magic; /* Detects stack overflow. */
268 +/* Tracks the completion of a process.
269 + Reference held by both the parent, in its `children' list,
270 + and by the child, in its `wait_status' pointer. */
273 + struct list_elem elem; /* `children' list element. */
274 + struct lock lock; /* Protects ref_cnt. */
275 + int ref_cnt; /* 2=child and parent both alive,
276 + 1=either child or parent alive,
277 + 0=child and parent both dead. */
278 + tid_t tid; /* Child thread id. */
279 + int exit_code; /* Child exit code, if dead. */
280 + struct semaphore dead; /* 1=child alive, 0=child dead. */
283 /* If false (default), use round-robin scheduler.
284 If true, use multi-level feedback queue scheduler.
285 Controlled by kernel command-line options "-o mlfqs".
286 Index: src/userprog/exception.c
287 diff -u src/userprog/exception.c~ src/userprog/exception.c
288 --- src/userprog/exception.c~
289 +++ src/userprog/exception.c
291 #include "userprog/gdt.h"
292 #include "threads/interrupt.h"
293 #include "threads/thread.h"
294 +#include "vm/page.h"
296 /* Number of page faults processed. */
297 static long long page_fault_cnt;
298 @@ -148,9 +149,14 @@ page_fault (struct intr_frame *f)
299 write = (f->error_code & PF_W) != 0;
300 user = (f->error_code & PF_U) != 0;
302 - /* To implement virtual memory, delete the rest of the function
303 - body, and replace it with code that brings in the page to
304 - which fault_addr refers. */
305 + /* Allow the pager to try to handle it. */
306 + if (user && not_present)
308 + if (!page_in (fault_addr))
313 printf ("Page fault at %p: %s error %s page in %s context.\n",
315 not_present ? "not present" : "rights violation",
316 Index: src/userprog/pagedir.c
317 diff -u src/userprog/pagedir.c~ src/userprog/pagedir.c
318 --- src/userprog/pagedir.c~
319 +++ src/userprog/pagedir.c
320 @@ -35,15 +35,7 @@ pagedir_destroy (uint32_t *pd)
321 ASSERT (pd != base_page_dir);
322 for (pde = pd; pde < pd + pd_no (PHYS_BASE); pde++)
325 - uint32_t *pt = pde_get_pt (*pde);
328 - for (pte = pt; pte < pt + PGSIZE / sizeof *pte; pte++)
330 - palloc_free_page (pte_get_page (*pte));
331 - palloc_free_page (pt);
333 + palloc_free_page (pde_get_pt (*pde));
334 palloc_free_page (pd);
337 Index: src/userprog/process.c
338 diff -u src/userprog/process.c~ src/userprog/process.c
339 --- src/userprog/process.c~
340 +++ src/userprog/process.c
342 #include "threads/flags.h"
343 #include "threads/init.h"
344 #include "threads/interrupt.h"
345 +#include "threads/malloc.h"
346 #include "threads/palloc.h"
347 #include "threads/thread.h"
348 #include "threads/vaddr.h"
349 +#include "vm/page.h"
350 +#include "vm/frame.h"
352 static thread_func start_process NO_RETURN;
353 -static bool load (const char *cmdline, void (**eip) (void), void **esp);
354 +static bool load (const char *cmd_line, void (**eip) (void), void **esp);
356 +/* Data structure shared between process_execute() in the
357 + invoking thread and start_process() in the newly invoked
361 + const char *file_name; /* Program to load. */
362 + struct semaphore load_done; /* "Up"ed when loading complete. */
363 + struct wait_status *wait_status; /* Child process. */
364 + bool success; /* Program successfully loaded? */
367 /* Starts a new thread running a user program loaded from
368 FILE_NAME. The new thread may be scheduled (and may even exit)
369 @@ -28,29 +42,37 @@ static bool load (const char *cmdline, v
371 process_execute (const char *file_name)
374 + struct exec_info exec;
375 + char thread_name[16];
379 - /* Make a copy of FILE_NAME.
380 - Otherwise there's a race between the caller and load(). */
381 - fn_copy = palloc_get_page (0);
382 - if (fn_copy == NULL)
384 - strlcpy (fn_copy, file_name, PGSIZE);
385 + /* Initialize exec_info. */
386 + exec.file_name = file_name;
387 + sema_init (&exec.load_done, 0);
389 /* Create a new thread to execute FILE_NAME. */
390 - tid = thread_create (file_name, PRI_DEFAULT, start_process, fn_copy);
391 - if (tid == TID_ERROR)
392 - palloc_free_page (fn_copy);
393 + strlcpy (thread_name, file_name, sizeof thread_name);
394 + strtok_r (thread_name, " ", &save_ptr);
395 + tid = thread_create (thread_name, PRI_DEFAULT, start_process, &exec);
396 + if (tid != TID_ERROR)
398 + sema_down (&exec.load_done);
400 + list_push_back (&thread_current ()->children, &exec.wait_status->elem);
408 /* A thread function that loads a user process and starts it
411 -start_process (void *file_name_)
412 +start_process (void *exec_)
414 - char *file_name = file_name_;
415 + struct exec_info *exec = exec_;
416 struct intr_frame if_;
419 @@ -59,10 +81,28 @@ start_process (void *file_name_)
420 if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
422 if_.eflags = FLAG_IF | FLAG_MBS;
423 - success = load (file_name, &if_.eip, &if_.esp);
424 + success = load (exec->file_name, &if_.eip, &if_.esp);
426 + /* Allocate wait_status. */
429 + exec->wait_status = thread_current ()->wait_status
430 + = malloc (sizeof *exec->wait_status);
431 + success = exec->wait_status != NULL;
434 - /* If load failed, quit. */
435 - palloc_free_page (file_name);
436 + /* Initialize wait_status. */
439 + lock_init (&exec->wait_status->lock);
440 + exec->wait_status->ref_cnt = 2;
441 + exec->wait_status->tid = thread_current ()->tid;
442 + sema_init (&exec->wait_status->dead, 0);
445 + /* Notify parent thread and clean up. */
446 + exec->success = success;
447 + sema_up (&exec->load_done);
451 @@ -76,18 +116,47 @@ start_process (void *file_name_)
455 +/* Releases one reference to CS and, if it is now unreferenced,
458 +release_child (struct wait_status *cs)
462 + lock_acquire (&cs->lock);
463 + new_ref_cnt = --cs->ref_cnt;
464 + lock_release (&cs->lock);
466 + if (new_ref_cnt == 0)
470 /* Waits for thread TID to die and returns its exit status. If
471 it was terminated by the kernel (i.e. killed due to an
472 exception), returns -1. If TID is invalid or if it was not a
473 child of the calling process, or if process_wait() has already
474 been successfully called for the given TID, returns -1
475 - immediately, without waiting.
477 - This function will be implemented in problem 2-2. For now, it
479 + immediately, without waiting. */
481 -process_wait (tid_t child_tid UNUSED)
482 +process_wait (tid_t child_tid)
484 + struct thread *cur = thread_current ();
485 + struct list_elem *e;
487 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
490 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
491 + if (cs->tid == child_tid)
495 + sema_down (&cs->dead);
496 + exit_code = cs->exit_code;
497 + release_child (cs);
504 @@ -96,8 +165,35 @@ void
507 struct thread *cur = thread_current ();
508 + struct list_elem *e, *next;
511 + printf ("%s: exit(%d)\n", cur->name, cur->exit_code);
513 + /* Notify parent that we're dead. */
514 + if (cur->wait_status != NULL)
516 + struct wait_status *cs = cur->wait_status;
517 + cs->exit_code = cur->exit_code;
518 + sema_up (&cs->dead);
519 + release_child (cs);
522 + /* Free entries of children list. */
523 + for (e = list_begin (&cur->children); e != list_end (&cur->children);
526 + struct wait_status *cs = list_entry (e, struct wait_status, elem);
527 + next = list_remove (e);
528 + release_child (cs);
531 + /* Destroy the page hash table. */
534 + /* Close executable (and allow writes). */
535 + file_close (cur->bin_file);
537 /* Destroy the current process's page directory and switch back
538 to the kernel-only page directory. */
540 @@ -194,7 +290,7 @@ struct Elf32_Phdr
541 #define PF_W 2 /* Writable. */
542 #define PF_R 4 /* Readable. */
544 -static bool setup_stack (void **esp);
545 +static bool setup_stack (const char *cmd_line, void **esp);
546 static bool validate_segment (const struct Elf32_Phdr *, struct file *);
547 static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
548 uint32_t read_bytes, uint32_t zero_bytes,
549 @@ -205,13 +301,15 @@ static bool load_segment (struct file *f
550 and its initial stack pointer into *ESP.
551 Returns true if successful, false otherwise. */
553 -load (const char *file_name, void (**eip) (void), void **esp)
554 +load (const char *cmd_line, void (**eip) (void), void **esp)
556 struct thread *t = thread_current ();
557 + char file_name[NAME_MAX + 2];
558 struct Elf32_Ehdr ehdr;
559 struct file *file = NULL;
561 bool success = false;
565 /* Allocate and activate page directory. */
566 @@ -220,13 +318,28 @@ load (const char *file_name, void (**eip)
570 + /* Create page hash table. */
571 + t->pages = malloc (sizeof *t->pages);
572 + if (t->pages == NULL)
574 + hash_init (t->pages, page_hash, page_less, NULL);
576 + /* Extract file_name from command line. */
577 + while (*cmd_line == ' ')
579 + strlcpy (file_name, cmd_line, sizeof file_name);
580 + cp = strchr (file_name, ' ');
584 /* Open executable file. */
585 - file = filesys_open (file_name);
586 + t->bin_file = file = filesys_open (file_name);
589 printf ("load: %s: open failed\n", file_name);
592 + file_deny_write (t->bin_file);
594 /* Read and verify executable header. */
595 if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
596 @@ -301,7 +414,7 @@ load (const char *file_name, void (**eip)
600 - if (!setup_stack (esp))
601 + if (!setup_stack (cmd_line, esp))
605 @@ -311,14 +424,11 @@ load (const char *file_name, void (**eip)
608 /* We arrive here whether the load is successful or not. */
613 /* load() helpers. */
615 -static bool install_page (void *upage, void *kpage, bool writable);
617 /* Checks whether PHDR describes a valid, loadable segment in
618 FILE and returns true if so, false otherwise. */
620 @@ -387,79 +497,127 @@ load_segment (struct file *file, off_t o
621 ASSERT (pg_ofs (upage) == 0);
622 ASSERT (ofs % PGSIZE == 0);
624 - file_seek (file, ofs);
625 while (read_bytes > 0 || zero_bytes > 0)
627 - /* Calculate how to fill this page.
628 - We will read PAGE_READ_BYTES bytes from FILE
629 - and zero the final PAGE_ZERO_BYTES bytes. */
630 size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
631 size_t page_zero_bytes = PGSIZE - page_read_bytes;
633 - /* Get a page of memory. */
634 - uint8_t *kpage = palloc_get_page (PAL_USER);
636 + struct page *p = page_allocate (upage, !writable);
640 - /* Load this page. */
641 - if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
643 - palloc_free_page (kpage);
646 - memset (kpage + page_read_bytes, 0, page_zero_bytes);
648 - /* Add the page to the process's address space. */
649 - if (!install_page (upage, kpage, writable))
650 + if (page_read_bytes > 0)
652 - palloc_free_page (kpage);
655 + p->file_offset = ofs;
656 + p->file_bytes = page_read_bytes;
660 read_bytes -= page_read_bytes;
661 zero_bytes -= page_zero_bytes;
662 + ofs += page_read_bytes;
668 -/* Create a minimal stack by mapping a zeroed page at the top of
669 - user virtual memory. */
670 +/* Reverse the order of the ARGC pointers to char in ARGV. */
672 +reverse (int argc, char **argv)
674 + for (; argc > 1; argc -= 2, argv++)
676 + char *tmp = argv[0];
677 + argv[0] = argv[argc - 1];
678 + argv[argc - 1] = tmp;
682 +/* Pushes the SIZE bytes in BUF onto the stack in KPAGE, whose
683 + page-relative stack pointer is *OFS, and then adjusts *OFS
684 + appropriately. The bytes pushed are rounded to a 32-bit
687 + If successful, returns a pointer to the newly pushed object.
688 + On failure, returns a null pointer. */
690 +push (uint8_t *kpage, size_t *ofs, const void *buf, size_t size)
692 + size_t padsize = ROUND_UP (size, sizeof (uint32_t));
693 + if (*ofs < padsize)
697 + memcpy (kpage + *ofs + (padsize - size), buf, size);
698 + return kpage + *ofs + (padsize - size);
701 +/* Sets up command line arguments in KPAGE, which will be mapped
702 + to UPAGE in user space. The command line arguments are taken
703 + from CMD_LINE, separated by spaces. Sets *ESP to the initial
704 + stack pointer for the process. */
706 -setup_stack (void **esp)
707 +init_cmd_line (uint8_t *kpage, uint8_t *upage, const char *cmd_line,
711 - bool success = false;
712 + size_t ofs = PGSIZE;
713 + char *const null = NULL;
714 + char *cmd_line_copy;
715 + char *karg, *saveptr;
719 + /* Push command line string. */
720 + cmd_line_copy = push (kpage, &ofs, cmd_line, strlen (cmd_line) + 1);
721 + if (cmd_line_copy == NULL)
724 + if (push (kpage, &ofs, &null, sizeof null) == NULL)
727 - kpage = palloc_get_page (PAL_USER | PAL_ZERO);
729 + /* Parse command line into arguments
730 + and push them in reverse order. */
732 + for (karg = strtok_r (cmd_line_copy, " ", &saveptr); karg != NULL;
733 + karg = strtok_r (NULL, " ", &saveptr))
735 - success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
739 - palloc_free_page (kpage);
740 + void *uarg = upage + (karg - (char *) kpage);
741 + if (push (kpage, &ofs, &uarg, sizeof uarg) == NULL)
747 + /* Reverse the order of the command line arguments. */
748 + argv = (char **) (upage + ofs);
749 + reverse (argc, (char **) (kpage + ofs));
751 + /* Push argv, argc, "return address". */
752 + if (push (kpage, &ofs, &argv, sizeof argv) == NULL
753 + || push (kpage, &ofs, &argc, sizeof argc) == NULL
754 + || push (kpage, &ofs, &null, sizeof null) == NULL)
757 + /* Set initial stack pointer. */
758 + *esp = upage + ofs;
762 -/* Adds a mapping from user virtual address UPAGE to kernel
763 - virtual address KPAGE to the page table.
764 - If WRITABLE is true, the user process may modify the page;
765 - otherwise, it is read-only.
766 - UPAGE must not already be mapped.
767 - KPAGE should probably be a page obtained from the user pool
768 - with palloc_get_page().
769 - Returns true on success, false if UPAGE is already mapped or
770 - if memory allocation fails. */
771 +/* Create a minimal stack for T by mapping a page at the
772 + top of user virtual memory. Fills in the page using CMD_LINE
773 + and sets *ESP to the stack pointer. */
775 -install_page (void *upage, void *kpage, bool writable)
776 +setup_stack (const char *cmd_line, void **esp)
778 - struct thread *t = thread_current ();
780 - /* Verify that there's not already a page at that virtual
781 - address, then map our page there. */
782 - return (pagedir_get_page (t->pagedir, upage) == NULL
783 - && pagedir_set_page (t->pagedir, upage, kpage, writable));
784 + struct page *page = page_allocate (((uint8_t *) PHYS_BASE) - PGSIZE, false);
787 + page->frame = frame_alloc_and_lock (page);
788 + if (page->frame != NULL)
791 + page->read_only = false;
792 + page->private = false;
793 + ok = init_cmd_line (page->frame->base, page->addr, cmd_line, esp);
794 + frame_unlock (page->frame);
800 Index: src/userprog/syscall.c
801 diff -u src/userprog/syscall.c~ src/userprog/syscall.c
802 --- src/userprog/syscall.c~
803 +++ src/userprog/syscall.c
805 #include "userprog/syscall.h"
808 #include <syscall-nr.h>
809 +#include "userprog/process.h"
810 +#include "userprog/pagedir.h"
811 +#include "devices/input.h"
812 +#include "filesys/directory.h"
813 +#include "filesys/filesys.h"
814 +#include "filesys/file.h"
815 +#include "threads/init.h"
816 #include "threads/interrupt.h"
817 +#include "threads/malloc.h"
818 +#include "threads/palloc.h"
819 #include "threads/thread.h"
821 +#include "threads/vaddr.h"
822 +#include "vm/page.h"
825 +static int sys_halt (void);
826 +static int sys_exit (int status);
827 +static int sys_exec (const char *ufile);
828 +static int sys_wait (tid_t);
829 +static int sys_create (const char *ufile, unsigned initial_size);
830 +static int sys_remove (const char *ufile);
831 +static int sys_open (const char *ufile);
832 +static int sys_filesize (int handle);
833 +static int sys_read (int handle, void *udst_, unsigned size);
834 +static int sys_write (int handle, void *usrc_, unsigned size);
835 +static int sys_seek (int handle, unsigned position);
836 +static int sys_tell (int handle);
837 +static int sys_close (int handle);
838 +static int sys_mmap (int handle, void *addr);
839 +static int sys_munmap (int mapping);
841 static void syscall_handler (struct intr_frame *);
842 +static void copy_in (void *, const void *, size_t);
844 +static struct lock fs_lock;
849 intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
850 + lock_init (&fs_lock);
853 +/* System call handler. */
855 +syscall_handler (struct intr_frame *f)
857 + typedef int syscall_function (int, int, int);
859 + /* A system call. */
862 + size_t arg_cnt; /* Number of arguments. */
863 + syscall_function *func; /* Implementation. */
866 + /* Table of system calls. */
867 + static const struct syscall syscall_table[] =
869 + {0, (syscall_function *) sys_halt},
870 + {1, (syscall_function *) sys_exit},
871 + {1, (syscall_function *) sys_exec},
872 + {1, (syscall_function *) sys_wait},
873 + {2, (syscall_function *) sys_create},
874 + {1, (syscall_function *) sys_remove},
875 + {1, (syscall_function *) sys_open},
876 + {1, (syscall_function *) sys_filesize},
877 + {3, (syscall_function *) sys_read},
878 + {3, (syscall_function *) sys_write},
879 + {2, (syscall_function *) sys_seek},
880 + {1, (syscall_function *) sys_tell},
881 + {1, (syscall_function *) sys_close},
882 + {2, (syscall_function *) sys_mmap},
883 + {1, (syscall_function *) sys_munmap},
886 + const struct syscall *sc;
890 + /* Get the system call. */
891 + copy_in (&call_nr, f->esp, sizeof call_nr);
892 + if (call_nr >= sizeof syscall_table / sizeof *syscall_table)
894 + sc = syscall_table + call_nr;
896 + /* Get the system call arguments. */
897 + ASSERT (sc->arg_cnt <= sizeof args / sizeof *args);
898 + memset (args, 0, sizeof args);
899 + copy_in (args, (uint32_t *) f->esp + 1, sizeof *args * sc->arg_cnt);
901 + /* Execute the system call,
902 + and set the return value. */
903 + f->eax = sc->func (args[0], args[1], args[2]);
906 +/* Copies SIZE bytes from user address USRC to kernel address
908 + Call thread_exit() if any of the user accesses are invalid. */
910 -syscall_handler (struct intr_frame *f UNUSED)
911 +copy_in (void *dst_, const void *usrc_, size_t size)
913 + uint8_t *dst = dst_;
914 + const uint8_t *usrc = usrc_;
918 + size_t chunk_size = PGSIZE - pg_ofs (usrc);
919 + if (chunk_size > size)
922 + if (!page_lock (usrc, false))
924 + memcpy (dst, usrc, chunk_size);
925 + page_unlock (usrc);
928 + usrc += chunk_size;
929 + size -= chunk_size;
933 +/* Creates a copy of user string US in kernel memory
934 + and returns it as a page that must be freed with
935 + palloc_free_page().
936 + Truncates the string at PGSIZE bytes in size.
937 + Call thread_exit() if any of the user accesses are invalid. */
939 +copy_in_string (const char *us)
945 + ks = palloc_get_page (0);
952 + upage = pg_round_down (us);
953 + if (!page_lock (upage, false))
956 + for (; us < upage + PGSIZE; us++)
958 + ks[length++] = *us;
961 + page_unlock (upage);
964 + else if (length >= PGSIZE)
965 + goto too_long_error;
968 + page_unlock (upage);
972 + page_unlock (upage);
974 + palloc_free_page (ks);
978 +/* Halt system call. */
985 +/* Exit system call. */
987 +sys_exit (int exit_code)
989 + thread_current ()->exit_code = exit_code;
994 +/* Exec system call. */
996 +sys_exec (const char *ufile)
999 + char *kfile = copy_in_string (ufile);
1001 + lock_acquire (&fs_lock);
1002 + tid = process_execute (kfile);
1003 + lock_release (&fs_lock);
1005 + palloc_free_page (kfile);
1010 +/* Wait system call. */
1012 +sys_wait (tid_t child)
1014 + return process_wait (child);
1017 +/* Create system call. */
1019 +sys_create (const char *ufile, unsigned initial_size)
1021 + char *kfile = copy_in_string (ufile);
1024 + lock_acquire (&fs_lock);
1025 + ok = filesys_create (kfile, initial_size);
1026 + lock_release (&fs_lock);
1028 + palloc_free_page (kfile);
1033 +/* Remove system call. */
1035 +sys_remove (const char *ufile)
1037 + char *kfile = copy_in_string (ufile);
1040 + lock_acquire (&fs_lock);
1041 + ok = filesys_remove (kfile);
1042 + lock_release (&fs_lock);
1044 + palloc_free_page (kfile);
1049 +/* A file descriptor, for binding a file handle to a file. */
1050 +struct file_descriptor
1052 + struct list_elem elem; /* List element. */
1053 + struct file *file; /* File. */
1054 + int handle; /* File handle. */
1057 +/* Open system call. */
1059 +sys_open (const char *ufile)
1061 + char *kfile = copy_in_string (ufile);
1062 + struct file_descriptor *fd;
1065 + fd = malloc (sizeof *fd);
1068 + lock_acquire (&fs_lock);
1069 + fd->file = filesys_open (kfile);
1070 + if (fd->file != NULL)
1072 + struct thread *cur = thread_current ();
1073 + handle = fd->handle = cur->next_handle++;
1074 + list_push_front (&cur->fds, &fd->elem);
1078 + lock_release (&fs_lock);
1081 + palloc_free_page (kfile);
1085 +/* Returns the file descriptor associated with the given handle.
1086 + Terminates the process if HANDLE is not associated with an
1088 +static struct file_descriptor *
1089 +lookup_fd (int handle)
1091 + struct thread *cur = thread_current ();
1092 + struct list_elem *e;
1094 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds);
1095 + e = list_next (e))
1097 + struct file_descriptor *fd;
1098 + fd = list_entry (e, struct file_descriptor, elem);
1099 + if (fd->handle == handle)
1106 +/* Filesize system call. */
1108 +sys_filesize (int handle)
1110 + struct file_descriptor *fd = lookup_fd (handle);
1113 + lock_acquire (&fs_lock);
1114 + size = file_length (fd->file);
1115 + lock_release (&fs_lock);
1120 +/* Read system call. */
1122 +sys_read (int handle, void *udst_, unsigned size)
1124 - printf ("system call!\n");
1125 + uint8_t *udst = udst_;
1126 + struct file_descriptor *fd;
1127 + int bytes_read = 0;
1129 + fd = lookup_fd (handle);
1132 + /* How much to read into this page? */
1133 + size_t page_left = PGSIZE - pg_ofs (udst);
1134 + size_t read_amt = size < page_left ? size : page_left;
1137 + /* Read from file into page. */
1138 + if (handle != STDIN_FILENO)
1140 + if (!page_lock (udst, true))
1142 + lock_acquire (&fs_lock);
1143 + retval = file_read (fd->file, udst, read_amt);
1144 + lock_release (&fs_lock);
1145 + page_unlock (udst);
1151 + for (i = 0; i < read_amt; i++)
1153 + char c = input_getc ();
1154 + if (!page_lock (udst, true))
1157 + page_unlock (udst);
1159 + bytes_read = read_amt;
1162 + /* Check success. */
1165 + if (bytes_read == 0)
1169 + bytes_read += retval;
1170 + if (retval != (off_t) read_amt)
1172 + /* Short read, so we're done. */
1181 + return bytes_read;
1184 +/* Write system call. */
1186 +sys_write (int handle, void *usrc_, unsigned size)
1188 + uint8_t *usrc = usrc_;
1189 + struct file_descriptor *fd = NULL;
1190 + int bytes_written = 0;
1192 + /* Lookup up file descriptor. */
1193 + if (handle != STDOUT_FILENO)
1194 + fd = lookup_fd (handle);
1198 + /* How much bytes to write to this page? */
1199 + size_t page_left = PGSIZE - pg_ofs (usrc);
1200 + size_t write_amt = size < page_left ? size : page_left;
1203 + /* Write from page into file. */
1204 + if (!page_lock (usrc, false))
1206 + lock_acquire (&fs_lock);
1207 + if (handle == STDOUT_FILENO)
1209 + putbuf ((char *) usrc, write_amt);
1210 + retval = write_amt;
1213 + retval = file_write (fd->file, usrc, write_amt);
1214 + lock_release (&fs_lock);
1215 + page_unlock (usrc);
1217 + /* Handle return value. */
1220 + if (bytes_written == 0)
1221 + bytes_written = -1;
1224 + bytes_written += retval;
1226 + /* If it was a short write we're done. */
1227 + if (retval != (off_t) write_amt)
1235 + return bytes_written;
1238 +/* Seek system call. */
1240 +sys_seek (int handle, unsigned position)
1242 + struct file_descriptor *fd = lookup_fd (handle);
1244 + lock_acquire (&fs_lock);
1245 + if ((off_t) position >= 0)
1246 + file_seek (fd->file, position);
1247 + lock_release (&fs_lock);
1252 +/* Tell system call. */
1254 +sys_tell (int handle)
1256 + struct file_descriptor *fd = lookup_fd (handle);
1257 + unsigned position;
1259 + lock_acquire (&fs_lock);
1260 + position = file_tell (fd->file);
1261 + lock_release (&fs_lock);
1266 +/* Close system call. */
1268 +sys_close (int handle)
1270 + struct file_descriptor *fd = lookup_fd (handle);
1271 + lock_acquire (&fs_lock);
1272 + file_close (fd->file);
1273 + lock_release (&fs_lock);
1274 + list_remove (&fd->elem);
1279 +/* Binds a mapping id to a region of memory and a file. */
1282 + struct list_elem elem; /* List element. */
1283 + int handle; /* Mapping id. */
1284 + struct file *file; /* File. */
1285 + uint8_t *base; /* Start of memory mapping. */
1286 + size_t page_cnt; /* Number of pages mapped. */
1289 +/* Returns the file descriptor associated with the given handle.
1290 + Terminates the process if HANDLE is not associated with a
1291 + memory mapping. */
1292 +static struct mapping *
1293 +lookup_mapping (int handle)
1295 + struct thread *cur = thread_current ();
1296 + struct list_elem *e;
1298 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1299 + e = list_next (e))
1301 + struct mapping *m = list_entry (e, struct mapping, elem);
1302 + if (m->handle == handle)
1309 +/* Remove mapping M from the virtual address space,
1310 + writing back any pages that have changed. */
1312 +unmap (struct mapping *m)
1314 + list_remove (&m->elem);
1315 + while (m->page_cnt-- > 0)
1317 + page_deallocate (m->base);
1318 + m->base += PGSIZE;
1320 + file_close (m->file);
1324 +/* Mmap system call. */
1326 +sys_mmap (int handle, void *addr)
1328 + struct file_descriptor *fd = lookup_fd (handle);
1329 + struct mapping *m = malloc (sizeof *m);
1333 + if (m == NULL || addr == NULL || pg_ofs (addr) != 0)
1336 + m->handle = thread_current ()->next_handle++;
1337 + lock_acquire (&fs_lock);
1338 + m->file = file_reopen (fd->file);
1339 + lock_release (&fs_lock);
1340 + if (m->file == NULL)
1347 + list_push_front (&thread_current ()->mappings, &m->elem);
1350 + lock_acquire (&fs_lock);
1351 + length = file_length (m->file);
1352 + lock_release (&fs_lock);
1353 + while (length > 0)
1355 + struct page *p = page_allocate ((uint8_t *) addr + offset, false);
1361 + p->private = false;
1362 + p->file = m->file;
1363 + p->file_offset = offset;
1364 + p->file_bytes = length >= PGSIZE ? PGSIZE : length;
1365 + offset += p->file_bytes;
1366 + length -= p->file_bytes;
1373 +/* Munmap system call. */
1375 +sys_munmap (int mapping)
1377 + unmap (lookup_mapping (mapping));
1381 +/* On thread exit, close all open files and unmap all mappings. */
1383 +syscall_exit (void)
1385 + struct thread *cur = thread_current ();
1386 + struct list_elem *e, *next;
1388 + for (e = list_begin (&cur->fds); e != list_end (&cur->fds); e = next)
1390 + struct file_descriptor *fd = list_entry (e, struct file_descriptor, elem);
1391 + next = list_next (e);
1392 + lock_acquire (&fs_lock);
1393 + file_close (fd->file);
1394 + lock_release (&fs_lock);
1398 + for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
1401 + struct mapping *m = list_entry (e, struct mapping, elem);
1402 + next = list_next (e);
1406 Index: src/userprog/syscall.h
1407 diff -u src/userprog/syscall.h~ src/userprog/syscall.h
1408 --- src/userprog/syscall.h~
1409 +++ src/userprog/syscall.h
1411 #define USERPROG_SYSCALL_H
1413 void syscall_init (void);
1414 +void syscall_exit (void);
1416 #endif /* userprog/syscall.h */
1417 Index: src/vm/frame.c
1418 diff -u src/vm/frame.c~ src/vm/frame.c
1422 +#include "vm/frame.h"
1424 +#include "vm/page.h"
1425 +#include "devices/timer.h"
1426 +#include "threads/init.h"
1427 +#include "threads/malloc.h"
1428 +#include "threads/palloc.h"
1429 +#include "threads/synch.h"
1430 +#include "threads/vaddr.h"
1432 +static struct frame *frames;
1433 +static size_t frame_cnt;
1435 +static struct lock scan_lock;
1436 +static size_t hand;
1438 +/* Initialize the frame manager. */
1444 + lock_init (&scan_lock);
1446 + frames = malloc (sizeof *frames * ram_pages);
1447 + if (frames == NULL)
1448 + PANIC ("out of memory allocating page frames");
1450 + while ((base = palloc_get_page (PAL_USER)) != NULL)
1452 + struct frame *f = &frames[frame_cnt++];
1453 + lock_init (&f->lock);
1459 +/* Tries to allocate and lock a frame for PAGE.
1460 + Returns the frame if successful, false on failure. */
1461 +static struct frame *
1462 +try_frame_alloc_and_lock (struct page *page)
1466 + lock_acquire (&scan_lock);
1468 + /* Find a free frame. */
1469 + for (i = 0; i < frame_cnt; i++)
1471 + struct frame *f = &frames[i];
1472 + if (!lock_try_acquire (&f->lock))
1474 + if (f->page == NULL)
1477 + lock_release (&scan_lock);
1480 + lock_release (&f->lock);
1483 + /* No free frame. Find a frame to evict. */
1484 + for (i = 0; i < frame_cnt * 2; i++)
1486 + /* Get a frame. */
1487 + struct frame *f = &frames[hand];
1488 + if (++hand >= frame_cnt)
1491 + if (!lock_try_acquire (&f->lock))
1494 + if (f->page == NULL)
1497 + lock_release (&scan_lock);
1501 + if (page_accessed_recently (f->page))
1503 + lock_release (&f->lock);
1507 + lock_release (&scan_lock);
1509 + /* Evict this frame. */
1510 + if (!page_out (f->page))
1512 + lock_release (&f->lock);
1520 + lock_release (&scan_lock);
1525 +/* Tries really hard to allocate and lock a frame for PAGE.
1526 + Returns the frame if successful, false on failure. */
1528 +frame_alloc_and_lock (struct page *page)
1532 + for (try = 0; try < 3; try++)
1534 + struct frame *f = try_frame_alloc_and_lock (page);
1537 + ASSERT (lock_held_by_current_thread (&f->lock));
1540 + timer_msleep (1000);
1546 +/* Locks P's frame into memory, if it has one.
1547 + Upon return, p->frame will not change until P is unlocked. */
1549 +frame_lock (struct page *p)
1551 + /* A frame can be asynchronously removed, but never inserted. */
1552 + struct frame *f = p->frame;
1555 + lock_acquire (&f->lock);
1556 + if (f != p->frame)
1558 + lock_release (&f->lock);
1559 + ASSERT (p->frame == NULL);
1564 +/* Releases frame F for use by another page.
1565 + F must be locked for use by the current process.
1566 + Any data in F is lost. */
1568 +frame_free (struct frame *f)
1570 + ASSERT (lock_held_by_current_thread (&f->lock));
1573 + lock_release (&f->lock);
1576 +/* Unlocks frame F, allowing it to be evicted.
1577 + F must be locked for use by the current process. */
1579 +frame_unlock (struct frame *f)
1581 + ASSERT (lock_held_by_current_thread (&f->lock));
1582 + lock_release (&f->lock);
1584 Index: src/vm/frame.h
1585 diff -u src/vm/frame.h~ src/vm/frame.h
1592 +#include <stdbool.h>
1593 +#include "threads/synch.h"
1595 +/* A physical frame. */
1598 + struct lock lock; /* Prevent simultaneous access. */
1599 + void *base; /* Kernel virtual base address. */
1600 + struct page *page; /* Mapped process page, if any. */
1603 +void frame_init (void);
1605 +struct frame *frame_alloc_and_lock (struct page *);
1606 +void frame_lock (struct page *);
1608 +void frame_free (struct frame *);
1609 +void frame_unlock (struct frame *);
1611 +#endif /* vm/frame.h */
1612 Index: src/vm/page.c
1613 diff -u src/vm/page.c~ src/vm/page.c
1617 +#include "vm/page.h"
1619 +#include <string.h>
1620 +#include "vm/frame.h"
1621 +#include "vm/swap.h"
1622 +#include "filesys/file.h"
1623 +#include "threads/malloc.h"
1624 +#include "threads/thread.h"
1625 +#include "userprog/pagedir.h"
1626 +#include "threads/vaddr.h"
1628 +/* Maximum size of process stack, in bytes. */
1629 +#define STACK_MAX (1024 * 1024)
1631 +/* Destroys a page, which must be in the current process's
1632 + page table. Used as a callback for hash_destroy(). */
1634 +destroy_page (struct hash_elem *p_, void *aux UNUSED)
1636 + struct page *p = hash_entry (p_, struct page, hash_elem);
1639 + frame_free (p->frame);
1643 +/* Destroys the current process's page table. */
1647 + struct hash *h = thread_current ()->pages;
1649 + hash_destroy (h, destroy_page);
1652 +/* Returns the page containing the given virtual ADDRESS,
1653 + or a null pointer if no such page exists.
1654 + Allocates stack pages as necessary. */
1655 +static struct page *
1656 +page_for_addr (const void *address)
1658 + if (address < PHYS_BASE)
1661 + struct hash_elem *e;
1663 + /* Find existing page. */
1664 + p.addr = (void *) pg_round_down (address);
1665 + e = hash_find (thread_current ()->pages, &p.hash_elem);
1667 + return hash_entry (e, struct page, hash_elem);
1669 + /* No page. Expand stack? */
1670 + if (address >= PHYS_BASE - STACK_MAX
1671 + && address >= thread_current ()->user_esp - 32)
1672 + return page_allocate ((void *) address, false);
1677 +/* Locks a frame for page P and pages it in.
1678 + Returns true if successful, false on failure. */
1680 +do_page_in (struct page *p)
1682 + /* Get a frame for the page. */
1683 + p->frame = frame_alloc_and_lock (p);
1684 + if (p->frame == NULL)
1687 + /* Copy data into the frame. */
1688 + if (p->sector != (disk_sector_t) -1)
1690 + /* Get data from swap. */
1693 + else if (p->file != NULL)
1695 + /* Get data from file. */
1696 + off_t read_bytes = file_read_at (p->file, p->frame->base,
1697 + p->file_bytes, p->file_offset);
1698 + off_t zero_bytes = PGSIZE - read_bytes;
1699 + memset (p->frame->base + read_bytes, 0, zero_bytes);
1700 + if (read_bytes != p->file_bytes)
1701 + printf ("bytes read (%"PROTd") != bytes requested (%"PROTd")\n",
1702 + read_bytes, p->file_bytes);
1706 + /* Provide all-zero page. */
1707 + memset (p->frame->base, 0, PGSIZE);
1713 +/* Faults in the page containing FAULT_ADDR.
1714 + Returns true if successful, false on failure. */
1716 +page_in (void *fault_addr)
1721 + /* Can't handle page faults without a hash table. */
1722 + if (thread_current ()->pages == NULL)
1725 + p = page_for_addr (fault_addr);
1730 + if (p->frame == NULL)
1732 + if (!do_page_in (p))
1735 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1737 + /* Install frame into page table. */
1738 + success = pagedir_set_page (thread_current ()->pagedir, p->addr,
1739 + p->frame->base, !p->read_only);
1741 + /* Release frame. */
1742 + frame_unlock (p->frame);
1748 + P must have a locked frame.
1749 + Return true if successful, false on failure. */
1751 +page_out (struct page *p)
1756 + ASSERT (p->frame != NULL);
1757 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1759 + /* Mark page not present in page table, forcing accesses by the
1760 + process to fault. This must happen before checking the
1761 + dirty bit, to prevent a race with the process dirtying the
1763 + pagedir_clear_page (p->thread->pagedir, p->addr);
1765 + /* Has the frame been modified? */
1766 + dirty = pagedir_is_dirty (p->thread->pagedir, p->addr);
1768 + /* Write frame contents to disk if necessary. */
1769 + if (p->file != NULL)
1774 + ok = swap_out (p);
1776 + ok = file_write_at (p->file, p->frame->base, p->file_bytes,
1777 + p->file_offset) == p->file_bytes;
1783 + ok = swap_out (p);
1786 + //memset (p->frame->base, 0xcc, PGSIZE);
1792 +/* Returns true if page P's data has been accessed recently,
1794 + P must have a frame locked into memory. */
1796 +page_accessed_recently (struct page *p)
1798 + bool was_accessed;
1800 + ASSERT (p->frame != NULL);
1801 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
1803 + was_accessed = pagedir_is_accessed (p->thread->pagedir, p->addr);
1805 + pagedir_set_accessed (p->thread->pagedir, p->addr, false);
1806 + return was_accessed;
1809 +/* Adds a mapping for user virtual address VADDR to the page hash
1810 + table. Fails if VADDR is already mapped or if memory
1811 + allocation fails. */
1813 +page_allocate (void *vaddr, bool read_only)
1815 + struct thread *t = thread_current ();
1816 + struct page *p = malloc (sizeof *p);
1819 + p->addr = pg_round_down (vaddr);
1821 + p->read_only = read_only;
1822 + p->private = !read_only;
1826 + p->sector = (disk_sector_t) -1;
1829 + p->file_offset = 0;
1830 + p->file_bytes = 0;
1832 + p->thread = thread_current ();
1834 + if (hash_insert (t->pages, &p->hash_elem) != NULL)
1836 + /* Already mapped. */
1844 +/* Evicts the page containing address VADDR
1845 + and removes it from the page table. */
1847 +page_deallocate (void *vaddr)
1849 + struct page *p = page_for_addr (vaddr);
1850 + ASSERT (p != NULL);
1854 + struct frame *f = p->frame;
1855 + if (p->file && !p->private)
1859 + hash_delete (thread_current ()->pages, &p->hash_elem);
1863 +/* Returns a hash value for the page that E refers to. */
1865 +page_hash (const struct hash_elem *e, void *aux UNUSED)
1867 + const struct page *p = hash_entry (e, struct page, hash_elem);
1868 + return ((uintptr_t) p->addr) >> PGBITS;
1871 +/* Returns true if page A precedes page B. */
1873 +page_less (const struct hash_elem *a_, const struct hash_elem *b_,
1876 + const struct page *a = hash_entry (a_, struct page, hash_elem);
1877 + const struct page *b = hash_entry (b_, struct page, hash_elem);
1879 + return a->addr < b->addr;
1882 +/* Tries to lock the page containing ADDR into physical memory.
1883 + If WILL_WRITE is true, the page must be writeable;
1884 + otherwise it may be read-only.
1885 + Returns true if successful, false on failure. */
1887 +page_lock (const void *addr, bool will_write)
1889 + struct page *p = page_for_addr (addr);
1890 + if (p == NULL || (p->read_only && will_write))
1894 + if (p->frame == NULL)
1895 + return (do_page_in (p)
1896 + && pagedir_set_page (thread_current ()->pagedir, p->addr,
1897 + p->frame->base, !p->read_only));
1902 +/* Unlocks a page locked with page_lock(). */
1904 +page_unlock (const void *addr)
1906 + struct page *p = page_for_addr (addr);
1907 + ASSERT (p != NULL);
1908 + frame_unlock (p->frame);
1910 Index: src/vm/page.h
1911 diff -u src/vm/page.h~ src/vm/page.h
1919 +#include "devices/disk.h"
1920 +#include "filesys/off_t.h"
1921 +#include "threads/synch.h"
1923 +/* Virtual page. */
1926 + /* Immutable members. */
1927 + void *addr; /* User virtual address. */
1928 + bool read_only; /* Read-only page? */
1929 + struct thread *thread; /* Owning thread. */
1931 + /* Accessed only in owning process context. */
1932 + struct hash_elem hash_elem; /* struct thread `pages' hash element. */
1934 + /* Set only in owning process context with frame->frame_lock held.
1935 + Cleared only with scan_lock and frame->frame_lock held. */
1936 + struct frame *frame; /* Page frame. */
1938 + /* Swap information, protected by frame->frame_lock. */
1939 + disk_sector_t sector; /* Starting sector of swap area, or -1. */
1941 + /* Memory-mapped file information, protected by frame->frame_lock. */
1942 + bool private; /* False to write back to file,
1943 + true to write back to swap. */
1944 + struct file *file; /* File. */
1945 + off_t file_offset; /* Offset in file. */
1946 + off_t file_bytes; /* Bytes to read/write, 1...PGSIZE. */
1949 +void page_exit (void);
1951 +struct page *page_allocate (void *, bool read_only);
1952 +void page_deallocate (void *vaddr);
1954 +bool page_in (void *fault_addr);
1955 +bool page_out (struct page *);
1956 +bool page_accessed_recently (struct page *);
1958 +bool page_lock (const void *, bool will_write);
1959 +void page_unlock (const void *);
1961 +hash_hash_func page_hash;
1962 +hash_less_func page_less;
1964 +#endif /* vm/page.h */
1965 Index: src/vm/swap.c
1966 diff -u src/vm/swap.c~ src/vm/swap.c
1970 +#include "vm/swap.h"
1971 +#include <bitmap.h>
1974 +#include "vm/frame.h"
1975 +#include "vm/page.h"
1976 +#include "devices/disk.h"
1977 +#include "threads/synch.h"
1978 +#include "threads/vaddr.h"
1980 +/* The swap disk. */
1981 +static struct disk *swap_disk;
1983 +/* Used swap pages. */
1984 +static struct bitmap *swap_bitmap;
1986 +/* Protects swap_bitmap. */
1987 +static struct lock swap_lock;
1989 +/* Number of sectors per page. */
1990 +#define PAGE_SECTORS (PGSIZE / DISK_SECTOR_SIZE)
1992 +/* Sets up swap. */
1996 + swap_disk = disk_get (1, 1);
1997 + if (swap_disk == NULL)
1999 + printf ("no swap disk--swap disabled\n");
2000 + swap_bitmap = bitmap_create (0);
2003 + swap_bitmap = bitmap_create (disk_size (swap_disk) / PAGE_SECTORS);
2004 + if (swap_bitmap == NULL)
2005 + PANIC ("couldn't create swap bitmap");
2006 + lock_init (&swap_lock);
2009 +/* Swaps in page P, which must have a locked frame
2010 + (and be swapped out). */
2012 +swap_in (struct page *p)
2016 + ASSERT (p->frame != NULL);
2017 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
2018 + ASSERT (p->sector != (disk_sector_t) -1);
2020 + for (i = 0; i < PAGE_SECTORS; i++)
2021 + disk_read (swap_disk, p->sector + i,
2022 + p->frame->base + i * DISK_SECTOR_SIZE);
2023 + bitmap_reset (swap_bitmap, p->sector / PAGE_SECTORS);
2024 + p->sector = (disk_sector_t) -1;
2027 +/* Swaps out page P, which must have a locked frame. */
2029 +swap_out (struct page *p)
2034 + ASSERT (p->frame != NULL);
2035 + ASSERT (lock_held_by_current_thread (&p->frame->lock));
2037 + lock_acquire (&swap_lock);
2038 + slot = bitmap_scan_and_flip (swap_bitmap, 0, 1, false);
2039 + lock_release (&swap_lock);
2040 + if (slot == BITMAP_ERROR)
2043 + p->sector = slot * PAGE_SECTORS;
2044 + for (i = 0; i < PAGE_SECTORS; i++)
2045 + disk_write (swap_disk, p->sector + i,
2046 + p->frame->base + i * DISK_SECTOR_SIZE);
2048 + p->private = false;
2050 + p->file_offset = 0;
2051 + p->file_bytes = 0;
2055 Index: src/vm/swap.h
2056 diff -u src/vm/swap.h~ src/vm/swap.h
2061 +#define VM_SWAP_H 1
2063 +#include <stdbool.h>
2066 +void swap_init (void);
2067 +void swap_in (struct page *);
2068 +bool swap_out (struct page *);
2070 +#endif /* vm/swap.h */