Normalize style of patches to reduce changes later.
[pintos-anon] / solutions / p4.patch
1 Index: src/Makefile.build
2 diff -u src/Makefile.build~ src/Makefile.build
3 --- src/Makefile.build~
4 +++ src/Makefile.build
5 @@ -53,7 +53,9 @@ userprog_SRC += userprog/gdt.c                # GDT in
6  userprog_SRC += userprog/tss.c         # TSS management.
7  
8  # No virtual memory code yet.
9 -#vm_SRC = vm/file.c                    # Some file.
10 +vm_SRC = vm/page.c
11 +vm_SRC += vm/frame.c
12 +vm_SRC += vm/swap.c
13  
14  # Filesystem code.
15  filesys_SRC  = filesys/filesys.c       # Filesystem core.
16 @@ -62,6 +64,7 @@ filesys_SRC += filesys/file.c         # Files.
17  filesys_SRC += filesys/directory.c     # Directories.
18  filesys_SRC += filesys/inode.c         # File headers.
19  filesys_SRC += filesys/fsutil.c                # Utilities.
20 +filesys_SRC += filesys/cache.c         # Cache.
21  
22  SOURCES = $(foreach dir,$(KERNEL_SUBDIRS),$($(dir)_SRC))
23  OBJECTS = $(patsubst %.c,%.o,$(patsubst %.S,%.o,$(SOURCES)))
24 Index: src/devices/timer.c
25 diff -u src/devices/timer.c~ src/devices/timer.c
26 --- src/devices/timer.c~
27 +++ src/devices/timer.c
28 @@ -23,6 +23,9 @@ static volatile int64_t ticks;
29     Initialized by timer_calibrate(). */
30  static unsigned loops_per_tick;
31  
32 +/* Threads waiting in timer_sleep(). */
33 +static struct list wait_list;
34 +
35  static intr_handler_func timer_interrupt;
36  static bool too_many_loops (unsigned loops);
37  static void busy_wait (int64_t loops);
38 @@ -43,6 +46,8 @@ timer_init (void) 
39    outb (0x40, count >> 8);
40  
41    intr_register_ext (0x20, timer_interrupt, "8254 Timer");
42 +
43 +  list_init (&wait_list);
44  }
45  
46  /* Calibrates loops_per_tick, used to implement brief delays. */
47 @@ -87,15 +92,36 @@ timer_elapsed (int64_t then) 
48    return timer_ticks () - then;
49  }
50  
51 +/* Compares two threads based on their wake-up times. */
52 +static bool
53 +compare_threads_by_wakeup_time (const struct list_elem *a_,
54 +                                const struct list_elem *b_,
55 +                                void *aux UNUSED) 
56 +{
57 +  const struct thread *a = list_entry (a_, struct thread, timer_elem);
58 +  const struct thread *b = list_entry (b_, struct thread, timer_elem);
59 +
60 +  return a->wakeup_time < b->wakeup_time;
61 +}
62 +
63  /* Suspends execution for approximately TICKS timer ticks. */
64  void
65  timer_sleep (int64_t ticks) 
66  {
67 -  int64_t start = timer_ticks ();
68 +  struct thread *t = thread_current ();
69 +
70 +  /* Schedule our wake-up time. */
71 +  t->wakeup_time = timer_ticks () + ticks;
72  
73 +  /* Atomically insert the current thread into the wait list. */
74    ASSERT (intr_get_level () == INTR_ON);
75 -  while (timer_elapsed (start) < ticks) 
76 -    thread_yield ();
77 +  intr_disable ();
78 +  list_insert_ordered (&wait_list, &t->timer_elem,
79 +                       compare_threads_by_wakeup_time, NULL);
80 +  intr_enable ();
81 +
82 +  /* Wait. */
83 +  sema_down (&t->timer_sema);
84  }
85  
86  /* Suspends execution for approximately MS milliseconds. */
87 @@ -132,6 +158,16 @@ timer_interrupt (struct intr_frame *args
88  {
89    ticks++;
90    thread_tick ();
91 +
92 +  while (!list_empty (&wait_list))
93 +    {
94 +      struct thread *t = list_entry (list_front (&wait_list),
95 +                                     struct thread, timer_elem);
96 +      if (ticks < t->wakeup_time) 
97 +        break;
98 +      sema_up (&t->timer_sema);
99 +      list_pop_front (&wait_list);
100 +    }
101  }
102  
103  /* Returns true if LOOPS iterations waits for more than one timer
104 Index: src/filesys/Make.vars
105 diff -u src/filesys/Make.vars~ src/filesys/Make.vars
106 --- src/filesys/Make.vars~
107 +++ src/filesys/Make.vars
108 @@ -6,7 +6,7 @@ TEST_SUBDIRS = tests/userprog tests/file
109  GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.no-vm
110  
111  # Uncomment the lines below to enable VM.
112 -#os.dsk: DEFINES += -DVM
113 -#KERNEL_SUBDIRS += vm
114 -#TEST_SUBDIRS += tests/vm
115 -#GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.with-vm
116 +os.dsk: DEFINES += -DVM
117 +KERNEL_SUBDIRS += vm
118 +TEST_SUBDIRS += tests/vm
119 +GRADING_FILE = $(SRCDIR)/tests/filesys/Grading.with-vm
120 Index: src/filesys/cache.c
121 diff -u src/filesys/cache.c~ src/filesys/cache.c
122 --- src/filesys/cache.c~
123 +++ src/filesys/cache.c
124 @@ -0,0 +1,473 @@
125 +#include "filesys/cache.h"
126 +#include <debug.h>
127 +#include <string.h>
128 +#include "filesys/filesys.h"
129 +#include "devices/disk.h"
130 +#include "devices/timer.h"
131 +#include "threads/malloc.h"
132 +#include "threads/synch.h"
133 +#include "threads/thread.h"
134 +
135 +#define INVALID_SECTOR ((disk_sector_t) -1)
136 +
137 +/* A cached block. */
138 +struct cache_block 
139 +  {
140 +    /* Locking to prevent eviction. */
141 +    struct lock block_lock;                    /* Protects fields in group. */
142 +    struct condition no_readers_or_writers; /* readers == 0 && writers == 0 */
143 +    struct condition no_writers;                            /* writers == 0 */
144 +    int readers, read_waiters;          /* # of readers, # waiting to read. */
145 +    int writers, write_waiters; /* # of writers (<= 1), # waiting to write. */
146 +
147 +    /* Sector number.  INVALID_SECTOR indicates a free cache block.
148 +
149 +       Changing from free to allocated requires cache_sync.
150 +
151 +       Changing from allocated to free requires block_lock, block
152 +       must be up-to-date and not dirty, and no one may be
153 +       waiting on it. */
154 +    disk_sector_t sector;
155 +
156 +    /* Is data[] correct?
157 +       Requires write lock or data_lock. */
158 +    bool up_to_date;
159 +
160 +    /* Does data[] need to be written back to disk?
161 +       Valid only when up-to-date.
162 +       Requires read lock or write lock or data_lock. */
163 +    bool dirty;
164 +
165 +    /* Sector data.
166 +       Access to data[] requires up-to-date and read or write lock.
167 +       Bringing up-to-date requires write lock or data_lock. */
168 +    struct lock data_lock;              /* Protects fields in group. */
169 +    uint8_t data[DISK_SECTOR_SIZE];     /* Disk data. */
170 +  };
171 +
172 +/* Cache. */
173 +#define CACHE_CNT 64
174 +struct cache_block cache[CACHE_CNT];
175 +
176 +/* Cache lock.
177 +
178 +   Required to allocate a cache block to a sector, to prevent a
179 +   single sector being allocated two different cache blocks.
180 +
181 +   Required to search the cache for a sector, to prevent the
182 +   sector from being added while the search is ongoing.
183 +
184 +   Protects hand. */
185 +struct lock cache_sync;
186 +
187 +/* Cache eviction hand.
188 +   Protected by cache_sync. */
189 +static int hand = 0;
190 +
191 +static void flushd_init (void);
192 +static void readaheadd_init (void);
193 +static void readaheadd_submit (disk_sector_t sector);
194 +\f
195 +/* Initializes cache. */
196 +void
197 +cache_init (void) 
198 +{
199 +  int i;
200 +  
201 +  lock_init (&cache_sync);
202 +  for (i = 0; i < CACHE_CNT; i++) 
203 +    {
204 +      struct cache_block *b = &cache[i];
205 +      lock_init (&b->block_lock);
206 +      cond_init (&b->no_readers_or_writers);
207 +      cond_init (&b->no_writers);
208 +      b->readers = b->read_waiters = 0;
209 +      b->writers = b->write_waiters = 0;
210 +      b->sector = INVALID_SECTOR;
211 +      lock_init (&b->data_lock);
212 +    }
213 +
214 +  flushd_init ();
215 +  readaheadd_init ();
216 +}
217 +
218 +/* Flushes cache to disk. */
219 +void
220 +cache_flush (void) 
221 +{
222 +  int i;
223 +  
224 +  for (i = 0; i < CACHE_CNT; i++)
225 +    {
226 +      struct cache_block *b = &cache[i];
227 +      disk_sector_t sector;
228 +      
229 +      lock_acquire (&b->block_lock);
230 +      sector = b->sector;
231 +      lock_release (&b->block_lock);
232 +
233 +      if (sector == INVALID_SECTOR)
234 +        continue;
235 +
236 +      b = cache_lock (sector, EXCLUSIVE);
237 +      if (b->up_to_date && b->dirty) 
238 +        {
239 +          disk_write (filesys_disk, b->sector, b->data);
240 +          b->dirty = false; 
241 +        }
242 +      cache_unlock (b);
243 +    }
244 +}
245 +
246 +/* Locks the given SECTOR into the cache and returns the cache
247 +   block.
248 +   If TYPE is EXCLUSIVE, then the block returned will be locked
249 +   only by the caller.  The calling thread must not already
250 +   have any lock on the block.
251 +   If TYPE is NON_EXCLUSIVE, then block returned may be locked by
252 +   any number of other callers.  The calling thread may already
253 +   have any number of non-exclusive locks on the block. */
254 +struct cache_block *
255 +cache_lock (disk_sector_t sector, enum lock_type type) 
256 +{
257 +  int i;
258 +
259 + try_again:
260 +  lock_acquire (&cache_sync);
261 +
262 +  /* Is the block already in-cache? */
263 +  for (i = 0; i < CACHE_CNT; i++)
264 +    {
265 +      /* Skip any blocks that don't hold SECTOR. */
266 +      struct cache_block *b = &cache[i];
267 +      lock_acquire (&b->block_lock);
268 +      if (b->sector != sector) 
269 +        {
270 +          lock_release (&b->block_lock);
271 +          continue;
272 +        }
273 +      lock_release (&cache_sync);
274 +
275 +      /* Get read or write lock. */
276 +      if (type == NON_EXCLUSIVE) 
277 +        {
278 +          /* Lock for read. */
279 +          b->read_waiters++;
280 +          if (b->writers || b->write_waiters)
281 +            do {
282 +              cond_wait (&b->no_writers, &b->block_lock);
283 +            } while (b->writers);
284 +          b->readers++;
285 +          b->read_waiters--;
286 +        }
287 +      else 
288 +        {
289 +          /* Lock for write. */
290 +          b->write_waiters++;
291 +          if (b->readers || b->read_waiters || b->writers)
292 +            do {
293 +              cond_wait (&b->no_readers_or_writers, &b->block_lock);
294 +            } while (b->readers || b->writers);
295 +          b->writers++;
296 +          b->write_waiters--;
297 +        }
298 +      lock_release (&b->block_lock);
299 +
300 +      /* Our sector should have been pinned in the cache while we
301 +         were waiting.  Make sure. */
302 +      ASSERT (b->sector == sector);
303 +
304 +      return b;
305 +    }
306 +
307 +  /* Not in cache.  Find empty slot.
308 +     We hold cache_sync. */
309 +  for (i = 0; i < CACHE_CNT; i++)
310 +    {
311 +      struct cache_block *b = &cache[i];
312 +      lock_acquire (&b->block_lock);
313 +      if (b->sector == INVALID_SECTOR) 
314 +        {
315 +          /* Drop block_lock, which is no longer needed because
316 +             this is the only code that allocates free blocks,
317 +             and we still have cache_sync.
318 +
319 +             We can't drop cache_sync yet because someone else
320 +             might try to allocate this same block (or read from
321 +             it) while we're still initializing the block. */
322 +          lock_release (&b->block_lock);
323 +
324 +          b->sector = sector;
325 +          b->up_to_date = false;
326 +          ASSERT (b->readers == 0);
327 +          ASSERT (b->writers == 0);
328 +          if (type == NON_EXCLUSIVE)
329 +            b->readers = 1;
330 +          else
331 +            b->writers = 1;
332 +          lock_release (&cache_sync);
333 +          return b;
334 +        }
335 +      lock_release (&b->block_lock); 
336 +    }
337 +
338 +  /* No empty slots.  Evict something.
339 +     We hold cache_sync. */
340 +  for (i = 0; i < CACHE_CNT; i++)
341 +    {
342 +      struct cache_block *b = &cache[hand];
343 +      if (++hand >= CACHE_CNT)
344 +        hand = 0;
345 +
346 +      /* Try to grab exclusive write access to block. */
347 +      lock_acquire (&b->block_lock);
348 +      if (b->readers || b->writers || b->read_waiters || b->write_waiters) 
349 +        {
350 +          lock_release (&b->block_lock);
351 +          continue;
352 +        }
353 +      b->writers = 1;
354 +      lock_release (&b->block_lock);
355 +
356 +      lock_release (&cache_sync);
357 +
358 +      /* Write block to disk if dirty. */
359 +      if (b->up_to_date && b->dirty) 
360 +        {
361 +          disk_write (filesys_disk, b->sector, b->data);
362 +          b->dirty = false;
363 +        }
364 +
365 +      /* Remove block from cache, if possible: someone might have
366 +         started waiting on it while the lock was released. */
367 +      lock_acquire (&b->block_lock);
368 +      b->writers = 0;
369 +      if (!b->read_waiters && !b->write_waiters) 
370 +        {
371 +          /* No one is waiting for it, so we can free it. */
372 +          b->sector = INVALID_SECTOR; 
373 +        }
374 +      else 
375 +        {
376 +          /* There is a waiter.  Give it the block. */
377 +          if (b->read_waiters)
378 +            cond_broadcast (&b->no_writers, &b->block_lock);
379 +          else
380 +            cond_signal (&b->no_readers_or_writers, &b->block_lock);
381 +        }
382 +      lock_release (&b->block_lock);
383 +
384 +      /* Try again. */
385 +      goto try_again;
386 +    }
387 +
388 +  /* Wait for cache contention to die down. */
389 +  lock_release (&cache_sync);
390 +  timer_sleep (1000);
391 +  goto try_again;
392 +}
393 +
394 +/* Bring block B up-to-date, by reading it from disk if
395 +   necessary, and return a pointer to its data.
396 +   The caller must have an exclusive or non-exclusive lock on
397 +   B. */
398 +void *
399 +cache_read (struct cache_block *b) 
400 +{
401 +  lock_acquire (&b->data_lock);
402 +  if (!b->up_to_date) 
403 +    {
404 +      disk_read (filesys_disk, b->sector, b->data);
405 +      b->up_to_date = true;
406 +      b->dirty = false; 
407 +    }
408 +  lock_release (&b->data_lock);
409 +
410 +  return b->data;
411 +}
412 +
413 +/* Zero out block B, without reading it from disk, and return a
414 +   pointer to the zeroed data.
415 +   The caller must have an exclusive lock on B. */
416 +void *
417 +cache_zero (struct cache_block *b) 
418 +{
419 +  ASSERT (b->writers);
420 +  memset (b->data, 0, DISK_SECTOR_SIZE);
421 +  b->up_to_date = true;
422 +  b->dirty = true;
423 +
424 +  return b->data;
425 +}
426 +
427 +/* Marks block B as dirty, so that it will be written back to
428 +   disk before eviction.
429 +   The caller must have a read or write lock on B,
430 +   and B must be up-to-date. */
431 +void
432 +cache_dirty (struct cache_block *b) 
433 +{
434 +  ASSERT (b->up_to_date);
435 +  b->dirty = true;
436 +}
437 +
438 +/* Unlocks block B.
439 +   If B is no longer locked by any thread, then it becomes a
440 +   candidate for immediate eviction. */
441 +void
442 +cache_unlock (struct cache_block *b) 
443 +{
444 +  lock_acquire (&b->block_lock);
445 +  if (b->readers) 
446 +    {
447 +      ASSERT (b->writers == 0);
448 +      if (--b->readers == 0)
449 +        cond_signal (&b->no_readers_or_writers, &b->block_lock);
450 +    }
451 +  else if (b->writers)
452 +    {
453 +      ASSERT (b->readers == 0);
454 +      ASSERT (b->writers == 1);
455 +      b->writers--;
456 +      if (b->read_waiters)
457 +        cond_broadcast (&b->no_writers, &b->block_lock);
458 +      else
459 +        cond_signal (&b->no_readers_or_writers, &b->block_lock);
460 +    }
461 +  else
462 +    NOT_REACHED ();
463 +  lock_release (&b->block_lock);
464 +}
465 +
466 +/* If SECTOR is in the cache, evicts it immediately without
467 +   writing it back to disk (even if dirty).
468 +   The block must be entirely unused. */
469 +void
470 +cache_free (disk_sector_t sector) 
471 +{
472 +  int i;
473 +  
474 +  lock_acquire (&cache_sync);
475 +  for (i = 0; i < CACHE_CNT; i++)
476 +    {
477 +      struct cache_block *b = &cache[i];
478 +
479 +      lock_acquire (&b->block_lock);
480 +      if (b->sector == sector) 
481 +        {
482 +          lock_release (&cache_sync);
483 +
484 +          /* Only invalidate the block if it's unused.  That
485 +             should be the normal case, but it could be part of a
486 +             read-ahead (in readaheadd()) or write-behind (in
487 +             cache_flush()). */
488 +          if (b->readers == 0 && b->read_waiters == 0
489 +              && b->writers == 0 && b->write_waiters == 0) 
490 +            b->sector = INVALID_SECTOR; 
491 +
492 +          lock_release (&b->block_lock);
493 +          return;
494 +        }
495 +      lock_release (&b->block_lock);
496 +    }
497 +  lock_release (&cache_sync);
498 +}
499 +
500 +void
501 +cache_readahead (disk_sector_t sector) 
502 +{
503 +  readaheadd_submit (sector);
504 +}
505 +\f
506 +/* Flush daemon. */
507 +
508 +static void flushd (void *aux);
509 +
510 +/* Initializes flush daemon. */
511 +static void
512 +flushd_init (void) 
513 +{
514 +  thread_create ("flushd", PRI_MIN, flushd, NULL);
515 +}
516 +
517 +/* Flush daemon thread. */
518 +static void
519 +flushd (void *aux UNUSED) 
520 +{
521 +  for (;;) 
522 +    {
523 +      timer_msleep (30 * 1000);
524 +      cache_flush ();
525 +    }
526 +}
527 +\f
528 +/* A block to read ahead. */
529 +struct readahead_block 
530 +  {
531 +    struct list_elem list_elem;         /* readahead_list element. */
532 +    disk_sector_t sector;               /* Sector to read. */
533 +  };
534 +
535 +/* Protects readahead_list.
536 +   Monitor lock for readahead_list_nonempty. */
537 +static struct lock readahead_lock;
538 +
539 +/* Signaled when a block is added to readahead_list. */
540 +static struct condition readahead_list_nonempty;
541 +
542 +/* List of blocks for read-ahead. */
543 +static struct list readahead_list;
544 +
545 +static void readaheadd (void *aux);
546 +
547 +/* Initialize read-ahead daemon. */
548 +static void
549 +readaheadd_init (void) 
550 +{
551 +  lock_init (&readahead_lock);
552 +  cond_init (&readahead_list_nonempty);
553 +  list_init (&readahead_list);
554 +  thread_create ("readaheadd", PRI_MIN, readaheadd, NULL);
555 +}
556 +
557 +/* Adds SECTOR to the read-ahead queue. */
558 +static void
559 +readaheadd_submit (disk_sector_t sector) 
560 +{
561 +  /* Allocate readahead block. */
562 +  struct readahead_block *block = malloc (sizeof *block);
563 +  if (block == NULL)
564 +    return;
565 +  block->sector = sector;
566 +
567 +  /* Add block to list. */
568 +  lock_acquire (&readahead_lock);
569 +  list_push_back (&readahead_list, &block->list_elem);
570 +  cond_signal (&readahead_list_nonempty, &readahead_lock);
571 +  lock_release (&readahead_lock);
572 +}
573 +
574 +/* Read-ahead daemon. */
575 +static void
576 +readaheadd (void *aux UNUSED) 
577 +{
578 +  for (;;) 
579 +    {
580 +      struct readahead_block *ra_block;
581 +      struct cache_block *cache_block;
582 +
583 +      /* Get readahead block from list. */
584 +      lock_acquire (&readahead_lock);
585 +      while (list_empty (&readahead_list)) 
586 +        cond_wait (&readahead_list_nonempty, &readahead_lock);
587 +      ra_block = list_entry (list_pop_front (&readahead_list),
588 +                             struct readahead_block, list_elem);
589 +      lock_release (&readahead_lock);
590 +
591 +      /* Read block into cache. */
592 +      cache_block = cache_lock (ra_block->sector, NON_EXCLUSIVE);
593 +      cache_read (cache_block);
594 +      cache_unlock (cache_block);
595 +      free (ra_block);
596 +    }
597 +}
598 Index: src/filesys/cache.h
599 diff -u src/filesys/cache.h~ src/filesys/cache.h
600 --- src/filesys/cache.h~
601 +++ src/filesys/cache.h
602 @@ -0,0 +1,23 @@
603 +#ifndef FILESYS_CACHE_H
604 +#define FILESYS_CACHE_H
605 +
606 +#include "devices/disk.h"
607 +
608 +/* Type of block lock. */
609 +enum lock_type 
610 +  {
611 +    NON_EXCLUSIVE,     /* Any number of lockers. */
612 +    EXCLUSIVE          /* Only one locker. */
613 +  };
614 +
615 +void cache_init (void);
616 +void cache_flush (void);
617 +struct cache_block *cache_lock (disk_sector_t, enum lock_type);
618 +void *cache_read (struct cache_block *);
619 +void *cache_zero (struct cache_block *);
620 +void cache_dirty (struct cache_block *);
621 +void cache_unlock (struct cache_block *);
622 +void cache_free (disk_sector_t);
623 +void cache_readahead (disk_sector_t);
624 +
625 +#endif /* filesys/cache.h */
626 Index: src/filesys/directory.c
627 diff -u src/filesys/directory.c~ src/filesys/directory.c
628 --- src/filesys/directory.c~
629 +++ src/filesys/directory.c
630 @@ -20,21 +20,13 @@ struct dir_entry 
631      bool in_use;                        /* In use or free? */
632    };
633  
634 -/* Creates a directory with space for ENTRY_CNT entries in the
635 -   given SECTOR.  Returns true if successful, false on failure. */
636 -bool
637 -dir_create (disk_sector_t sector, size_t entry_cnt) 
638 -{
639 -  return inode_create (sector, entry_cnt * sizeof (struct dir_entry));
640 -}
641 -
642  /* Opens and returns the directory for the given INODE, of which
643     it takes ownership.  Returns a null pointer on failure. */
644  struct dir *
645  dir_open (struct inode *inode) 
646  {
647    struct dir *dir = calloc (1, sizeof *dir);
648 -  if (inode != NULL && dir != NULL)
649 +  if (inode != NULL && dir != NULL && inode_get_type (inode) == DIR_INODE)
650      {
651        dir->inode = inode;
652        return dir;
653 @@ -67,10 +67,8 @@ dir_close (struct dir *dir) 
654  }
655  
656  /* Searches DIR for a file with the given NAME.
657 -   If successful, returns true, sets *EP to the directory entry
658 -   if EP is non-null, and sets *OFSP to the byte offset of the
659 -   directory entry if OFSP is non-null.
660 -   otherwise, returns false and ignores EP and OFSP. */
661 +   If successful, returns the file's entry;
662 +   otherwise, returns a null pointer. */
663  static bool
664  lookup (const struct dir *dir, const char *name,
665          struct dir_entry *ep, off_t *ofsp) 
666 @@ -107,10 +105,12 @@ dir_lookup (const struct dir *dir, const
667    ASSERT (dir != NULL);
668    ASSERT (name != NULL);
669  
670 +  inode_lock (dir->inode);
671    if (lookup (dir, name, &e, NULL))
672      *inode = inode_open (e.inode_sector);
673    else
674      *inode = NULL;
675 +  inode_unlock (dir->inode);
676  
677    return *inode != NULL;
678  }
679 @@ -132,10 +132,11 @@ dir_add (struct dir *dir, const char *na
680    ASSERT (name != NULL);
681  
682    /* Check NAME for validity. */
683 -  if (*name == '\0' || strlen (name) > NAME_MAX)
684 +  if (*name == '\0' || strchr (name, '/') || strlen (name) > NAME_MAX)
685      return false;
686  
687    /* Check that NAME is not in use. */
688 +  inode_lock (dir->inode);
689    if (lookup (dir, name, NULL, NULL))
690      goto done;
691  
692 @@ -158,6 +159,7 @@ dir_add (struct dir *dir, const char *na
693    success = inode_write_at (dir->inode, &e, sizeof e, ofs) == sizeof e;
694  
695   done:
696 +  inode_unlock (dir->inode);
697    return success;
698  }
699  
700 @@ -176,12 +178,14 @@ dir_remove (struct dir *dir, const char 
701    ASSERT (name != NULL);
702  
703    /* Find directory entry. */
704 +  inode_lock (dir->inode);
705    if (!lookup (dir, name, &e, &ofs))
706      goto done;
707  
708 -  /* Open inode. */
709 +  /* Open inode and verify that it is not an in-use directory. */
710    inode = inode_open (e.inode_sector);
711 -  if (inode == NULL)
712 +  if (inode == NULL
713 +      || (inode_get_type (inode) == DIR_INODE && inode_open_cnt (inode) != 1))
714      goto done;
715  
716    /* Erase directory entry. */
717 @@ -195,6 +199,7 @@ dir_remove (struct dir *dir, const char 
718  
719   done:
720    inode_close (inode);
721 +  inode_unlock (dir->inode);
722    return success;
723  }
724  
725 @@ -216,14 +216,17 @@
726  {
727    struct dir_entry e;
728  
729 +  inode_lock (dir->inode);
730    while (inode_read_at (dir->inode, &e, sizeof e, dir->pos) == sizeof e) 
731      {
732        dir->pos += sizeof e;
733        if (e.in_use)
734          {
735            strlcpy (name, e.name, NAME_MAX + 1);
736 +          inode_unlock (dir->inode);
737            return true;
738          } 
739      }
740 +  inode_unlock (dir->inode);
741    return false;
742  }
743 Index: src/filesys/directory.h
744 diff -u src/filesys/directory.h~ src/filesys/directory.h
745 --- src/filesys/directory.h~
746 +++ src/filesys/directory.h
747 @@ -12,6 +11,5 @@
748  struct inode;
749  
750  /* Opening and closing directories. */
751 -bool dir_create (disk_sector_t sector, size_t entry_cnt);
752  struct dir *dir_open (struct inode *);
753  struct dir *dir_open_root (void);
754 Index: src/filesys/file.c
755 diff -u src/filesys/file.c~ src/filesys/file.c
756 --- src/filesys/file.c~
757 +++ src/filesys/file.c
758 @@ -18,7 +18,7 @@ struct file *
759  file_open (struct inode *inode) 
760  {
761    struct file *file = calloc (1, sizeof *file);
762 -  if (inode != NULL && file != NULL)
763 +  if (inode != NULL && file != NULL && inode_get_type (inode) == FILE_INODE)
764      {
765        file->inode = inode;
766        file->pos = 0;
767 Index: src/filesys/filesys.c
768 diff -u src/filesys/filesys.c~ src/filesys/filesys.c
769 --- src/filesys/filesys.c~
770 +++ src/filesys/filesys.c
771 @@ -2,11 +2,13 @@
772  #include <debug.h>
773  #include <stdio.h>
774  #include <string.h>
775 +#include "filesys/cache.h"
776  #include "filesys/file.h"
777  #include "filesys/free-map.h"
778  #include "filesys/inode.h"
779  #include "filesys/directory.h"
780  #include "devices/disk.h"
781 +#include "threads/thread.h"
782  
783  /* The disk that contains the file system. */
784  struct disk *filesys_disk;
785 @@ -23,6 +25,7 @@ filesys_init (bool format) 
786      PANIC ("hd0:1 (hdb) not present, file system initialization failed");
787  
788    inode_init ();
789 +  cache_init ();
790    free_map_init ();
791  
792    if (format) 
793 @@ -37,6 +40,99 @@ void
794  filesys_done (void) 
795  {
796    free_map_close ();
797 +  cache_flush ();
798 +}
799 +\f
800 +/* Extracts a file name part from *SRCP into PART,
801 +   and updates *SRCP so that the next call will return the next
802 +   file name part.
803 +   Returns 1 if successful, 0 at end of string, -1 for a too-long
804 +   file name part. */
805 +static int
806 +get_next_part (char part[NAME_MAX], const char **srcp)
807 +{
808 +  const char *src = *srcp;
809 +  char *dst = part;
810 +
811 +  /* Skip leading slashes.
812 +     If it's all slashes, we're done. */
813 +  while (*src == '/')
814 +    src++;
815 +  if (*src == '\0')
816 +    return 0;
817 +
818 +  /* Copy up to NAME_MAX character from SRC to DST.
819 +     Add null terminator. */
820 +  while (*src != '/' && *src != '\0') 
821 +    {
822 +      if (dst < part + NAME_MAX)
823 +        *dst++ = *src;
824 +      else
825 +        return -1;
826 +      src++; 
827 +    }
828 +  *dst = '\0';
829 +
830 +  /* Advance source pointer. */
831 +  *srcp = src;
832 +  return 1;
833 +}
834 +
835 +/* Resolves relative or absolute file NAME.
836 +   Returns true if successful, false on failure.
837 +   Stores the directory corresponding to the name into *DIRP,
838 +   and the file name part into BASE_NAME. */
839 +static bool
840 +resolve_name (const char *name,
841 +              struct dir **dirp, char base_name[NAME_MAX + 1]) 
842 +{
843 +  struct dir *dir = NULL;
844 +  struct inode *inode;
845 +  const char *cp;
846 +  char part[NAME_MAX + 1], next_part[NAME_MAX + 1];
847 +  int ok;
848 +
849 +  /* Find starting directory. */
850 +  if (name[0] == '/' || thread_current ()->wd == NULL)
851 +    dir = dir_open_root ();
852 +  else
853 +    dir = dir_reopen (thread_current ()->wd);
854 +  if (dir == NULL)
855 +    goto error;
856 +
857 +  /* Get first name part. */
858 +  cp = name;
859 +  if (get_next_part (part, &cp) <= 0)
860 +    goto error;
861 +
862 +  /* As long as another part follows the current one,
863 +     traverse down another directory. */
864 +  while ((ok = get_next_part (next_part, &cp)) > 0)
865 +    {
866 +      if (!dir_lookup (dir, part, &inode))
867 +        goto error;
868 +
869 +      dir_close (dir);
870 +      dir = dir_open (inode);
871 +      if (dir == NULL)
872 +        goto error;
873 +
874 +      strlcpy (part, next_part, NAME_MAX + 1);
875 +    }
876 +  if (ok < 0)
877 +    goto error;
878 +
879 +  /* Return our results. */
880 +  *dirp = dir;
881 +  strlcpy (base_name, part, NAME_MAX + 1);
882 +  return true;
883 +
884 + error:
885 +  /* Return failure. */
886 +  dir_close (dir);
887 +  *dirp = NULL;
888 +  base_name[0] = '\0';
889 +  return false;
890  }
891  \f
892  /* Creates a file named NAME with the given INITIAL_SIZE.
893 @@ -44,16 +140,17 @@ filesys_done (void) 
894     Fails if a file named NAME already exists,
895     or if internal memory allocation fails. */
896  bool
897 -filesys_create (const char *name, off_t initial_size) 
898 +filesys_create (const char *name, off_t initial_size, enum inode_type type) 
899  {
900 +  struct dir *dir;
901 +  char base_name[NAME_MAX + 1];
902    disk_sector_t inode_sector = 0;
903 -  struct dir *dir = dir_open_root ();
904 -  bool success = (dir != NULL
905 -                  && free_map_allocate (1, &inode_sector)
906 -                  && inode_create (inode_sector, initial_size)
907 -                  && dir_add (dir, name, inode_sector));
908 +  bool success = (resolve_name (name, &dir, base_name)
909 +                  && free_map_allocate (&inode_sector)
910 +                  && inode_create (inode_sector, initial_size, type)
911 +                  && dir_add (dir, base_name, inode_sector));
912    if (!success && inode_sector != 0) 
913 -    free_map_release (inode_sector, 1);
914 +    free_map_release (inode_sector);
915    dir_close (dir);
916  
917    return success;
918 @@ -64,17 +161,22 @@ filesys_create (const char *name, off_t 
919     otherwise.
920     Fails if no file named NAME exists,
921     or if an internal memory allocation fails. */
922 -struct file *
923 +struct inode *
924  filesys_open (const char *name)
925  {
926 -  struct dir *dir = dir_open_root ();
927 +  struct dir *dir = NULL;
928 +  char base_name[NAME_MAX + 1];
929    struct inode *inode = NULL;
930  
931 -  if (dir != NULL)
932 -    dir_lookup (dir, name, &inode);
933 +  if (!strcmp (name, "/"))
934 +    inode = inode_open (ROOT_DIR_SECTOR);
935 +  else if (!strcmp (name, "."))
936 +    inode = inode_reopen (dir_get_inode (thread_current ()->wd));
937 +  else if (resolve_name (name, &dir, base_name))
938 +    dir_lookup (dir, base_name, &inode);
939    dir_close (dir);
940  
941 -  return file_open (inode);
942 +  return inode;
943  }
944  
945  /* Deletes the file named NAME.
946 @@ -84,7 +182,11 @@ filesys_open (const char *name)
947  bool
948  filesys_remove (const char *name) 
949  {
950 -  struct dir *dir = dir_open_root ();
951 -  bool success = dir != NULL && dir_remove (dir, name);
952 +  struct dir *dir = NULL;
953 +  char base_name[NAME_MAX + 1];
954 +  bool success = false;
955 +
956 +  if (resolve_name (name, &dir, base_name)) 
957 +    success = dir_remove (dir, base_name);
958    dir_close (dir); 
959  
960 @@ -91,5 +193,44 @@
961    return success;
962  }
963 +/* Change current directory to NAME.
964 +   Return true if successful, false on failure. */
965 +bool
966 +filesys_chdir (const char *name) 
967 +{
968 +  struct dir *dir;
969 +
970 +  /* Find new directory. */
971 +  if (*name == '\0')
972 +    return false;
973 +  else if (name[strspn (name, "/")] == '\0')
974 +    {
975 +      dir = dir_open_root ();
976 +      if (dir == NULL)
977 +        return false; 
978 +    }
979 +  else 
980 +    {
981 +      char base_name[NAME_MAX + 1];
982 +      struct inode *base_inode;
983 +      struct dir *base_dir;
984 +      if (!resolve_name (name, &dir, base_name)
985 +          || !dir_lookup (dir, base_name, &base_inode)
986 +          || (base_dir = dir_open (base_inode)) == NULL)
987 +        {
988 +          dir_close (dir);
989 +          return false;
990 +        }
991 +      dir_close (dir);
992 +      dir = base_dir;
993 +    }
994 +
995 +  /* Change current directory. */
996 +  dir_close (thread_current ()->wd);
997 +  thread_current ()->wd = dir;
998 +  
999 +  return true;
1000 +}
1001 +
1002  \f
1003  static void must_succeed_function (int, bool) NO_INLINE;
1004  #define MUST_SUCCEED(EXPR) must_succeed_function (__LINE__, EXPR)
1005 @@ -129,8 +264,8 @@ filesys_self_test (void)
1006      {
1007        /* Create file and check that it contains zeros
1008           throughout the created length. */
1009 -      MUST_SUCCEED (filesys_create ("foo", sizeof s));
1010 -      MUST_SUCCEED ((file = filesys_open ("foo")) != NULL);
1011 +      MUST_SUCCEED (filesys_create ("foo", sizeof s, FILE_INODE));
1012 +      MUST_SUCCEED ((file = file_open (filesys_open ("foo"))) != NULL);
1013        MUST_SUCCEED (file_read (file, s2, sizeof s2) == sizeof s2);
1014        MUST_SUCCEED (memcmp (s2, zeros, sizeof s) == 0);
1015        MUST_SUCCEED (file_tell (file) == sizeof s);
1016 @@ -138,7 +273,7 @@ filesys_self_test (void)
1017        file_close (file);
1018  
1019        /* Reopen file and write to it. */
1020 -      MUST_SUCCEED ((file = filesys_open ("foo")) != NULL);
1021 +      MUST_SUCCEED ((file = file_open (filesys_open ("foo"))) != NULL);
1022        MUST_SUCCEED (file_write (file, s, sizeof s) == sizeof s);
1023        MUST_SUCCEED (file_tell (file) == sizeof s);
1024        MUST_SUCCEED (file_length (file) == sizeof s);
1025 @@ -146,7 +281,7 @@ filesys_self_test (void)
1026  
1027        /* Reopen file and verify that it reads back correctly.
1028           Delete file while open to check proper semantics. */
1029 -      MUST_SUCCEED ((file = filesys_open ("foo")) != NULL);
1030 +      MUST_SUCCEED ((file = file_open (filesys_open ("foo"))) != NULL);
1031        MUST_SUCCEED (filesys_remove ("foo"));
1032        MUST_SUCCEED (filesys_open ("foo") == NULL);
1033        MUST_SUCCEED (file_read (file, s2, sizeof s) == sizeof s);
1034 @@ -173,9 +308,13 @@ static void
1035  do_format (void)
1036  {
1037    printf ("Formatting file system...");
1038 +
1039 +  /* Set up free map. */
1040    free_map_create ();
1041 -  if (!dir_create (ROOT_DIR_SECTOR, 16))
1042 +
1043 +  /* Set up root directory. */
1044 +  if (!inode_create (ROOT_DIR_SECTOR, 0, DIR_INODE))
1045      PANIC ("root directory creation failed");
1046 -  free_map_close ();
1047 +
1048    printf ("done.\n");
1049  }
1050 Index: src/filesys/filesys.h
1051 diff -u src/filesys/filesys.h~ src/filesys/filesys.h
1052 --- src/filesys/filesys.h~
1053 +++ src/filesys/filesys.h
1054 @@ -3,6 +3,7 @@
1055  
1056  #include <stdbool.h>
1057  #include "filesys/off_t.h"
1058 +#include "filesys/inode.h"
1059  
1060  /* Sectors of system file inodes. */
1061  #define FREE_MAP_SECTOR 0       /* Free map file inode sector. */
1062 @@ -13,9 +14,10 @@ extern struct disk *filesys_disk;
1063  
1064  void filesys_init (bool format);
1065  void filesys_done (void);
1066 -bool filesys_create (const char *name, off_t initial_size);
1067 -struct file *filesys_open (const char *name);
1068 +bool filesys_create (const char *name, off_t initial_size, enum inode_type);
1069 +struct inode *filesys_open (const char *name);
1070  bool filesys_remove (const char *name);
1071 +bool filesys_chdir (const char *name);
1072  
1073  void filesys_self_test (void);
1074  
1075 Index: src/filesys/free-map.c
1076 diff -u src/filesys/free-map.c~ src/filesys/free-map.c
1077 --- src/filesys/free-map.c~
1078 +++ src/filesys/free-map.c
1079 @@ -3,15 +3,18 @@
1080  #include <debug.h>
1081  #include "filesys/file.h"
1082  #include "filesys/filesys.h"
1083 -#include "filesys/inode.h"
1084 +#include "threads/synch.h"
1085  
1086  static struct file *free_map_file;   /* Free map file. */
1087  static struct bitmap *free_map;      /* Free map, one bit per disk sector. */
1088 +static struct lock free_map_lock;    /* Mutual exclusion. */
1089  
1090  /* Initializes the free map. */
1091  void
1092  free_map_init (void) 
1093  {
1094 +  lock_init (&free_map_lock);
1095 +
1096    free_map = bitmap_create (disk_size (filesys_disk));
1097    if (free_map == NULL)
1098      PANIC ("bitmap creation failed--disk is too large");
1099 @@ -19,33 +22,32 @@ free_map_init (void) 
1100    bitmap_mark (free_map, ROOT_DIR_SECTOR);
1101  }
1102  
1103 -/* Allocates CNT consecutive sectors from the free map and stores
1104 -   the first into *SECTORP.
1105 -   Returns true if successful, false if all sectors were
1106 +/* Allocates a sector from the free map and stores it into
1107 +   *SECTORP.
1108 +   Return true if successful, false if all sectors were
1109     available. */
1110  bool
1111 -free_map_allocate (size_t cnt, disk_sector_t *sectorp) 
1112 +free_map_allocate (disk_sector_t *sectorp) 
1113  {
1114 -  disk_sector_t sector = bitmap_scan_and_flip (free_map, 0, cnt, false);
1115 -  if (sector != BITMAP_ERROR
1116 -      && free_map_file != NULL
1117 -      && !bitmap_write (free_map, free_map_file))
1118 -    {
1119 -      bitmap_set_multiple (free_map, sector, cnt, false); 
1120 -      sector = BITMAP_ERROR;
1121 -    }
1122 -  if (sector != BITMAP_ERROR)
1123 +  size_t sector;
1124 +  
1125 +  lock_acquire (&free_map_lock);
1126 +  sector = bitmap_scan_and_flip (free_map, 0, 1, false);
1127 +  lock_release (&free_map_lock);
1128 +
1129 +  if (sector != BITMAP_ERROR) 
1130      *sectorp = sector;
1131    return sector != BITMAP_ERROR;
1132  }
1133  
1134 -/* Makes CNT sectors starting at SECTOR available for use. */
1135 +/* Makes SECTOR available for use. */
1136  void
1137 -free_map_release (disk_sector_t sector, size_t cnt)
1138 +free_map_release (disk_sector_t sector)
1139  {
1140 -  ASSERT (bitmap_all (free_map, sector, cnt));
1141 -  bitmap_set_multiple (free_map, sector, cnt, false);
1142 -  bitmap_write (free_map, free_map_file);
1143 +  lock_acquire (&free_map_lock);
1144 +  ASSERT (bitmap_test (free_map, sector));
1145 +  bitmap_reset (free_map, sector);
1146 +  lock_release (&free_map_lock);
1147  }
1148  
1149  /* Opens the free map file and reads it from disk. */
1150 @@ -63,6 +65,8 @@ free_map_open (void) 
1151  void
1152  free_map_close (void) 
1153  {
1154 +  if (!bitmap_write (free_map, free_map_file))
1155 +    PANIC ("can't write free map");
1156    file_close (free_map_file);
1157  }
1158  
1159 @@ -72,7 +76,7 @@ void
1160  free_map_create (void) 
1161  {
1162    /* Create inode. */
1163 -  if (!inode_create (FREE_MAP_SECTOR, bitmap_file_size (free_map)))
1164 +  if (!inode_create (FREE_MAP_SECTOR, bitmap_file_size (free_map), FILE_INODE))
1165      PANIC ("free map creation failed");
1166  
1167    /* Write bitmap to file. */
1168 @@ -81,4 +85,5 @@ free_map_create (void) 
1169      PANIC ("can't open free map");
1170    if (!bitmap_write (free_map, free_map_file))
1171      PANIC ("can't write free map");
1172 +  file_close (free_map_file);
1173  }
1174 Index: src/filesys/free-map.h
1175 diff -u src/filesys/free-map.h~ src/filesys/free-map.h
1176 --- src/filesys/free-map.h~
1177 +++ src/filesys/free-map.h
1178 @@ -11,7 +11,7 @@ void free_map_create (void);
1179  void free_map_open (void);
1180  void free_map_close (void);
1181  
1182 -bool free_map_allocate (size_t, disk_sector_t *);
1183 -void free_map_release (disk_sector_t, size_t);
1184 +bool free_map_allocate (disk_sector_t *);
1185 +void free_map_release (disk_sector_t);
1186  
1187  #endif /* filesys/free-map.h */
1188 Index: src/filesys/fsutil.c
1189 diff -u src/filesys/fsutil.c~ src/filesys/fsutil.c
1190 --- src/filesys/fsutil.c~
1191 +++ src/filesys/fsutil.c
1192 @@ -30,7 +30,7 @@ fsutil_cat (char **argv)
1193    char *buffer;
1194  
1195    printf ("Printing '%s' to the console...\n", file_name);
1196 -  file = filesys_open (file_name);
1197 +  file = file_open (filesys_open (file_name));
1198    if (file == NULL)
1199      PANIC ("%s: open failed", file_name);
1200    buffer = palloc_get_page (PAL_ASSERT);
1201 @@ -102,9 +102,9 @@ fsutil_put (char **argv) 
1202      PANIC ("%s: invalid file size %d", file_name, size);
1203    
1204    /* Create destination file. */
1205 -  if (!filesys_create (file_name, size))
1206 +  if (!filesys_create (file_name, size, FILE_INODE))
1207      PANIC ("%s: create failed", file_name);
1208 -  dst = filesys_open (file_name);
1209 +  dst = file_open (filesys_open (file_name));
1210    if (dst == NULL)
1211      PANIC ("%s: open failed", file_name);
1212  
1213 @@ -154,7 +154,7 @@ fsutil_get (char **argv)
1214      PANIC ("couldn't allocate buffer");
1215  
1216    /* Open source file. */
1217 -  src = filesys_open (file_name);
1218 +  src = file_open (filesys_open (file_name));
1219    if (src == NULL)
1220      PANIC ("%s: open failed", file_name);
1221    size = file_length (src);
1222 Index: src/filesys/inode.c
1223 diff -u src/filesys/inode.c~ src/filesys/inode.c
1224 --- src/filesys/inode.c~
1225 +++ src/filesys/inode.c
1226 @@ -1,23 +1,38 @@
1227  #include "filesys/inode.h"
1228 +#include <bitmap.h>
1229  #include <list.h>
1230  #include <debug.h>
1231  #include <round.h>
1232 +#include <stdio.h>
1233  #include <string.h>
1234 +#include "filesys/cache.h"
1235  #include "filesys/filesys.h"
1236  #include "filesys/free-map.h"
1237  #include "threads/malloc.h"
1238 +#include "threads/synch.h"
1239  
1240  /* Identifies an inode. */
1241  #define INODE_MAGIC 0x494e4f44
1242  
1243 +#define DIRECT_CNT 123
1244 +#define INDIRECT_CNT 1
1245 +#define DBL_INDIRECT_CNT 1
1246 +#define SECTOR_CNT (DIRECT_CNT + INDIRECT_CNT + DBL_INDIRECT_CNT)
1247 +
1248 +#define PTRS_PER_SECTOR ((off_t) (DISK_SECTOR_SIZE / sizeof (disk_sector_t))) 
1249 +#define INODE_SPAN ((DIRECT_CNT                                              \
1250 +                     + PTRS_PER_SECTOR * INDIRECT_CNT                        \
1251 +                     + PTRS_PER_SECTOR * PTRS_PER_SECTOR * DBL_INDIRECT_CNT) \
1252 +                    * DISK_SECTOR_SIZE)
1253 +
1254  /* On-disk inode.
1255     Must be exactly DISK_SECTOR_SIZE bytes long. */
1256  struct inode_disk
1257    {
1258 -    disk_sector_t start;                /* First data sector. */
1259 +    disk_sector_t sectors[SECTOR_CNT];  /* Sectors. */
1260 +    enum inode_type type;               /* FILE_INODE or DIR_INODE. */
1261      off_t length;                       /* File size in bytes. */
1262      unsigned magic;                     /* Magic number. */
1263 -    uint32_t unused[125];               /* Not used. */
1264    };
1265  
1266  /* Returns the number of sectors to allocate for an inode SIZE
1267 @@ -35,33 +50,30 @@ struct inode 
1268      disk_sector_t sector;               /* Sector number of disk location. */
1269      int open_cnt;                       /* Number of openers. */
1270      bool removed;                       /* True if deleted, false otherwise. */
1271 +    struct lock lock;                   /* Protects the inode. */
1272 +
1273 +    /* Denying writes. */
1274 +    struct lock deny_write_lock;        /* Protects members below. */
1275 +    struct condition no_writers_cond;   /* Signaled when no writers. */ 
1276      int deny_write_cnt;                 /* 0: writes ok, >0: deny writes. */
1277 -    struct inode_disk data;             /* Inode content. */
1278 +    int writer_cnt;                     /* Number of writers. */
1279    };
1280  
1281 -/* Returns the disk sector that contains byte offset POS within
1282 -   INODE.
1283 -   Returns -1 if INODE does not contain data for a byte at offset
1284 -   POS. */
1285 -static disk_sector_t
1286 -byte_to_sector (const struct inode *inode, off_t pos) 
1287 -{
1288 -  ASSERT (inode != NULL);
1289 -  if (pos < inode->data.length)
1290 -    return inode->data.start + pos / DISK_SECTOR_SIZE;
1291 -  else
1292 -    return -1;
1293 -}
1294 -
1295  /* List of open inodes, so that opening a single inode twice
1296     returns the same `struct inode'. */
1297  static struct list open_inodes;
1298  
1299 +/* Controls access to open_inodes list. */
1300 +static struct lock open_inodes_lock;
1301 +
1302 +static void deallocate_inode (const struct inode *);
1303 +
1304  /* Initializes the inode module. */
1305  void
1306  inode_init (void) 
1307  {
1308    list_init (&open_inodes);
1309 +  lock_init (&open_inodes_lock);
1310  }
1311  
1312  /* Initializes an inode with LENGTH bytes of data and
1313 @@ -70,38 +82,35 @@ inode_init (void) 
1314     Returns true if successful.
1315     Returns false if memory or disk allocation fails. */
1316  bool
1317 -inode_create (disk_sector_t sector, off_t length)
1318 +inode_create (disk_sector_t sector, off_t length, enum inode_type type) 
1319  {
1320 -  struct inode_disk *disk_inode = NULL;
1321 -  bool success = false;
1322 +  struct cache_block *block;
1323 +  struct inode_disk *disk_inode;
1324 +  bool success;
1325  
1326    ASSERT (length >= 0);
1327  
1328 +  block = cache_lock (sector, EXCLUSIVE);
1329 +
1330    /* If this assertion fails, the inode structure is not exactly
1331       one sector in size, and you should fix that. */
1332    ASSERT (sizeof *disk_inode == DISK_SECTOR_SIZE);
1333 +  disk_inode = cache_zero (block);
1334 +  disk_inode->type = type;
1335 +  disk_inode->length = 0;
1336 +  disk_inode->magic = INODE_MAGIC;
1337 +  cache_dirty (block);
1338 +  cache_unlock (block);
1339  
1340 -  disk_inode = calloc (1, sizeof *disk_inode);
1341 -  if (disk_inode != NULL)
1342 +  if (length > 0) 
1343      {
1344 -      size_t sectors = bytes_to_sectors (length);
1345 -      disk_inode->length = length;
1346 -      disk_inode->magic = INODE_MAGIC;
1347 -      if (free_map_allocate (sectors, &disk_inode->start))
1348 -        {
1349 -          disk_write (filesys_disk, sector, disk_inode);
1350 -          if (sectors > 0) 
1351 -            {
1352 -              static char zeros[DISK_SECTOR_SIZE];
1353 -              size_t i;
1354 -              
1355 -              for (i = 0; i < sectors; i++) 
1356 -                disk_write (filesys_disk, disk_inode->start + i, zeros); 
1357 -            }
1358 -          success = true; 
1359 -        } 
1360 -      free (disk_inode);
1361 +      struct inode *inode = inode_open (sector);
1362 +      success = inode != NULL && inode_write_at (inode, "", 1, length - 1);
1363 +      inode_close (inode);
1364      }
1365 +  else
1366 +    success = true;
1367 +
1368    return success;
1369  }
1370  
1371 @@ -115,6 +124,7 @@ inode_open (disk_sector_t sector) 
1372    struct inode *inode;
1373  
1374    /* Check whether this inode is already open. */
1375 +  lock_acquire (&open_inodes_lock);
1376    for (e = list_begin (&open_inodes); e != list_end (&open_inodes);
1377         e = list_next (e)) 
1378      {
1379 @@ -122,22 +132,27 @@ inode_open (disk_sector_t sector) 
1380        if (inode->sector == sector) 
1381          {
1382            inode_reopen (inode);
1383 -          return inode; 
1384 +          goto done; 
1385          }
1386      }
1387  
1388    /* Allocate memory. */
1389    inode = malloc (sizeof *inode);
1390    if (inode == NULL)
1391 -    return NULL;
1392 +    goto done;
1393  
1394    /* Initialize. */
1395    list_push_front (&open_inodes, &inode->elem);
1396    inode->sector = sector;
1397    inode->open_cnt = 1;
1398 +  lock_init (&inode->lock);
1399    inode->deny_write_cnt = 0;
1400 +  lock_init (&inode->deny_write_lock);
1401 +  cond_init (&inode->no_writers_cond);
1402    inode->removed = false;
1403 -  disk_read (filesys_disk, inode->sector, &inode->data);
1404 +  
1405 + done:
1406 +  lock_release (&open_inodes_lock);
1407    return inode;
1408  }
1409  
1410 @@ -146,10 +161,25 @@ struct inode *
1411  inode_reopen (struct inode *inode) 
1412  {
1413    if (inode != NULL) 
1414 -    inode->open_cnt++;
1415 +    {
1416 +      inode_lock (inode);
1417 +      inode->open_cnt++;
1418 +      inode_unlock (inode); 
1419 +    }
1420    return inode;
1421  }
1422  
1423 +/* Returns the type of INODE. */
1424 +enum inode_type
1425 +inode_get_type (const struct inode *inode) 
1426 +{
1427 +  struct cache_block *inode_block = cache_lock (inode->sector, NON_EXCLUSIVE);
1428 +  struct inode_disk *disk_inode = cache_read (inode_block);
1429 +  enum inode_type type = disk_inode->type;
1430 +  cache_unlock (inode_block);
1431 +  return type;
1432 +}
1433 +
1434  /* Closes INODE and writes it to disk.
1435     If this was the last reference to INODE, frees its memory.
1436     If INODE was also a removed inode, frees its blocks. */
1437 @@ -161,21 +191,60 @@ inode_close (struct inode *inode) 
1438      return;
1439  
1440    /* Release resources if this was the last opener. */
1441 +  lock_acquire (&open_inodes_lock);
1442    if (--inode->open_cnt == 0)
1443      {
1444        /* Remove from inode list and release lock. */
1445        list_remove (&inode->elem);
1446 +      lock_release (&open_inodes_lock);
1447   
1448        /* Deallocate blocks if removed. */
1449        if (inode->removed) 
1450 -        {
1451 -          free_map_release (inode->sector, 1);
1452 -          free_map_release (inode->data.start,
1453 -                            bytes_to_sectors (inode->data.length)); 
1454 -        }
1455 +        deallocate_inode (inode);
1456  
1457        free (inode); 
1458      }
1459 +  else
1460 +    lock_release (&open_inodes_lock);
1461 +}
1462 +
1463 +/* Deallocates SECTOR and anything it points to recursively.
1464 +   LEVEL is 2 if SECTOR is doubly indirect,
1465 +   or 1 if SECTOR is indirect,
1466 +   or 0 if SECTOR is a data sector. */
1467 +static void
1468 +deallocate_recursive (disk_sector_t sector, int level) 
1469 +{
1470 +  if (level > 0) 
1471 +    {
1472 +      struct cache_block *block = cache_lock (sector, EXCLUSIVE);
1473 +      disk_sector_t *pointers = cache_read (block);
1474 +      int i;
1475 +      for (i = 0; i < PTRS_PER_SECTOR; i++)
1476 +        if (pointers[i])
1477 +          deallocate_recursive (sector, level - 1);
1478 +      cache_unlock (block);
1479 +    }
1480 +  
1481 +  cache_free (sector);
1482 +  free_map_release (sector);
1483 +}
1484 +
1485 +/* Deallocates the blocks allocated for INODE. */
1486 +static void
1487 +deallocate_inode (const struct inode *inode)
1488 +{
1489 +  struct cache_block *block = cache_lock (inode->sector, EXCLUSIVE);
1490 +  struct inode_disk *disk_inode = cache_read (block);
1491 +  int i;
1492 +  for (i = 0; i < SECTOR_CNT; i++)
1493 +    if (disk_inode->sectors[i]) 
1494 +      {
1495 +        int level = (i >= DIRECT_CNT) + (i >= DIRECT_CNT + INDIRECT_CNT);
1496 +        deallocate_recursive (disk_inode->sectors[i], level); 
1497 +      }
1498 +  cache_unlock (block);
1499 +  deallocate_recursive (inode->sector, 0);
1500  }
1501  
1502  /* Marks INODE to be deleted when it is closed by the last caller who
1503 @@ -187,6 +256,156 @@ inode_remove (struct inode *inode) 
1504    inode->removed = true;
1505  }
1506  
1507 +/* Translates SECTOR_IDX into a sequence of block indexes in
1508 +   OFFSETS and sets *OFFSET_CNT to the number of offsets. */
1509 +static void
1510 +calculate_indices (off_t sector_idx, size_t offsets[], size_t *offset_cnt)
1511 +{
1512 +  /* Handle direct blocks. */
1513 +  if (sector_idx < DIRECT_CNT) 
1514 +    {
1515 +      offsets[0] = sector_idx;
1516 +      *offset_cnt = 1;
1517 +      return;
1518 +    }
1519 +  sector_idx -= DIRECT_CNT;
1520 +
1521 +  /* Handle indirect blocks. */
1522 +  if (sector_idx < PTRS_PER_SECTOR * INDIRECT_CNT)
1523 +    {
1524 +      offsets[0] = DIRECT_CNT + sector_idx / PTRS_PER_SECTOR;
1525 +      offsets[1] = sector_idx % PTRS_PER_SECTOR;
1526 +      *offset_cnt = 2;
1527 +      return;
1528 +    }
1529 +  sector_idx -= PTRS_PER_SECTOR * INDIRECT_CNT;
1530 +
1531 +  /* Handle doubly indirect blocks. */
1532 +  if (sector_idx < DBL_INDIRECT_CNT * PTRS_PER_SECTOR * PTRS_PER_SECTOR)
1533 +    {
1534 +      offsets[0] = (DIRECT_CNT + INDIRECT_CNT
1535 +                    + sector_idx / (PTRS_PER_SECTOR * PTRS_PER_SECTOR));
1536 +      offsets[1] = sector_idx / PTRS_PER_SECTOR;
1537 +      offsets[2] = sector_idx % PTRS_PER_SECTOR;
1538 +      *offset_cnt = 3;
1539 +      return;
1540 +    }
1541 +  NOT_REACHED ();
1542 +}
1543 +
1544 +/* Retrieves the data block for the given byte OFFSET in INODE,
1545 +   setting *DATA_BLOCK to the block.
1546 +   Returns true if successful, false on failure.
1547 +   If ALLOCATE is false, then missing blocks will be successful
1548 +   with *DATA_BLOCk set to a null pointer.
1549 +   If ALLOCATE is true, then missing blocks will be allocated.
1550 +   The block returned will be locked, normally non-exclusively,
1551 +   but a newly allocated block will have an exclusive lock. */
1552 +static bool
1553 +get_data_block (struct inode *inode, off_t offset, bool allocate,
1554 +                struct cache_block **data_block) 
1555 +{
1556 +  disk_sector_t this_level_sector;
1557 +  size_t offsets[3];
1558 +  size_t offset_cnt;
1559 +  size_t level;
1560 +
1561 +  ASSERT (offset >= 0);
1562 +
1563 +  calculate_indices (offset / DISK_SECTOR_SIZE, offsets, &offset_cnt);
1564 +  level = 0;
1565 +  this_level_sector = inode->sector;
1566 +  for (;;) 
1567 +    {
1568 +      struct cache_block *this_level_block;
1569 +      uint32_t *this_level_data;
1570 +
1571 +      struct cache_block *next_level_block;
1572 +
1573 +      /* Check whether the block for the next level is allocated. */
1574 +      this_level_block = cache_lock (this_level_sector, NON_EXCLUSIVE);
1575 +      this_level_data = cache_read (this_level_block);
1576 +      if (this_level_data[offsets[level]] != 0)
1577 +        {
1578 +          /* Yes, it's allocated.  Advance to next level. */
1579 +          this_level_sector = this_level_data[offsets[level]];
1580 +
1581 +          if (++level == offset_cnt) 
1582 +            {
1583 +              /* We hit the data block.
1584 +                 Do read-ahead. */
1585 +              if ((level == 0 && offsets[level] + 1 < DIRECT_CNT)
1586 +                  || (level > 0 && offsets[level] + 1 < PTRS_PER_SECTOR)) 
1587 +                {
1588 +                  uint32_t next_sector = this_level_data[offsets[level] + 1];
1589 +                  if (next_sector && next_sector < disk_size (filesys_disk))
1590 +                    cache_readahead (next_sector); 
1591 +                }
1592 +              cache_unlock (this_level_block);
1593 +
1594 +              /* Return block. */
1595 +              *data_block = cache_lock (this_level_sector, NON_EXCLUSIVE);
1596 +              return true;
1597 +            }
1598 +          cache_unlock (this_level_block);
1599 +          continue;
1600 +        }
1601 +      cache_unlock (this_level_block);
1602 +
1603 +      /* No block is allocated.  Nothing is locked.
1604 +         If we're not allocating new blocks, then this is
1605 +         "success" (with all-zero data). */
1606 +      if (!allocate) 
1607 +        {
1608 +          *data_block = NULL;
1609 +          return true;
1610 +        }
1611 +
1612 +      /* We need to allocate a new block.
1613 +         Grab an exclusive lock on this level's block so we can
1614 +         insert the new block. */
1615 +      this_level_block = cache_lock (this_level_sector, EXCLUSIVE);
1616 +      this_level_data = cache_read (this_level_block);
1617 +
1618 +      /* Since we released this level's block, someone else might
1619 +         have allocated the block in the meantime.  Recheck. */
1620 +      if (this_level_data[offsets[level]] != 0)
1621 +        {
1622 +          cache_unlock (this_level_block);
1623 +          continue;
1624 +        }
1625 +
1626 +      /* Allocate the new block. */
1627 +      if (!free_map_allocate (&this_level_data[offsets[level]]))
1628 +        {
1629 +          cache_unlock (this_level_block);
1630 +          *data_block = NULL;
1631 +          return false;
1632 +        }
1633 +      cache_dirty (this_level_block);
1634 +
1635 +      /* Lock and clear the new block. */
1636 +      next_level_block = cache_lock (this_level_data[offsets[level]],
1637 +                                     EXCLUSIVE);
1638 +      cache_zero (next_level_block);
1639 +
1640 +      /* Release this level's block.  No one else can access the
1641 +         new block yet, because we have an exclusive lock on it. */
1642 +      cache_unlock (this_level_block);
1643 +
1644 +      /* If this is the final level, then return the new block. */
1645 +      if (level == offset_cnt - 1) 
1646 +        {
1647 +          *data_block = next_level_block;
1648 +          return true;
1649 +        }
1650 +
1651 +      /* Otherwise, release the new block and go around again to
1652 +         follow the new pointer. */
1653 +      cache_unlock (next_level_block);
1654 +    }
1655 +}
1656 +
1657  /* Reads SIZE bytes from INODE into BUFFER, starting at position OFFSET.
1658     Returns the number of bytes actually read, which may be less
1659     than SIZE if an error occurs or end of file is reached. */
1660 @@ -195,13 +414,12 @@ inode_read_at (struct inode *inode, void
1661  {
1662    uint8_t *buffer = buffer_;
1663    off_t bytes_read = 0;
1664 -  uint8_t *bounce = NULL;
1665  
1666    while (size > 0) 
1667      {
1668 -      /* Disk sector to read, starting byte offset within sector. */
1669 -      disk_sector_t sector_idx = byte_to_sector (inode, offset);
1670 +      /* Sector to read, starting byte offset within sector, sector data. */
1671        int sector_ofs = offset % DISK_SECTOR_SIZE;
1672 +      struct cache_block *block;
1673  
1674        /* Bytes left in inode, bytes left in sector, lesser of the two. */
1675        off_t inode_left = inode_length (inode) - offset;
1676 @@ -210,26 +428,16 @@ inode_read_at (struct inode *inode, void
1677  
1678        /* Number of bytes to actually copy out of this sector. */
1679        int chunk_size = size < min_left ? size : min_left;
1680 -      if (chunk_size <= 0)
1681 +      if (chunk_size <= 0 || !get_data_block (inode, offset, false, &block))
1682          break;
1683  
1684 -      if (sector_ofs == 0 && chunk_size == DISK_SECTOR_SIZE) 
1685 -        {
1686 -          /* Read full sector directly into caller's buffer. */
1687 -          disk_read (filesys_disk, sector_idx, buffer + bytes_read); 
1688 -        }
1689 +      if (block == NULL) 
1690 +        memset (buffer + bytes_read, 0, chunk_size);
1691        else 
1692          {
1693 -          /* Read sector into bounce buffer, then partially copy
1694 -             into caller's buffer. */
1695 -          if (bounce == NULL) 
1696 -            {
1697 -              bounce = malloc (DISK_SECTOR_SIZE);
1698 -              if (bounce == NULL)
1699 -                break;
1700 -            }
1701 -          disk_read (filesys_disk, sector_idx, bounce);
1702 -          memcpy (buffer + bytes_read, bounce + sector_ofs, chunk_size);
1703 +          const uint8_t *sector_data = cache_read (block);
1704 +          memcpy (buffer + bytes_read, sector_data + sector_ofs, chunk_size);
1705 +          cache_unlock (block);
1706          }
1707        
1708        /* Advance. */
1709 @@ -237,75 +445,84 @@ inode_read_at (struct inode *inode, void
1710        offset += chunk_size;
1711        bytes_read += chunk_size;
1712      }
1713 -  free (bounce);
1714  
1715    return bytes_read;
1716  }
1717  
1718 +/* Extends INODE to be at least LENGTH bytes long. */
1719 +static void
1720 +extend_file (struct inode *inode, off_t length) 
1721 +{
1722 +  if (length > inode_length (inode)) 
1723 +    {
1724 +      struct cache_block *inode_block = cache_lock (inode->sector, EXCLUSIVE);
1725 +      struct inode_disk *disk_inode = cache_read (inode_block);
1726 +      if (length > disk_inode->length) 
1727 +        {
1728 +          disk_inode->length = length;
1729 +          cache_dirty (inode_block);
1730 +        }
1731 +      cache_unlock (inode_block);
1732 +    }
1733 +}
1734 +
1735  /* Writes SIZE bytes from BUFFER into INODE, starting at OFFSET.
1736     Returns the number of bytes actually written, which may be
1737     less than SIZE if end of file is reached or an error occurs.
1738 -   (Normally a write at end of file would extend the inode, but
1739 -   growth is not yet implemented.) */
1740 +   (Normally a write at end of file would extend the file, but
1741 +   file growth is not yet implemented.) */
1742  off_t
1743  inode_write_at (struct inode *inode, const void *buffer_, off_t size,
1744                  off_t offset) 
1745  {
1746    const uint8_t *buffer = buffer_;
1747    off_t bytes_written = 0;
1748 -  uint8_t *bounce = NULL;
1749  
1750 -  if (inode->deny_write_cnt)
1751 -    return 0;
1752 +  /* Don't write if writes are denied. */
1753 +  lock_acquire (&inode->deny_write_lock);
1754 +  if (inode->deny_write_cnt) 
1755 +    {
1756 +      lock_release (&inode->deny_write_lock);
1757 +      return 0;
1758 +    }
1759 +  inode->writer_cnt++;
1760 +  lock_release (&inode->deny_write_lock);
1761  
1762    while (size > 0) 
1763      {
1764 -      /* Sector to write, starting byte offset within sector. */
1765 -      disk_sector_t sector_idx = byte_to_sector (inode, offset);
1766 +      /* Sector to write, starting byte offset within sector, sector data. */
1767        int sector_ofs = offset % DISK_SECTOR_SIZE;
1768 +      struct cache_block *block;
1769 +      uint8_t *sector_data;
1770  
1771 -      /* Bytes left in inode, bytes left in sector, lesser of the two. */
1772 -      off_t inode_left = inode_length (inode) - offset;
1773 +      /* Bytes to max inode size, bytes left in sector, lesser of the two. */
1774 +      off_t inode_left = INODE_SPAN - offset;
1775        int sector_left = DISK_SECTOR_SIZE - sector_ofs;
1776        int min_left = inode_left < sector_left ? inode_left : sector_left;
1777  
1778        /* Number of bytes to actually write into this sector. */
1779        int chunk_size = size < min_left ? size : min_left;
1780 -      if (chunk_size <= 0)
1781 -        break;
1782  
1783 -      if (sector_ofs == 0 && chunk_size == DISK_SECTOR_SIZE) 
1784 -        {
1785 -          /* Write full sector directly to disk. */
1786 -          disk_write (filesys_disk, sector_idx, buffer + bytes_written); 
1787 -        }
1788 -      else 
1789 -        {
1790 -          /* We need a bounce buffer. */
1791 -          if (bounce == NULL) 
1792 -            {
1793 -              bounce = malloc (DISK_SECTOR_SIZE);
1794 -              if (bounce == NULL)
1795 -                break;
1796 -            }
1797 +      if (chunk_size <= 0 || !get_data_block (inode, offset, true, &block))
1798 +        break;
1799  
1800 -          /* If the sector contains data before or after the chunk
1801 -             we're writing, then we need to read in the sector
1802 -             first.  Otherwise we start with a sector of all zeros. */
1803 -          if (sector_ofs > 0 || chunk_size < sector_left) 
1804 -            disk_read (filesys_disk, sector_idx, bounce);
1805 -          else
1806 -            memset (bounce, 0, DISK_SECTOR_SIZE);
1807 -          memcpy (bounce + sector_ofs, buffer + bytes_written, chunk_size);
1808 -          disk_write (filesys_disk, sector_idx, bounce); 
1809 -        }
1810 +      sector_data = cache_read (block);
1811 +      memcpy (sector_data + sector_ofs, buffer + bytes_written, chunk_size);
1812 +      cache_dirty (block);
1813 +      cache_unlock (block);
1814  
1815        /* Advance. */
1816        size -= chunk_size;
1817        offset += chunk_size;
1818        bytes_written += chunk_size;
1819      }
1820 -  free (bounce);
1821 +
1822 +  extend_file (inode, offset);
1823 +
1824 +  lock_acquire (&inode->deny_write_lock);
1825 +  if (--inode->writer_cnt == 0)
1826 +    cond_signal (&inode->no_writers_cond, &inode->deny_write_lock);
1827 +  lock_release (&inode->deny_write_lock);
1828  
1829    return bytes_written;
1830  }
1831 @@ -315,8 +532,12 @@ inode_write_at (struct inode *inode, con
1832  void
1833  inode_deny_write (struct inode *inode) 
1834  {
1835 +  lock_acquire (&inode->deny_write_lock);
1836 +  while (inode->writer_cnt > 0)
1837 +    cond_wait (&inode->no_writers_cond, &inode->deny_write_lock);
1838 +  ASSERT (inode->deny_write_cnt < inode->open_cnt);
1839    inode->deny_write_cnt++;
1840 -  ASSERT (inode->deny_write_cnt <= inode->open_cnt);
1841 +  lock_release (&inode->deny_write_lock);
1842  }
1843  
1844  /* Re-enables writes to INODE.
1845 @@ -325,14 +546,47 @@ inode_deny_write (struct inode *inode) 
1846  void
1847  inode_allow_write (struct inode *inode) 
1848  {
1849 +  lock_acquire (&inode->deny_write_lock);
1850    ASSERT (inode->deny_write_cnt > 0);
1851    ASSERT (inode->deny_write_cnt <= inode->open_cnt);
1852    inode->deny_write_cnt--;
1853 +  lock_release (&inode->deny_write_lock);
1854  }
1855  
1856  /* Returns the length, in bytes, of INODE's data. */
1857  off_t
1858  inode_length (const struct inode *inode)
1859  {
1860 -  return inode->data.length;
1861 +  struct cache_block *inode_block = cache_lock (inode->sector, NON_EXCLUSIVE);
1862 +  struct inode_disk *disk_inode = cache_read (inode_block);
1863 +  off_t length = disk_inode->length;
1864 +  cache_unlock (inode_block);
1865 +  return length;
1866 +}
1867 +
1868 +/* Returns the number of openers. */
1869 +int
1870 +inode_open_cnt (const struct inode *inode) 
1871 +{
1872 +  int open_cnt;
1873 +  
1874 +  lock_acquire (&open_inodes_lock);
1875 +  open_cnt = inode->open_cnt;
1876 +  lock_release (&open_inodes_lock);
1877 +
1878 +  return open_cnt;
1879 +}
1880 +
1881 +/* Locks INODE. */
1882 +void
1883 +inode_lock (struct inode *inode) 
1884 +{
1885 +  lock_acquire (&inode->lock);
1886 +}
1887 +
1888 +/* Releases INODE's lock. */
1889 +void
1890 +inode_unlock (struct inode *inode) 
1891 +{
1892 +  lock_release (&inode->lock);
1893  }
1894 Index: src/filesys/inode.h
1895 diff -u src/filesys/inode.h~ src/filesys/inode.h
1896 --- src/filesys/inode.h~
1897 +++ src/filesys/inode.h
1898 @@ -7,10 +7,18 @@
1899  
1900  struct bitmap;
1901  
1902 +/* Type of an inode. */
1903 +enum inode_type 
1904 +  {
1905 +    FILE_INODE,        /* Ordinary file. */
1906 +    DIR_INODE          /* Directory. */
1907 +  };
1908 +
1909  void inode_init (void);
1910 -bool inode_create (disk_sector_t, off_t);
1911 +bool inode_create (disk_sector_t, off_t, enum inode_type);
1912  struct inode *inode_open (disk_sector_t);
1913  struct inode *inode_reopen (struct inode *);
1914 +enum inode_type inode_get_type (const struct inode *);
1915  void inode_close (struct inode *);
1916  void inode_remove (struct inode *);
1917  off_t inode_read_at (struct inode *, void *, off_t size, off_t offset);
1918 @@ -18,5 +26,8 @@ off_t inode_write_at (struct inode *, co
1919  void inode_deny_write (struct inode *);
1920  void inode_allow_write (struct inode *);
1921  off_t inode_length (const struct inode *);
1922 +int inode_open_cnt (const struct inode *);
1923 +void inode_lock (struct inode *);
1924 +void inode_unlock (struct inode *);
1925  
1926  #endif /* filesys/inode.h */
1927 Index: src/threads/init.c
1928 diff -u src/threads/init.c~ src/threads/init.c
1929 --- src/threads/init.c~
1930 +++ src/threads/init.c
1931 @@ -33,6 +33,8 @@
1932  #include "filesys/filesys.h"
1933  #include "filesys/fsutil.h"
1934  #endif
1935 +#include "vm/frame.h"
1936 +#include "vm/swap.h"
1937  
1938  /* Amount of physical memory, in 4 kB pages. */
1939  size_t ram_pages;
1940 @@ -124,6 +126,9 @@ main (void)
1941    filesys_init (format_filesys);
1942  #endif
1943  
1944 +  frame_init ();
1945 +  swap_init ();
1946 +
1947    printf ("Boot complete.\n");
1948    
1949    /* Run actions specified on kernel command line. */
1950 Index: src/threads/interrupt.c
1951 diff -u src/threads/interrupt.c~ src/threads/interrupt.c
1952 --- src/threads/interrupt.c~
1953 +++ src/threads/interrupt.c
1954 @@ -354,6 +354,8 @@ intr_handler (struct intr_frame *frame) 
1955        in_external_intr = true;
1956        yield_on_return = false;
1957      }
1958 +  else 
1959 +    thread_current ()->user_esp = frame->esp;
1960  
1961    /* Invoke the interrupt's handler.
1962       If there is no handler, invoke the unexpected interrupt
1963 Index: src/threads/thread.c
1964 diff -u src/threads/thread.c~ src/threads/thread.c
1965 --- src/threads/thread.c~
1966 +++ src/threads/thread.c
1967 @@ -13,6 +13,7 @@
1968  #include "threads/vaddr.h"
1969  #ifdef USERPROG
1970  #include "userprog/process.h"
1971 +#include "userprog/syscall.h"
1972  #endif
1973  
1974  /* Random value for struct thread's `magic' member.
1975 @@ -55,7 +56,8 @@ static void kernel_thread (thread_func *
1976  static void idle (void *aux UNUSED);
1977  static struct thread *running_thread (void);
1978  static struct thread *next_thread_to_run (void);
1979 -static void init_thread (struct thread *, const char *name, int priority);
1980 +static void init_thread (struct thread *, const char *name, int priority,
1981 +                         tid_t);
1982  static bool is_thread (struct thread *) UNUSED;
1983  static void *alloc_frame (struct thread *, size_t size);
1984  static void schedule (void);
1985 @@ -82,9 +84,8 @@ thread_init (void) 
1986  
1987    /* Set up a thread structure for the running thread. */
1988    initial_thread = running_thread ();
1989 -  init_thread (initial_thread, "main", PRI_DEFAULT);
1990 +  init_thread (initial_thread, "main", PRI_DEFAULT, 0);
1991    initial_thread->status = THREAD_RUNNING;
1992 -  initial_thread->tid = allocate_tid ();
1993  }
1994  
1995  /* Starts preemptive thread scheduling by enabling interrupts.
1996 @@ -159,8 +160,8 @@ thread_create (const char *name, int pri
1997      return TID_ERROR;
1998  
1999    /* Initialize thread. */
2000 -  init_thread (t, name, priority);
2001 -  tid = t->tid = allocate_tid ();
2002 +  init_thread (t, name, priority, allocate_tid ());
2003 +  tid = t->tid;
2004  
2005    /* Stack frame for kernel_thread(). */
2006    kf = alloc_frame (t, sizeof *kf);
2007 @@ -253,16 +254,19 @@ thread_tid (void) 
2008  void
2009  thread_exit (void) 
2010  {
2011 +  struct thread *t = thread_current ();
2012 +
2013    ASSERT (!intr_context ());
2014  
2015 +  syscall_exit ();
2016  #ifdef USERPROG
2017    process_exit ();
2018  #endif
2019 -
2020 +  
2021    /* Just set our status to dying and schedule another process.
2022       We will be destroyed during the call to schedule_tail(). */
2023    intr_disable ();
2024 -  thread_current ()->status = THREAD_DYING;
2025 +  t->status = THREAD_DYING;
2026    schedule ();
2027    NOT_REACHED ();
2028  }
2029 @@ -406,17 +410,29 @@ is_thread (struct thread *t)
2030  /* Does basic initialization of T as a blocked thread named
2031     NAME. */
2032  static void
2033 -init_thread (struct thread *t, const char *name, int priority)
2034 +init_thread (struct thread *t, const char *name, int priority, tid_t tid)
2035  {
2036    ASSERT (t != NULL);
2037    ASSERT (PRI_MIN <= priority && priority <= PRI_MAX);
2038    ASSERT (name != NULL);
2039  
2040    memset (t, 0, sizeof *t);
2041 +  t->tid = tid;
2042    t->status = THREAD_BLOCKED;
2043    strlcpy (t->name, name, sizeof t->name);
2044    t->stack = (uint8_t *) t + PGSIZE;
2045    t->priority = priority;
2046 +  t->exit_code = -1;
2047 +  t->wait_status = NULL;
2048 +  list_init (&t->children);
2049 +  sema_init (&t->timer_sema, 0);
2050 +  t->pagedir = NULL;
2051 +  t->pages = NULL;
2052 +  t->bin_file = NULL;
2053 +  list_init (&t->fds);
2054 +  list_init (&t->mappings);
2055 +  t->next_handle = 2;
2056 +  t->wd = NULL;
2057    t->magic = THREAD_MAGIC;
2058  }
2059  
2060 Index: src/threads/thread.h
2061 diff -u src/threads/thread.h~ src/threads/thread.h
2062 --- src/threads/thread.h~
2063 +++ src/threads/thread.h
2064 @@ -2,8 +2,10 @@
2065  #define THREADS_THREAD_H
2066  
2067  #include <debug.h>
2068 +#include <hash.h>
2069  #include <list.h>
2070  #include <stdint.h>
2071 +#include "threads/synch.h"
2072  
2073  /* States in a thread's life cycle. */
2074  enum thread_status
2075 @@ -89,18 +91,50 @@ struct thread
2076      uint8_t *stack;                     /* Saved stack pointer. */
2077      int priority;                       /* Priority. */
2078  
2079 +    /* Owned by process.c. */
2080 +    int exit_code;                      /* Exit code. */
2081 +    struct wait_status *wait_status;    /* This process's completion status. */
2082 +    struct list children;               /* Completion status of children. */
2083 +
2084      /* Shared between thread.c and synch.c. */
2085      struct list_elem elem;              /* List element. */
2086  
2087 -#ifdef USERPROG
2088 +    /* Alarm clock. */
2089 +    int64_t wakeup_time;                /* Time to wake this thread up. */
2090 +    struct list_elem timer_elem;        /* Element in timer_wait_list. */
2091 +    struct semaphore timer_sema;        /* Semaphore. */
2092 +
2093      /* Owned by userprog/process.c. */
2094      uint32_t *pagedir;                  /* Page directory. */
2095 -#endif
2096 +    struct hash *pages;                 /* Page table. */
2097 +    struct file *bin_file;              /* The binary executable. */
2098 +
2099 +    /* Owned by syscall.c. */
2100 +    struct list fds;                    /* List of file descriptors. */
2101 +    struct list mappings;               /* Memory-mapped files. */
2102 +    int next_handle;                    /* Next handle value. */
2103 +    void *user_esp;                     /* User's stack pointer. */
2104 +    struct dir *wd;                     /* Working directory. */
2105  
2106      /* Owned by thread.c. */
2107      unsigned magic;                     /* Detects stack overflow. */
2108    };
2109  
2110 +/* Tracks the completion of a process.
2111 +   Reference held by both the parent, in its `children' list,
2112 +   and by the child, in its `wait_status' pointer. */
2113 +struct wait_status
2114 +  {
2115 +    struct list_elem elem;              /* `children' list element. */
2116 +    struct lock lock;                   /* Protects ref_cnt. */
2117 +    int ref_cnt;                        /* 2=child and parent both alive,
2118 +                                           1=either child or parent alive,
2119 +                                           0=child and parent both dead. */
2120 +    tid_t tid;                          /* Child thread id. */
2121 +    int exit_code;                      /* Child exit code, if dead. */
2122 +    struct semaphore dead;              /* 1=child alive, 0=child dead. */
2123 +  };
2124 +
2125  void thread_init (void);
2126  void thread_start (void);
2127  
2128 Index: src/userprog/exception.c
2129 diff -u src/userprog/exception.c~ src/userprog/exception.c
2130 --- src/userprog/exception.c~
2131 +++ src/userprog/exception.c
2132 @@ -4,6 +4,7 @@
2133  #include "userprog/gdt.h"
2134  #include "threads/interrupt.h"
2135  #include "threads/thread.h"
2136 +#include "vm/page.h"
2137  
2138  /* Number of page faults processed. */
2139  static long long page_fault_cnt;
2140 @@ -148,9 +149,14 @@ page_fault (struct intr_frame *f) 
2141    write = (f->error_code & PF_W) != 0;
2142    user = (f->error_code & PF_U) != 0;
2143  
2144 -  /* To implement virtual memory, delete the rest of the function
2145 -     body, and replace it with code that brings in the page to
2146 -     which fault_addr refers. */
2147 +  /* Allow the pager to try to handle it. */
2148 +  if (user && not_present)
2149 +    {
2150 +      if (!page_in (fault_addr))
2151 +        thread_exit ();
2152 +      return;
2153 +    }
2154 +
2155    printf ("Page fault at %p: %s error %s page in %s context.\n",
2156            fault_addr,
2157            not_present ? "not present" : "rights violation",
2158 Index: src/userprog/pagedir.c
2159 diff -u src/userprog/pagedir.c~ src/userprog/pagedir.c
2160 --- src/userprog/pagedir.c~
2161 +++ src/userprog/pagedir.c
2162 @@ -35,15 +35,7 @@ pagedir_destroy (uint32_t *pd) 
2163    ASSERT (pd != base_page_dir);
2164    for (pde = pd; pde < pd + pd_no (PHYS_BASE); pde++)
2165      if (*pde & PTE_P) 
2166 -      {
2167 -        uint32_t *pt = pde_get_pt (*pde);
2168 -        uint32_t *pte;
2169 -        
2170 -        for (pte = pt; pte < pt + PGSIZE / sizeof *pte; pte++)
2171 -          if (*pte & PTE_P) 
2172 -            palloc_free_page (pte_get_page (*pte));
2173 -        palloc_free_page (pt);
2174 -      }
2175 +      palloc_free_page (pde_get_pt (*pde));
2176    palloc_free_page (pd);
2177  }
2178  
2179 Index: src/userprog/process.c
2180 diff -u src/userprog/process.c~ src/userprog/process.c
2181 --- src/userprog/process.c~
2182 +++ src/userprog/process.c
2183 @@ -14,12 +14,27 @@
2184  #include "threads/flags.h"
2185  #include "threads/init.h"
2186  #include "threads/interrupt.h"
2187 +#include "threads/malloc.h"
2188  #include "threads/palloc.h"
2189  #include "threads/thread.h"
2190  #include "threads/vaddr.h"
2191 +#include "vm/page.h"
2192 +#include "vm/frame.h"
2193  
2194  static thread_func execute_thread NO_RETURN;
2195 -static bool load (const char *cmdline, void (**eip) (void), void **esp);
2196 +static bool load (const char *cmd_line, void (**eip) (void), void **esp);
2197 +
2198 +/* Data structure shared between process_execute() in the
2199 +   invoking thread and execute_thread() in the newly invoked
2200 +   thread. */
2201 +struct exec_info 
2202 +  {
2203 +    const char *file_name;              /* Program to load. */
2204 +    struct semaphore load_done;         /* "Up"ed when loading complete. */
2205 +    struct wait_status *wait_status;    /* Child process. */
2206 +    struct dir *wd;                     /* Working directory. */
2207 +    bool success;                       /* Program successfully loaded? */
2208 +  };
2209  
2210  /* Starts a new thread running a user program loaded from
2211     FILE_NAME.  The new thread may be scheduled (and may even exit)
2212 @@ -28,41 +43,78 @@ static bool load (const char *cmdline, v
2213  tid_t
2214  process_execute (const char *file_name) 
2215  {
2216 -  char *fn_copy;
2217 +  struct dir *wd = thread_current ()->wd;
2218 +  struct exec_info exec;
2219 +  char thread_name[16];
2220 +  char *save_ptr;
2221    tid_t tid;
2222  
2223 -  /* Make a copy of FILE_NAME.
2224 -     Otherwise there's a race between the caller and load(). */
2225 -  fn_copy = palloc_get_page (0);
2226 -  if (fn_copy == NULL)
2227 +  /* Initialize exec_info. */
2228 +  exec.file_name = file_name;
2229 +  exec.wd = wd != NULL ? dir_reopen (wd) : dir_open_root ();
2230 +  if (exec.wd == NULL)
2231      return TID_ERROR;
2232 -  strlcpy (fn_copy, file_name, PGSIZE);
2233 +  sema_init (&exec.load_done, 0);
2234  
2235    /* Create a new thread to execute FILE_NAME. */
2236 -  tid = thread_create (file_name, PRI_DEFAULT, execute_thread, fn_copy);
2237 -  if (tid == TID_ERROR)
2238 -    palloc_free_page (fn_copy); 
2239 +  strlcpy (thread_name, file_name, sizeof thread_name);
2240 +  strtok_r (thread_name, " ", &save_ptr);
2241 +  tid = thread_create (thread_name, PRI_DEFAULT, execute_thread, &exec);
2242 +  if (tid != TID_ERROR)
2243 +    {
2244 +      sema_down (&exec.load_done);
2245 +      if (exec.success)
2246 +        list_push_back (&thread_current ()->children, &exec.wait_status->elem);
2247 +      else 
2248 +        {
2249 +          tid = TID_ERROR;
2250 +          /* Don't close exec.wd; child process will have done so. */
2251 +        }
2252 +    }
2253 +  else
2254 +    dir_close (exec.wd);
2255 +
2256    return tid;
2257  }
2258  
2259  /* A thread function that loads a user process and starts it
2260     running. */
2261  static void
2262 -execute_thread (void *file_name_)
2263 +execute_thread (void *exec_)
2264  {
2265 -  char *file_name = file_name_;
2266 +  struct exec_info *exec = exec_;
2267    struct intr_frame if_;
2268    bool success;
2269  
2270 +  thread_current ()->wd = exec->wd;
2271 +
2272    /* Initialize interrupt frame and load executable. */
2273    memset (&if_, 0, sizeof if_);
2274    if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
2275    if_.cs = SEL_UCSEG;
2276    if_.eflags = FLAG_IF | FLAG_MBS;
2277 -  success = load (file_name, &if_.eip, &if_.esp);
2278 +  success = load (exec->file_name, &if_.eip, &if_.esp);
2279  
2280 -  /* If load failed, quit. */
2281 -  palloc_free_page (file_name);
2282 +  /* Allocate wait_status. */
2283 +  if (success)
2284 +    {
2285 +      exec->wait_status = thread_current ()->wait_status
2286 +        = malloc (sizeof *exec->wait_status);
2287 +      success = exec->wait_status != NULL; 
2288 +    }
2289 +
2290 +  /* Initialize wait_status. */
2291 +  if (success) 
2292 +    {
2293 +      lock_init (&exec->wait_status->lock);
2294 +      exec->wait_status->ref_cnt = 2;
2295 +      exec->wait_status->tid = thread_current ()->tid;
2296 +      sema_init (&exec->wait_status->dead, 0);
2297 +    }
2298 +  
2299 +  /* Notify parent thread and clean up. */
2300 +  exec->success = success;
2301 +  sema_up (&exec->load_done);
2302    if (!success) 
2303      thread_exit ();
2304  
2305 @@ -76,18 +128,47 @@ execute_thread (void *file_name_)
2306    NOT_REACHED ();
2307  }
2308  
2309 +/* Releases one reference to CS and, if it is now unreferenced,
2310 +   frees it. */
2311 +static void
2312 +release_child (struct wait_status *cs) 
2313 +{
2314 +  int new_ref_cnt;
2315 +  
2316 +  lock_acquire (&cs->lock);
2317 +  new_ref_cnt = --cs->ref_cnt;
2318 +  lock_release (&cs->lock);
2319 +
2320 +  if (new_ref_cnt == 0)
2321 +    free (cs);
2322 +}
2323 +
2324  /* Waits for thread TID to die and returns its exit status.  If
2325     it was terminated by the kernel (i.e. killed due to an
2326     exception), returns -1.  If TID is invalid or if it was not a
2327     child of the calling process, or if process_wait() has already
2328     been successfully called for the given TID, returns -1
2329 -   immediately, without waiting.
2330 -
2331 -   This function will be implemented in problem 2-2.  For now, it
2332 -   does nothing. */
2333 +   immediately, without waiting. */
2334  int
2335 -process_wait (tid_t child_tid UNUSED) 
2336 +process_wait (tid_t child_tid) 
2337  {
2338 +  struct thread *cur = thread_current ();
2339 +  struct list_elem *e;
2340 +
2341 +  for (e = list_begin (&cur->children); e != list_end (&cur->children);
2342 +       e = list_next (e)) 
2343 +    {
2344 +      struct wait_status *cs = list_entry (e, struct wait_status, elem);
2345 +      if (cs->tid == child_tid) 
2346 +        {
2347 +          int exit_code;
2348 +          list_remove (e);
2349 +          sema_down (&cs->dead);
2350 +          exit_code = cs->exit_code;
2351 +          release_child (cs);
2352 +          return exit_code;
2353 +        }
2354 +    }
2355    return -1;
2356  }
2357  
2358 @@ -96,8 +177,35 @@ void
2359  process_exit (void)
2360  {
2361    struct thread *cur = thread_current ();
2362 +  struct list_elem *e, *next;
2363    uint32_t *pd;
2364  
2365 +  printf ("%s: exit(%d)\n", cur->name, cur->exit_code);
2366 +
2367 +  /* Notify parent that we're dead. */
2368 +  if (cur->wait_status != NULL) 
2369 +    {
2370 +      struct wait_status *cs = cur->wait_status;
2371 +      cs->exit_code = cur->exit_code;
2372 +      sema_up (&cs->dead);
2373 +      release_child (cs);
2374 +    }
2375 +
2376 +  /* Free entries of children list. */
2377 +  for (e = list_begin (&cur->children); e != list_end (&cur->children);
2378 +       e = next) 
2379 +    {
2380 +      struct wait_status *cs = list_entry (e, struct wait_status, elem);
2381 +      next = list_remove (e);
2382 +      release_child (cs);
2383 +    }
2384 +
2385 +  /* Destroy the page hash table. */
2386 +  page_exit ();
2387 +  
2388 +  /* Close executable (and allow writes). */
2389 +  file_close (cur->bin_file);
2390 +
2391    /* Destroy the current process's page directory and switch back
2392       to the kernel-only page directory. */
2393    pd = cur->pagedir;
2394 @@ -194,7 +302,7 @@ struct Elf32_Phdr
2395  #define PF_W 2          /* Writable. */
2396  #define PF_R 4          /* Readable. */
2397  
2398 -static bool setup_stack (void **esp);
2399 +static bool setup_stack (const char *cmd_line, void **esp);
2400  static bool validate_segment (const struct Elf32_Phdr *, struct file *);
2401  static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
2402                            uint32_t read_bytes, uint32_t zero_bytes,
2403 @@ -205,13 +313,15 @@ static bool load_segment (struct file *f
2404     and its initial stack pointer into *ESP.
2405     Returns true if successful, false otherwise. */
2406  bool
2407 -load (const char *file_name, void (**eip) (void), void **esp) 
2408 +load (const char *cmd_line, void (**eip) (void), void **esp) 
2409  {
2410    struct thread *t = thread_current ();
2411 +  char file_name[NAME_MAX + 2];
2412    struct Elf32_Ehdr ehdr;
2413    struct file *file = NULL;
2414    off_t file_ofs;
2415    bool success = false;
2416 +  char *cp;
2417    int i;
2418  
2419    /* Allocate and activate page directory. */
2420 @@ -220,13 +330,28 @@ load (const char *file_name, void (**eip)
2421      goto done;
2422    process_activate ();
2423  
2424 +  /* Create page hash table. */
2425 +  t->pages = malloc (sizeof *t->pages);
2426 +  if (t->pages == NULL)
2427 +    goto done;
2428 +  hash_init (t->pages, page_hash, page_less, NULL);
2429 +
2430 +  /* Extract file_name from command line. */
2431 +  while (*cmd_line == ' ')
2432 +    cmd_line++;
2433 +  strlcpy (file_name, cmd_line, sizeof file_name);
2434 +  cp = strchr (file_name, ' ');
2435 +  if (cp != NULL)
2436 +    *cp = '\0';
2437 +
2438    /* Open executable file. */
2439 -  file = filesys_open (file_name);
2440 +  t->bin_file = file = file_open (filesys_open (file_name));
2441    if (file == NULL) 
2442      {
2443        printf ("load: %s: open failed\n", file_name);
2444        goto done; 
2445      }
2446 +  file_deny_write (file);
2447  
2448    /* Read and verify executable header. */
2449    if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
2450 @@ -301,7 +426,7 @@ load (const char *file_name, void (**eip)
2451      }
2452  
2453    /* Set up stack. */
2454 -  if (!setup_stack (esp))
2455 +  if (!setup_stack (cmd_line, esp))
2456      goto done;
2457  
2458    /* Start address. */
2459 @@ -311,14 +436,11 @@ load (const char *file_name, void (**eip)
2460  
2461   done:
2462    /* We arrive here whether the load is successful or not. */
2463 -  file_close (file);
2464    return success;
2465  }
2466  \f
2467  /* load() helpers. */
2468  
2469 -static bool install_page (void *upage, void *kpage, bool writable);
2470 -
2471  /* Checks whether PHDR describes a valid, loadable segment in
2472     FILE and returns true if so, false otherwise. */
2473  static bool
2474 @@ -386,79 +508,127 @@ load_segment (struct file *file, off_t o
2475    ASSERT (pg_ofs (upage) == 0);
2476    ASSERT (ofs % PGSIZE == 0);
2477  
2478 -  file_seek (file, ofs);
2479    while (read_bytes > 0 || zero_bytes > 0) 
2480      {
2481 -      /* Calculate how to fill this page.
2482 -         We will read PAGE_READ_BYTES bytes from FILE
2483 -         and zero the final PAGE_ZERO_BYTES bytes. */
2484        size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
2485        size_t page_zero_bytes = PGSIZE - page_read_bytes;
2486 -
2487 -      /* Get a page of memory. */
2488 -      uint8_t *kpage = palloc_get_page (PAL_USER);
2489 -      if (kpage == NULL)
2490 +      struct page *p = page_allocate (upage, !writable);
2491 +      if (p == NULL)
2492          return false;
2493 -
2494 -      /* Load this page. */
2495 -      if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
2496 -        {
2497 -          palloc_free_page (kpage);
2498 -          return false; 
2499 -        }
2500 -      memset (kpage + page_read_bytes, 0, page_zero_bytes);
2501 -
2502 -      /* Add the page to the process's address space. */
2503 -      if (!install_page (upage, kpage, writable)) 
2504 +      if (page_read_bytes > 0) 
2505          {
2506 -          palloc_free_page (kpage);
2507 -          return false; 
2508 +          p->file = file;
2509 +          p->file_offset = ofs;
2510 +          p->file_bytes = page_read_bytes;
2511          }
2512 -
2513 -      /* Advance. */
2514        read_bytes -= page_read_bytes;
2515        zero_bytes -= page_zero_bytes;
2516 +      ofs += page_read_bytes;
2517        upage += PGSIZE;
2518      }
2519    return true;
2520  }
2521  
2522 -/* Create a minimal stack by mapping a zeroed page at the top of
2523 -   user virtual memory. */
2524 +/* Reverse the order of the ARGC pointers to char in ARGV. */
2525 +static void
2526 +reverse (int argc, char **argv) 
2527 +{
2528 +  for (; argc > 1; argc -= 2, argv++) 
2529 +    {
2530 +      char *tmp = argv[0];
2531 +      argv[0] = argv[argc - 1];
2532 +      argv[argc - 1] = tmp;
2533 +    }
2534 +}
2535
2536 +/* Pushes the SIZE bytes in BUF onto the stack in KPAGE, whose
2537 +   page-relative stack pointer is *OFS, and then adjusts *OFS
2538 +   appropriately.  The bytes pushed are rounded to a 32-bit
2539 +   boundary.
2540 +
2541 +   If successful, returns a pointer to the newly pushed object.
2542 +   On failure, returns a null pointer. */
2543 +static void *
2544 +push (uint8_t *kpage, size_t *ofs, const void *buf, size_t size) 
2545 +{
2546 +  size_t padsize = ROUND_UP (size, sizeof (uint32_t));
2547 +  if (*ofs < padsize)
2548 +    return NULL;
2549 +
2550 +  *ofs -= padsize;
2551 +  memcpy (kpage + *ofs + (padsize - size), buf, size);
2552 +  return kpage + *ofs + (padsize - size);
2553 +}
2554 +
2555 +/* Sets up command line arguments in KPAGE, which will be mapped
2556 +   to UPAGE in user space.  The command line arguments are taken
2557 +   from CMD_LINE, separated by spaces.  Sets *ESP to the initial
2558 +   stack pointer for the process. */
2559  static bool
2560 -setup_stack (void **esp) 
2561 +init_cmd_line (uint8_t *kpage, uint8_t *upage, const char *cmd_line,
2562 +               void **esp) 
2563  {
2564 -  uint8_t *kpage;
2565 -  bool success = false;
2566 +  size_t ofs = PGSIZE;
2567 +  char *const null = NULL;
2568 +  char *cmd_line_copy;
2569 +  char *karg, *saveptr;
2570 +  int argc;
2571 +  char **argv;
2572 +
2573 +  /* Push command line string. */
2574 +  cmd_line_copy = push (kpage, &ofs, cmd_line, strlen (cmd_line) + 1);
2575 +  if (cmd_line_copy == NULL)
2576 +    return false;
2577  
2578 -  kpage = palloc_get_page (PAL_USER | PAL_ZERO);
2579 -  if (kpage != NULL) 
2580 +  if (push (kpage, &ofs, &null, sizeof null) == NULL)
2581 +    return false;
2582 +
2583 +  /* Parse command line into arguments
2584 +     and push them in reverse order. */
2585 +  argc = 0;
2586 +  for (karg = strtok_r (cmd_line_copy, " ", &saveptr); karg != NULL;
2587 +       karg = strtok_r (NULL, " ", &saveptr))
2588      {
2589 -      success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
2590 -      if (success)
2591 -        *esp = PHYS_BASE;
2592 -      else
2593 -        palloc_free_page (kpage);
2594 +      void *uarg = upage + (karg - (char *) kpage);
2595 +      if (push (kpage, &ofs, &uarg, sizeof uarg) == NULL)
2596 +        return false;
2597 +      argc++;
2598      }
2599 -  return success;
2600 +
2601 +  /* Reverse the order of the command line arguments. */
2602 +  argv = (char **) (upage + ofs);
2603 +  reverse (argc, (char **) (kpage + ofs));
2604 +
2605 +  /* Push argv, argc, "return address". */
2606 +  if (push (kpage, &ofs, &argv, sizeof argv) == NULL
2607 +      || push (kpage, &ofs, &argc, sizeof argc) == NULL
2608 +      || push (kpage, &ofs, &null, sizeof null) == NULL)
2609 +    return false;
2610 +
2611 +  /* Set initial stack pointer. */
2612 +  *esp = upage + ofs;
2613 +  return true;
2614  }
2615  
2616 -/* Adds a mapping from user virtual address UPAGE to kernel
2617 -   virtual address KPAGE to the page table.
2618 -   If WRITABLE is true, the user process may modify the page;
2619 -   otherwise, it is read-only.
2620 -   UPAGE must not already be mapped.
2621 -   KPAGE should probably be a page obtained from the user pool
2622 -   with palloc_get_page().
2623 -   Returns true on success, false if UPAGE is already mapped or
2624 -   if memory allocation fails. */
2625 +/* Create a minimal stack for T by mapping a page at the
2626 +   top of user virtual memory.  Fills in the page using CMD_LINE
2627 +   and sets *ESP to the stack pointer. */
2628  static bool
2629 -install_page (void *upage, void *kpage, bool writable)
2630 +setup_stack (const char *cmd_line, void **esp) 
2631  {
2632 -  struct thread *t = thread_current ();
2633 -
2634 -  /* Verify that there's not already a page at that virtual
2635 -     address, then map our page there. */
2636 -  return (pagedir_get_page (t->pagedir, upage) == NULL
2637 -          && pagedir_set_page (t->pagedir, upage, kpage, writable));
2638 +  struct page *page = page_allocate (((uint8_t *) PHYS_BASE) - PGSIZE, false);
2639 +  if (page != NULL) 
2640 +    {
2641 +      page->frame = frame_alloc_and_lock (page);
2642 +      if (page->frame != NULL)
2643 +        {
2644 +          bool ok;
2645 +          page->read_only = false;
2646 +          page->private = false;
2647 +          ok = init_cmd_line (page->frame->base, page->addr, cmd_line, esp);
2648 +          frame_unlock (page->frame);
2649 +          return ok;
2650 +        }
2651 +    }
2652 +  return false;
2653  }
2654 Index: src/userprog/syscall.c
2655 diff -u src/userprog/syscall.c~ src/userprog/syscall.c
2656 --- src/userprog/syscall.c~
2657 +++ src/userprog/syscall.c
2658 @@ -1,20 +1,671 @@
2659  #include "userprog/syscall.h"
2660  #include <stdio.h>
2661 +#include <string.h>
2662  #include <syscall-nr.h>
2663 +#include "userprog/process.h"
2664 +#include "userprog/pagedir.h"
2665 +#include "devices/kbd.h"
2666 +#include "filesys/directory.h"
2667 +#include "filesys/filesys.h"
2668 +#include "filesys/file.h"
2669 +#include "threads/init.h"
2670  #include "threads/interrupt.h"
2671 +#include "threads/malloc.h"
2672 +#include "threads/palloc.h"
2673  #include "threads/thread.h"
2674 -
2675 +#include "threads/vaddr.h"
2676 +#include "vm/page.h"
2677
2678
2679 +static int sys_halt (void);
2680 +static int sys_exit (int status);
2681 +static int sys_exec (const char *ufile);
2682 +static int sys_wait (tid_t);
2683 +static int sys_create (const char *ufile, unsigned initial_size);
2684 +static int sys_remove (const char *ufile);
2685 +static int sys_open (const char *ufile);
2686 +static int sys_filesize (int handle);
2687 +static int sys_read (int handle, void *udst_, unsigned size);
2688 +static int sys_write (int handle, void *usrc_, unsigned size);
2689 +static int sys_seek (int handle, unsigned position);
2690 +static int sys_tell (int handle);
2691 +static int sys_close (int handle);
2692 +static int sys_mmap (int handle, void *addr);
2693 +static int sys_munmap (int mapping);
2694 +static int sys_chdir (const char *udir);
2695 +static int sys_mkdir (const char *udir);
2696 +static int sys_readdir (int handle, char *name);
2697 +static int sys_isdir (int handle);
2698
2699  static void syscall_handler (struct intr_frame *);
2700 -
2701 +static void copy_in (void *, const void *, size_t);
2702
2703  void
2704  syscall_init (void) 
2705  {
2706    intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
2707  }
2708
2709 +/* System call handler. */
2710 +static void
2711 +syscall_handler (struct intr_frame *f) 
2712 +{
2713 +  typedef int syscall_function (int, int, int);
2714 +
2715 +  /* A system call. */
2716 +  struct syscall 
2717 +    {
2718 +      size_t arg_cnt;           /* Number of arguments. */
2719 +      syscall_function *func;   /* Implementation. */
2720 +    };
2721 +
2722 +  /* Table of system calls. */
2723 +  static const struct syscall syscall_table[] =
2724 +    {
2725 +      {0, (syscall_function *) sys_halt},
2726 +      {1, (syscall_function *) sys_exit},
2727 +      {1, (syscall_function *) sys_exec},
2728 +      {1, (syscall_function *) sys_wait},
2729 +      {2, (syscall_function *) sys_create},
2730 +      {1, (syscall_function *) sys_remove},
2731 +      {1, (syscall_function *) sys_open},
2732 +      {1, (syscall_function *) sys_filesize},
2733 +      {3, (syscall_function *) sys_read},
2734 +      {3, (syscall_function *) sys_write},
2735 +      {2, (syscall_function *) sys_seek},
2736 +      {1, (syscall_function *) sys_tell},
2737 +      {1, (syscall_function *) sys_close},
2738 +      {2, (syscall_function *) sys_mmap},
2739 +      {1, (syscall_function *) sys_munmap},
2740 +      {1, (syscall_function *) sys_chdir},
2741 +      {1, (syscall_function *) sys_mkdir},
2742 +      {2, (syscall_function *) sys_readdir},
2743 +      {1, (syscall_function *) sys_isdir},
2744 +    };
2745  
2746 +  const struct syscall *sc;
2747 +  unsigned call_nr;
2748 +  int args[3];
2749 +
2750 +  /* Get the system call. */
2751 +  copy_in (&call_nr, f->esp, sizeof call_nr);
2752 +  if (call_nr >= sizeof syscall_table / sizeof *syscall_table)
2753 +    thread_exit ();
2754 +  sc = syscall_table + call_nr;
2755 +
2756 +  /* Get the system call arguments. */
2757 +  ASSERT (sc->arg_cnt <= sizeof args / sizeof *args);
2758 +  memset (args, 0, sizeof args);
2759 +  copy_in (args, (uint32_t *) f->esp + 1, sizeof *args * sc->arg_cnt);
2760 +
2761 +  /* Execute the system call,
2762 +     and set the return value. */
2763 +  f->eax = sc->func (args[0], args[1], args[2]);
2764 +}
2765
2766 +/* Copies SIZE bytes from user address USRC to kernel address
2767 +   DST.
2768 +   Call thread_exit() if any of the user accesses are invalid. */
2769  static void
2770 -syscall_handler (struct intr_frame *f UNUSED) 
2771 +copy_in (void *dst_, const void *usrc_, size_t size) 
2772 +{
2773 +  uint8_t *dst = dst_;
2774 +  const uint8_t *usrc = usrc_;
2775 +
2776 +  while (size > 0) 
2777 +    {
2778 +      size_t chunk_size = PGSIZE - pg_ofs (usrc);
2779 +      if (chunk_size > size)
2780 +        chunk_size = size;
2781 +      
2782 +      if (!page_lock (usrc, false))
2783 +        thread_exit ();
2784 +      memcpy (dst, usrc, chunk_size);
2785 +      page_unlock (usrc);
2786 +
2787 +      dst += chunk_size;
2788 +      usrc += chunk_size;
2789 +      size -= chunk_size;
2790 +    }
2791 +}
2792
2793 +/* Copies SIZE bytes from kernel address SRC to user address
2794 +   UDST.
2795 +   Call thread_exit() if any of the user accesses are invalid. */
2796 +static void
2797 +copy_out (void *udst_, const void *src_, size_t size) 
2798 +{
2799 +  uint8_t *udst = udst_;
2800 +  const uint8_t *src = src_;
2801 +
2802 +  while (size > 0) 
2803 +    {
2804 +      size_t chunk_size = PGSIZE - pg_ofs (udst);
2805 +      if (chunk_size > size)
2806 +        chunk_size = size;
2807 +      
2808 +      if (!page_lock (udst, false))
2809 +        thread_exit ();
2810 +      memcpy (udst, src, chunk_size);
2811 +      page_unlock (udst);
2812 +
2813 +      udst += chunk_size;
2814 +      src += chunk_size;
2815 +      size -= chunk_size;
2816 +    }
2817 +}
2818
2819 +/* Creates a copy of user string US in kernel memory
2820 +   and returns it as a page that must be freed with
2821 +   palloc_free_page().
2822 +   Truncates the string at PGSIZE bytes in size.
2823 +   Call thread_exit() if any of the user accesses are invalid. */
2824 +static char *
2825 +copy_in_string (const char *us) 
2826 +{
2827 +  char *ks;
2828 +  char *upage;
2829 +  size_t length;
2830
2831 +  ks = palloc_get_page (0);
2832 +  if (ks == NULL) 
2833 +    thread_exit ();
2834 +
2835 +  length = 0;
2836 +  for (;;) 
2837 +    {
2838 +      upage = pg_round_down (us);
2839 +      if (!page_lock (upage, false))
2840 +        goto lock_error;
2841 +
2842 +      for (; us < upage + PGSIZE; us++) 
2843 +        {
2844 +          ks[length++] = *us;
2845 +          if (*us == '\0') 
2846 +            {
2847 +              page_unlock (upage);
2848 +              return ks; 
2849 +            }
2850 +          else if (length >= PGSIZE) 
2851 +            goto too_long_error;
2852 +        }
2853 +
2854 +      page_unlock (upage);
2855 +    }
2856 +
2857 + too_long_error:
2858 +  page_unlock (upage);
2859 + lock_error:
2860 +  palloc_free_page (ks);
2861 +  thread_exit ();
2862 +}
2863
2864 +/* Halt system call. */
2865 +static int
2866 +sys_halt (void)
2867 +{
2868 +  power_off ();
2869 +}
2870
2871 +/* Exit system call. */
2872 +static int
2873 +sys_exit (int exit_code) 
2874 +{
2875 +  thread_current ()->exit_code = exit_code;
2876 +  thread_exit ();
2877 +  NOT_REACHED ();
2878 +}
2879
2880 +/* Exec system call. */
2881 +static int
2882 +sys_exec (const char *ufile) 
2883 +{
2884 +  tid_t tid;
2885 +  char *kfile = copy_in_string (ufile);
2886
2887 +  tid = process_execute (kfile);
2888
2889 +  palloc_free_page (kfile);
2890
2891 +  return tid;
2892 +}
2893
2894 +/* Wait system call. */
2895 +static int
2896 +sys_wait (tid_t child) 
2897 +{
2898 +  return process_wait (child);
2899 +}
2900
2901 +/* Create system call. */
2902 +static int
2903 +sys_create (const char *ufile, unsigned initial_size) 
2904 +{
2905 +  char *kfile = copy_in_string (ufile);
2906 +  bool ok = filesys_create (kfile, initial_size, FILE_INODE);
2907 +  palloc_free_page (kfile);
2908
2909 +  return ok;
2910 +}
2911
2912 +/* Remove system call. */
2913 +static int
2914 +sys_remove (const char *ufile) 
2915 +{
2916 +  char *kfile = copy_in_string (ufile);
2917 +  bool ok = filesys_remove (kfile);
2918 +  palloc_free_page (kfile);
2919
2920 +  return ok;
2921 +}
2922 +\f
2923 +/* A file descriptor, for binding a file handle to a file. */
2924 +struct file_descriptor
2925 +  {
2926 +    struct list_elem elem;      /* List element. */
2927 +    struct file *file;          /* File. */
2928 +    struct dir *dir;            /* Directory. */
2929 +    int handle;                 /* File handle. */
2930 +  };
2931
2932 +/* Open system call. */
2933 +static int
2934 +sys_open (const char *ufile) 
2935 +{
2936 +  char *kfile = copy_in_string (ufile);
2937 +  struct file_descriptor *fd;
2938 +  int handle = -1;
2939
2940 +  fd = calloc (1, sizeof *fd);
2941 +  if (fd != NULL)
2942 +    {
2943 +      struct inode *inode = filesys_open (kfile);
2944 +      if (inode != NULL)
2945 +        {
2946 +          if (inode_get_type (inode) == FILE_INODE)
2947 +            fd->file = file_open (inode);
2948 +          else
2949 +            fd->dir = dir_open (inode);
2950 +          if (fd->file != NULL || fd->dir != NULL)
2951 +            {
2952 +              struct thread *cur = thread_current ();
2953 +              handle = fd->handle = cur->next_handle++;
2954 +              list_push_front (&cur->fds, &fd->elem);
2955 +            }
2956 +          else 
2957 +            {
2958 +              free (fd);
2959 +              inode_close (inode);
2960 +            }
2961 +        }
2962 +    }
2963 +  
2964 +  palloc_free_page (kfile);
2965 +  return handle;
2966 +}
2967
2968 +/* Returns the file descriptor associated with the given handle.
2969 +   Terminates the process if HANDLE is not associated with an
2970 +   open file. */
2971 +static struct file_descriptor *
2972 +lookup_fd (int handle) 
2973 +{
2974 +  struct thread *cur = thread_current ();
2975 +  struct list_elem *e;
2976 +   
2977 +  for (e = list_begin (&cur->fds); e != list_end (&cur->fds);
2978 +       e = list_next (e))
2979 +    {
2980 +      struct file_descriptor *fd;
2981 +      fd = list_entry (e, struct file_descriptor, elem);
2982 +      if (fd->handle == handle)
2983 +        return fd;
2984 +    }
2985
2986 +  thread_exit ();
2987 +}
2988
2989 +/* Returns the file descriptor associated with the given handle.
2990 +   Terminates the process if HANDLE is not associated with an
2991 +   open ordinary file. */
2992 +static struct file_descriptor *
2993 +lookup_file_fd (int handle) 
2994 +{
2995 +  struct file_descriptor *fd = lookup_fd (handle);
2996 +  if (fd->file == NULL)
2997 +    thread_exit ();
2998 +  return fd;
2999 +}
3000
3001 +/* Returns the file descriptor associated with the given handle.
3002 +   Terminates the process if HANDLE is not associated with an
3003 +   open directory. */
3004 +static struct file_descriptor *
3005 +lookup_dir_fd (int handle) 
3006 +{
3007 +  struct file_descriptor *fd = lookup_fd (handle);
3008 +  if (fd->dir == NULL)
3009 +    thread_exit ();
3010 +  return fd;
3011 +}
3012 +
3013 +/* Filesize system call. */
3014 +static int
3015 +sys_filesize (int handle) 
3016 +{
3017 +  struct file_descriptor *fd = lookup_file_fd (handle);
3018 +  int size;
3019
3020 +  size = file_length (fd->file);
3021
3022 +  return size;
3023 +}
3024
3025 +/* Read system call. */
3026 +static int
3027 +sys_read (int handle, void *udst_, unsigned size) 
3028 +{
3029 +  uint8_t *udst = udst_;
3030 +  struct file_descriptor *fd;
3031 +  int bytes_read = 0;
3032 +
3033 +  /* Look up file descriptor. */
3034 +  if (handle != STDIN_FILENO)
3035 +    fd = lookup_file_fd (handle);
3036 +
3037 +  while (size > 0) 
3038 +    {
3039 +      /* How much to read into this page? */
3040 +      size_t page_left = PGSIZE - pg_ofs (udst);
3041 +      size_t read_amt = size < page_left ? size : page_left;
3042 +      off_t retval;
3043 +
3044 +      /* Check that touching this page is okay. */
3045 +      if (!page_lock (udst, true)) 
3046 +        thread_exit ();
3047 +
3048 +      /* Read from file into page. */
3049 +      if (handle != STDIN_FILENO) 
3050 +        {
3051 +          retval = file_read (fd->file, udst, read_amt);
3052 +          if (retval < 0)
3053 +            {
3054 +              if (bytes_read == 0)
3055 +                bytes_read = -1; 
3056 +              break;
3057 +            }
3058 +          bytes_read += retval; 
3059 +        }
3060 +      else 
3061 +        {
3062 +          size_t i;
3063 +          
3064 +          for (i = 0; i < read_amt; i++) 
3065 +            udst[i] = kbd_getc ();
3066 +          bytes_read = read_amt;
3067 +        }
3068 +
3069 +      /* Release page. */
3070 +      page_unlock (udst);
3071 +
3072 +      /* If it was a short read we're done. */
3073 +      if (retval != (off_t) read_amt)
3074 +        break;
3075 +
3076 +      /* Advance. */
3077 +      udst += retval;
3078 +      size -= retval;
3079 +    }
3080 +   
3081 +  return bytes_read;
3082 +}
3083
3084 +/* Write system call. */
3085 +static int
3086 +sys_write (int handle, void *usrc_, unsigned size) 
3087  {
3088 -  printf ("system call!\n");
3089 +  uint8_t *usrc = usrc_;
3090 +  struct file_descriptor *fd = NULL;
3091 +  int bytes_written = 0;
3092 +
3093 +  /* Lookup up file descriptor. */
3094 +  if (handle != STDOUT_FILENO)
3095 +    fd = lookup_file_fd (handle);
3096 +
3097 +  while (size > 0) 
3098 +    {
3099 +      /* How much bytes to write to this page? */
3100 +      size_t page_left = PGSIZE - pg_ofs (usrc);
3101 +      size_t write_amt = size < page_left ? size : page_left;
3102 +      off_t retval;
3103 +
3104 +      /* Check that we can touch this user page. */
3105 +      if (!page_lock (usrc, false)) 
3106 +        thread_exit ();
3107 +
3108 +      /* Do the write. */
3109 +      if (handle == STDOUT_FILENO)
3110 +        {
3111 +          putbuf ((char *) usrc, write_amt);
3112 +          retval = write_amt;
3113 +        }
3114 +      else
3115 +        retval = file_write (fd->file, usrc, write_amt);
3116 +
3117 +      /* Release user page. */
3118 +      page_unlock (usrc);
3119 +
3120 +      /* Handle return value. */
3121 +      if (retval < 0) 
3122 +        {
3123 +          if (bytes_written == 0)
3124 +            bytes_written = -1;
3125 +          break;
3126 +        }
3127 +      bytes_written += retval;
3128 +
3129 +      /* If it was a short write we're done. */
3130 +      if (retval != (off_t) write_amt)
3131 +        break;
3132 +
3133 +      /* Advance. */
3134 +      usrc += retval;
3135 +      size -= retval;
3136 +    }
3137
3138 +  return bytes_written;
3139 +}
3140
3141 +/* Seek system call. */
3142 +static int
3143 +sys_seek (int handle, unsigned position) 
3144 +{
3145 +  if ((off_t) position >= 0)
3146 +    file_seek (lookup_file_fd (handle)->file, position);
3147 +  return 0;
3148 +}
3149
3150 +/* Tell system call. */
3151 +static int
3152 +sys_tell (int handle) 
3153 +{
3154 +  return file_tell (lookup_file_fd (handle)->file);
3155 +}
3156
3157 +/* Close system call. */
3158 +static int
3159 +sys_close (int handle) 
3160 +{
3161 +  struct file_descriptor *fd = lookup_fd (handle);
3162 +  file_close (fd->file);
3163 +  dir_close (fd->dir);
3164 +  list_remove (&fd->elem);
3165 +  free (fd);
3166 +  return 0;
3167 +}
3168 +\f
3169 +/* Binds a mapping id to a region of memory and a file. */
3170 +struct mapping
3171 +  {
3172 +    struct list_elem elem;      /* List element. */
3173 +    int handle;                 /* Mapping id. */
3174 +    struct file *file;          /* File. */
3175 +    uint8_t *base;              /* Start of memory mapping. */
3176 +    size_t page_cnt;            /* Number of pages mapped. */
3177 +  };
3178 +
3179 +/* Returns the file descriptor associated with the given handle.
3180 +   Terminates the process if HANDLE is not associated with a
3181 +   memory mapping. */
3182 +static struct mapping *
3183 +lookup_mapping (int handle) 
3184 +{
3185 +  struct thread *cur = thread_current ();
3186 +  struct list_elem *e;
3187 +   
3188 +  for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
3189 +       e = list_next (e))
3190 +    {
3191 +      struct mapping *m = list_entry (e, struct mapping, elem);
3192 +      if (m->handle == handle)
3193 +        return m;
3194 +    }
3195
3196    thread_exit ();
3197  }
3198 +
3199 +/* Remove mapping M from the virtual address space,
3200 +   writing back any pages that have changed. */
3201 +static void
3202 +unmap (struct mapping *m) 
3203 +{
3204 +  list_remove (&m->elem);
3205 +  while (m->page_cnt-- > 0) 
3206 +    {
3207 +      page_deallocate (m->base);
3208 +      m->base += PGSIZE;
3209 +    }
3210 +  file_close (m->file);
3211 +  free (m);
3212 +}
3213
3214 +/* Mmap system call. */
3215 +static int
3216 +sys_mmap (int handle, void *addr)
3217 +{
3218 +  struct file_descriptor *fd = lookup_file_fd (handle);
3219 +  struct mapping *m = malloc (sizeof *m);
3220 +  size_t offset;
3221 +  off_t length;
3222 +
3223 +  if (m == NULL || addr == NULL || pg_ofs (addr) != 0)
3224 +    return -1;
3225 +
3226 +  m->handle = thread_current ()->next_handle++;
3227 +  m->file = file_reopen (fd->file);
3228 +  if (m->file == NULL) 
3229 +    {
3230 +      free (m);
3231 +      return -1;
3232 +    }
3233 +  m->base = addr;
3234 +  m->page_cnt = 0;
3235 +  list_push_front (&thread_current ()->mappings, &m->elem);
3236 +
3237 +  offset = 0;
3238 +  length = file_length (m->file);
3239 +  while (length > 0)
3240 +    {
3241 +      struct page *p = page_allocate ((uint8_t *) addr + offset, false);
3242 +      if (p == NULL)
3243 +        {
3244 +          unmap (m);
3245 +          return -1;
3246 +        }
3247 +      p->private = false;
3248 +      p->file = m->file;
3249 +      p->file_offset = offset;
3250 +      p->file_bytes = length >= PGSIZE ? PGSIZE : length;
3251 +      offset += p->file_bytes;
3252 +      length -= p->file_bytes;
3253 +      m->page_cnt++;
3254 +    }
3255 +  
3256 +  return m->handle;
3257 +}
3258 +
3259 +/* Munmap system call. */
3260 +static int
3261 +sys_munmap (int mapping) 
3262 +{
3263 +  unmap (lookup_mapping (mapping));
3264 +  return 0;
3265 +}
3266 +
3267 +/* Chdir system call. */
3268 +static int
3269 +sys_chdir (const char *udir) 
3270 +{
3271 +  char *kdir = copy_in_string (udir);
3272 +  bool ok = filesys_chdir (kdir);
3273 +  palloc_free_page (kdir);
3274 +  return ok;
3275 +}
3276 +
3277 +/* Mkdir system call. */
3278 +static int
3279 +sys_mkdir (const char *udir)
3280 +{
3281 +  char *kdir = copy_in_string (udir);
3282 +  bool ok = filesys_create (kdir, 0, DIR_INODE);
3283 +  palloc_free_page (kdir);
3284
3285 +  return ok;
3286 +}
3287 +
3288 +/* Readdir system call. */
3289 +static int
3290 +sys_readdir (int handle, char *uname)
3291 +{
3292 +  struct file_descriptor *fd = lookup_dir_fd (handle);
3293 +  char name[NAME_MAX + 1];
3294 +  bool ok = dir_readdir (fd->dir, name);
3295 +  if (ok)
3296 +    copy_out (uname, name, strlen (name) + 1);
3297 +  return ok;
3298 +}
3299 +
3300 +/* Isdir system call. */
3301 +static int
3302 +sys_isdir (int handle)
3303 +{
3304 +  struct file_descriptor *fd = lookup_fd (handle);
3305 +  return fd->dir != NULL;
3306 +}
3307 +\f 
3308 +/* On thread exit, close all open files and unmap all mappings. */
3309 +void
3310 +syscall_exit (void) 
3311 +{
3312 +  struct thread *cur = thread_current ();
3313 +  struct list_elem *e, *next;
3314 +   
3315 +  for (e = list_begin (&cur->fds); e != list_end (&cur->fds); e = next)
3316 +    {
3317 +      struct file_descriptor *fd = list_entry (e, struct file_descriptor, elem);
3318 +      next = list_next (e);
3319 +      file_close (fd->file);
3320 +      dir_close (fd->dir);
3321 +      free (fd);
3322 +    }
3323 +   
3324 +  for (e = list_begin (&cur->mappings); e != list_end (&cur->mappings);
3325 +       e = next)
3326 +    {
3327 +      struct mapping *m = list_entry (e, struct mapping, elem);
3328 +      next = list_next (e);
3329 +      unmap (m);
3330 +    }
3331 +
3332 +  dir_close (cur->wd);
3333 +}
3334 Index: src/userprog/syscall.h
3335 diff -u src/userprog/syscall.h~ src/userprog/syscall.h
3336 --- src/userprog/syscall.h~
3337 +++ src/userprog/syscall.h
3338 @@ -2,5 +2,6 @@
3339  #define USERPROG_SYSCALL_H
3340  
3341  void syscall_init (void);
3342 +void syscall_exit (void);
3343  
3344  #endif /* userprog/syscall.h */
3345 Index: src/vm/frame.c
3346 diff -u src/vm/frame.c~ src/vm/frame.c
3347 --- src/vm/frame.c~
3348 +++ src/vm/frame.c
3349 @@ -0,0 +1,161 @@
3350 +#include "vm/frame.h"
3351 +#include <stdio.h>
3352 +#include "vm/page.h"
3353 +#include "devices/timer.h"
3354 +#include "threads/init.h"
3355 +#include "threads/malloc.h"
3356 +#include "threads/palloc.h"
3357 +#include "threads/synch.h"
3358 +#include "threads/vaddr.h"
3359 +
3360 +static struct frame *frames;
3361 +static size_t frame_cnt;
3362 +
3363 +static struct lock scan_lock;
3364 +static size_t hand;
3365 +
3366 +/* Initialize the frame manager. */
3367 +void
3368 +frame_init (void) 
3369 +{
3370 +  void *base;
3371 +
3372 +  lock_init (&scan_lock);
3373 +  
3374 +  frames = malloc (sizeof *frames * ram_pages);
3375 +  if (frames == NULL)
3376 +    PANIC ("out of memory allocating page frames");
3377 +
3378 +  while ((base = palloc_get_page (PAL_USER)) != NULL) 
3379 +    {
3380 +      struct frame *f = &frames[frame_cnt++];
3381 +      lock_init (&f->lock);
3382 +      f->base = base;
3383 +      f->page = NULL;
3384 +    }
3385 +}
3386 +
3387 +/* Tries to allocate and lock a frame for PAGE.
3388 +   Returns the frame if successful, false on failure. */
3389 +static struct frame *
3390 +try_frame_alloc_and_lock (struct page *page) 
3391 +{
3392 +  size_t i;
3393 +
3394 +  lock_acquire (&scan_lock);
3395 +
3396 +  /* Find a free frame. */
3397 +  for (i = 0; i < frame_cnt; i++)
3398 +    {
3399 +      struct frame *f = &frames[i];
3400 +      if (!lock_try_acquire (&f->lock))
3401 +        continue;
3402 +      if (f->page == NULL) 
3403 +        {
3404 +          f->page = page;
3405 +          lock_release (&scan_lock);
3406 +          return f;
3407 +        } 
3408 +      lock_release (&f->lock);
3409 +    }
3410 +
3411 +  /* No free frame.  Find a frame to evict. */
3412 +  for (i = 0; i < frame_cnt * 2; i++) 
3413 +    {
3414 +      /* Get a frame. */
3415 +      struct frame *f = &frames[hand];
3416 +      if (++hand >= frame_cnt)
3417 +        hand = 0;
3418 +
3419 +      if (!lock_try_acquire (&f->lock))
3420 +        continue;
3421 +
3422 +      if (f->page == NULL) 
3423 +        {
3424 +          f->page = page;
3425 +          lock_release (&scan_lock);
3426 +          return f;
3427 +        } 
3428 +
3429 +      if (page_accessed_recently (f->page)) 
3430 +        {
3431 +          lock_release (&f->lock);
3432 +          continue;
3433 +        }
3434 +          
3435 +      lock_release (&scan_lock);
3436 +      
3437 +      /* Evict this frame. */
3438 +      if (!page_out (f->page))
3439 +        {
3440 +          lock_release (&f->lock);
3441 +          return NULL;
3442 +        }
3443 +
3444 +      f->page = page;
3445 +      return f;
3446 +    }
3447 +
3448 +  lock_release (&scan_lock);
3449 +  return NULL;
3450 +}
3451 +
3452 +/* Tries really hard to allocate and lock a frame for PAGE.
3453 +   Returns the frame if successful, false on failure. */
3454 +struct frame *
3455 +frame_alloc_and_lock (struct page *page) 
3456 +{
3457 +  size_t try;
3458 +
3459 +  for (try = 0; try < 3; try++) 
3460 +    {
3461 +      struct frame *f = try_frame_alloc_and_lock (page);
3462 +      if (f != NULL) 
3463 +        {
3464 +          ASSERT (lock_held_by_current_thread (&f->lock));
3465 +          return f; 
3466 +        }
3467 +      timer_msleep (1000);
3468 +    }
3469 +
3470 +  return NULL;
3471 +}
3472 +
3473 +/* Locks P's frame into memory, if it has one.
3474 +   Upon return, p->frame will not change until P is unlocked. */
3475 +void
3476 +frame_lock (struct page *p) 
3477 +{
3478 +  /* A frame can be asynchronously removed, but never inserted. */
3479 +  struct frame *f = p->frame;
3480 +  if (f != NULL) 
3481 +    {
3482 +      lock_acquire (&f->lock);
3483 +      if (f != p->frame)
3484 +        {
3485 +          lock_release (&f->lock);
3486 +          ASSERT (p->frame == NULL); 
3487 +        } 
3488 +    }
3489 +}
3490 +
3491 +/* Releases frame F for use by another page.
3492 +   F must be locked for use by the current process.
3493 +   Any data in F is lost. */
3494 +void
3495 +frame_free (struct frame *f)
3496 +{
3497 +  ASSERT (lock_held_by_current_thread (&f->lock));
3498 +          
3499 +  f->page = NULL;
3500 +  lock_release (&f->lock);
3501 +}
3502 +
3503 +/* Unlocks frame F, allowing it to be evicted.
3504 +   F must be locked for use by the current process. */
3505 +void
3506 +frame_unlock (struct frame *f) 
3507 +{
3508 +  ASSERT (lock_held_by_current_thread (&f->lock));
3509 +  lock_release (&f->lock);
3510 +}
3511 Index: src/vm/frame.h
3512 diff -u src/vm/frame.h~ src/vm/frame.h
3513 --- src/vm/frame.h~
3514 +++ src/vm/frame.h
3515 @@ -0,0 +1,23 @@
3516 +#ifndef VM_FRAME_H
3517 +#define VM_FRAME_H
3518 +
3519 +#include <stdbool.h>
3520 +#include "threads/synch.h"
3521 +
3522 +/* A physical frame. */
3523 +struct frame 
3524 +  {
3525 +    struct lock lock;           /* Prevent simultaneous access. */
3526 +    void *base;                 /* Kernel virtual base address. */
3527 +    struct page *page;          /* Mapped process page, if any. */
3528 +  };
3529 +
3530 +void frame_init (void);
3531 +
3532 +struct frame *frame_alloc_and_lock (struct page *);
3533 +void frame_lock (struct page *);
3534 +
3535 +void frame_free (struct frame *);
3536 +void frame_unlock (struct frame *);
3537 +
3538 +#endif /* vm/frame.h */
3539 Index: src/vm/page.c
3540 diff -u src/vm/page.c~ src/vm/page.c
3541 --- src/vm/page.c~
3542 +++ src/vm/page.c
3543 @@ -0,0 +1,294 @@
3544 +#include "vm/page.h"
3545 +#include <stdio.h>
3546 +#include <string.h>
3547 +#include "vm/frame.h"
3548 +#include "vm/swap.h"
3549 +#include "filesys/file.h"
3550 +#include "threads/malloc.h"
3551 +#include "threads/thread.h"
3552 +#include "userprog/pagedir.h"
3553 +#include "threads/vaddr.h"
3554 +
3555 +/* Maximum size of process stack, in bytes. */
3556 +#define STACK_MAX (1024 * 1024)
3557 +
3558 +/* Destroys a page, which must be in the current process's
3559 +   page table.  Used as a callback for hash_destroy(). */
3560 +static void
3561 +destroy_page (struct hash_elem *p_, void *aux UNUSED)
3562 +{
3563 +  struct page *p = hash_entry (p_, struct page, hash_elem);
3564 +  frame_lock (p);
3565 +  if (p->frame)
3566 +    frame_free (p->frame);
3567 +  free (p);
3568 +}
3569 +
3570 +
3571 +/* Destroys the current process's page table. */
3572 +void
3573 +page_exit (void) 
3574 +{
3575 +  struct hash *h = thread_current ()->pages;
3576 +  if (h != NULL)
3577 +    hash_destroy (h, destroy_page);
3578 +}
3579 +
3580 +/* Returns the page containing the given virtual ADDRESS,
3581 +   or a null pointer if no such page exists.
3582 +   Allocates stack pages as necessary. */
3583 +static struct page *
3584 +page_for_addr (const void *address) 
3585 +{
3586 +  if (address < PHYS_BASE) 
3587 +    {
3588 +      struct page p;
3589 +      struct hash_elem *e;
3590 +
3591 +      /* Find existing page. */
3592 +      p.addr = (void *) pg_round_down (address);
3593 +      e = hash_find (thread_current ()->pages, &p.hash_elem);
3594 +      if (e != NULL)
3595 +        return hash_entry (e, struct page, hash_elem);
3596 +
3597 +      /* No page.  Expand stack? */
3598 +      if (address >= PHYS_BASE - STACK_MAX
3599 +          && address >= thread_current ()->user_esp - 32)
3600 +        return page_allocate ((void *) address, false);
3601 +    }
3602 +  return NULL;
3603 +}
3604 +
3605 +/* Locks a frame for page P and pages it in.
3606 +   Returns true if successful, false on failure. */
3607 +static bool
3608 +do_page_in (struct page *p)
3609 +{
3610 +  /* Get a frame for the page. */
3611 +  p->frame = frame_alloc_and_lock (p);
3612 +  if (p->frame == NULL)
3613 +    return false;
3614 +
3615 +  /* Copy data into the frame. */
3616 +  if (p->sector != (disk_sector_t) -1) 
3617 +    {
3618 +      /* Get data from swap. */
3619 +      swap_in (p); 
3620 +    }
3621 +  else if (p->file != NULL) 
3622 +    {
3623 +      /* Get data from file. */
3624 +      off_t read_bytes = file_read_at (p->file, p->frame->base,
3625 +                                        p->file_bytes, p->file_offset);
3626 +      off_t zero_bytes = PGSIZE - read_bytes;
3627 +      memset (p->frame->base + read_bytes, 0, zero_bytes);
3628 +      if (read_bytes != p->file_bytes)
3629 +        printf ("bytes read (%"PROTd") != bytes requested (%"PROTd")\n",
3630 +                read_bytes, p->file_bytes);
3631 +    }
3632 +  else 
3633 +    {
3634 +      /* Provide all-zero page. */
3635 +      memset (p->frame->base, 0, PGSIZE);
3636 +    }
3637 +
3638 +  return true;
3639 +}
3640 +
3641 +/* Faults in the page containing FAULT_ADDR.
3642 +   Returns true if successful, false on failure. */
3643 +bool
3644 +page_in (void *fault_addr) 
3645 +{
3646 +  struct page *p;
3647 +  bool success;
3648 +
3649 +  /* Can't handle page faults without a hash table. */
3650 +  if (thread_current ()->pages == NULL) 
3651 +    return false;
3652 +
3653 +  p = page_for_addr (fault_addr);
3654 +  if (p == NULL) 
3655 +    return false; 
3656 +
3657 +  frame_lock (p);
3658 +  if (p->frame == NULL)
3659 +    {
3660 +      if (!do_page_in (p))
3661 +        return false;
3662 +    }
3663 +  ASSERT (lock_held_by_current_thread (&p->frame->lock));
3664 +    
3665 +  /* Install frame into page table. */
3666 +  success = pagedir_set_page (thread_current ()->pagedir, p->addr,
3667 +                              p->frame->base, !p->read_only);
3668 +
3669 +  /* Release frame. */
3670 +  frame_unlock (p->frame);
3671 +
3672 +  return success;
3673 +}
3674 +
3675 +/* Evicts page P.
3676 +   P must have a locked frame.
3677 +   Return true if successful, false on failure. */
3678 +bool
3679 +page_out (struct page *p) 
3680 +{
3681 +  bool dirty;
3682 +  bool ok;
3683 +
3684 +  ASSERT (p->frame != NULL);
3685 +  ASSERT (lock_held_by_current_thread (&p->frame->lock));
3686 +
3687 +  /* Mark page not present in page table, forcing accesses by the
3688 +     process to fault.  This must happen before checking the
3689 +     dirty bit, to prevent a race with the process dirtying the
3690 +     page. */
3691 +  pagedir_clear_page (p->thread->pagedir, p->addr);
3692 +
3693 +  /* Has the frame been modified? */
3694 +  dirty = pagedir_is_dirty (p->thread->pagedir, p->addr);
3695 +
3696 +  /* Write frame contents to disk if necessary. */
3697 +  if (p->file != NULL) 
3698 +    {
3699 +      if (dirty) 
3700 +        {
3701 +          if (p->private)
3702 +            ok = swap_out (p);
3703 +          else 
3704 +            ok = file_write_at (p->file, p->frame->base, p->file_bytes,
3705 +                                p->file_offset) == p->file_bytes;
3706 +        }
3707 +      else
3708 +        ok = true;
3709 +    }
3710 +  else
3711 +    ok = swap_out (p);
3712 +  if (ok) 
3713 +    {
3714 +      //memset (p->frame->base, 0xcc, PGSIZE);
3715 +      p->frame = NULL; 
3716 +    }
3717 +  return ok;
3718 +}
3719 +
3720 +/* Returns true if page P's data has been accessed recently,
3721 +   false otherwise.
3722 +   P must have a frame locked into memory. */
3723 +bool
3724 +page_accessed_recently (struct page *p) 
3725 +{
3726 +  bool was_accessed;
3727 +
3728 +  ASSERT (p->frame != NULL);
3729 +  ASSERT (lock_held_by_current_thread (&p->frame->lock));
3730 +
3731 +  was_accessed = pagedir_is_accessed (p->thread->pagedir, p->addr);
3732 +  if (was_accessed)
3733 +    pagedir_set_accessed (p->thread->pagedir, p->addr, false);
3734 +  return was_accessed;
3735 +}
3736 +
3737 +/* Adds a mapping for user virtual address VADDR to the page hash
3738 +   table.  Fails if VADDR is already mapped or if memory
3739 +   allocation fails. */
3740 +struct page *
3741 +page_allocate (void *vaddr, bool read_only)
3742 +{
3743 +  struct thread *t = thread_current ();
3744 +  struct page *p = malloc (sizeof *p);
3745 +  if (p != NULL) 
3746 +    {
3747 +      p->addr = pg_round_down (vaddr);
3748 +
3749 +      p->read_only = read_only;
3750 +      p->private = !read_only;
3751 +
3752 +      p->frame = NULL;
3753 +
3754 +      p->sector = (disk_sector_t) -1;
3755 +
3756 +      p->file = NULL;
3757 +      p->file_offset = 0;
3758 +      p->file_bytes = 0;
3759 +
3760 +      p->thread = thread_current ();
3761 +
3762 +      if (hash_insert (t->pages, &p->hash_elem) != NULL) 
3763 +        {
3764 +          /* Already mapped. */
3765 +          free (p);
3766 +          p = NULL;
3767 +        }
3768 +    }
3769 +  return p;
3770 +}
3771 +
3772 +/* Evicts the page containing address VADDR
3773 +   and removes it from the page table. */
3774 +void
3775 +page_deallocate (void *vaddr) 
3776 +{
3777 +  struct page *p = page_for_addr (vaddr);
3778 +  ASSERT (p != NULL);
3779 +  frame_lock (p);
3780 +  if (p->frame)
3781 +    {
3782 +      struct frame *f = p->frame;
3783 +      if (p->file && !p->private) 
3784 +        page_out (p); 
3785 +      frame_free (f);
3786 +    }
3787 +  hash_delete (thread_current ()->pages, &p->hash_elem);
3788 +  free (p);
3789 +}
3790 +
3791 +/* Returns a hash value for the page that E refers to. */
3792 +unsigned
3793 +page_hash (const struct hash_elem *e, void *aux UNUSED) 
3794 +{
3795 +  const struct page *p = hash_entry (e, struct page, hash_elem);
3796 +  return ((uintptr_t) p->addr) >> PGBITS;
3797 +}
3798 +
3799 +/* Returns true if page A precedes page B. */
3800 +bool
3801 +page_less (const struct hash_elem *a_, const struct hash_elem *b_,
3802 +           void *aux UNUSED) 
3803 +{
3804 +  const struct page *a = hash_entry (a_, struct page, hash_elem);
3805 +  const struct page *b = hash_entry (b_, struct page, hash_elem);
3806 +  
3807 +  return a->addr < b->addr;
3808 +}
3809 +
3810 +/* Tries to lock the page containing ADDR into physical memory.
3811 +   If WILL_WRITE is true, the page must be writeable;
3812 +   otherwise it may be read-only.
3813 +   Returns true if successful, false on failure. */
3814 +bool
3815 +page_lock (const void *addr, bool will_write) 
3816 +{
3817 +  struct page *p = page_for_addr (addr);
3818 +  if (p == NULL || (p->read_only && will_write))
3819 +    return false;
3820 +  
3821 +  frame_lock (p);
3822 +  if (p->frame == NULL)
3823 +    return (do_page_in (p)
3824 +            && pagedir_set_page (thread_current ()->pagedir, p->addr,
3825 +                                 p->frame->base, !p->read_only)); 
3826 +  else
3827 +    return true;
3828 +}
3829 +
3830 +/* Unlocks a page locked with page_lock(). */
3831 +void
3832 +page_unlock (const void *addr) 
3833 +{
3834 +  struct page *p = page_for_addr (addr);
3835 +  ASSERT (p != NULL);
3836 +  frame_unlock (p->frame);
3837 +}
3838 Index: src/vm/page.h
3839 diff -u src/vm/page.h~ src/vm/page.h
3840 --- src/vm/page.h~
3841 +++ src/vm/page.h
3842 @@ -0,0 +1,50 @@
3843 +#ifndef VM_PAGE_H
3844 +#define VM_PAGE_H
3845 +
3846 +#include <hash.h>
3847 +#include "devices/disk.h"
3848 +#include "filesys/off_t.h"
3849 +#include "threads/synch.h"
3850 +
3851 +/* Virtual page. */
3852 +struct page 
3853 +  {
3854 +    /* Immutable members. */
3855 +    void *addr;                 /* User virtual address. */
3856 +    bool read_only;             /* Read-only page? */
3857 +    struct thread *thread;      /* Owning thread. */
3858 +
3859 +    /* Accessed only in owning process context. */
3860 +    struct hash_elem hash_elem; /* struct thread `pages' hash element. */
3861 +
3862 +    /* Set only in owning process context with frame->frame_lock held.
3863 +       Cleared only with scan_lock and frame->frame_lock held. */
3864 +    struct frame *frame;        /* Page frame. */
3865 +
3866 +    /* Swap information, protected by frame->frame_lock. */
3867 +    disk_sector_t sector;       /* Starting sector of swap area, or -1. */
3868 +    
3869 +    /* Memory-mapped file information, protected by frame->frame_lock. */
3870 +    bool private;               /* False to write back to file,
3871 +                                   true to write back to swap. */
3872 +    struct file *file;          /* File. */
3873 +    off_t file_offset;          /* Offset in file. */
3874 +    off_t file_bytes;           /* Bytes to read/write, 1...PGSIZE. */
3875 +  };
3876 +
3877 +void page_exit (void);
3878 +
3879 +struct page *page_allocate (void *, bool read_only);
3880 +void page_deallocate (void *vaddr);
3881 +
3882 +bool page_in (void *fault_addr);
3883 +bool page_out (struct page *);
3884 +bool page_accessed_recently (struct page *);
3885 +
3886 +bool page_lock (const void *, bool will_write);
3887 +void page_unlock (const void *);
3888 +
3889 +hash_hash_func page_hash;
3890 +hash_less_func page_less;
3891 +
3892 +#endif /* vm/page.h */
3893 Index: src/vm/swap.c
3894 diff -u src/vm/swap.c~ src/vm/swap.c
3895 --- src/vm/swap.c~
3896 +++ src/vm/swap.c
3897 @@ -0,0 +1,85 @@
3898 +#include "vm/swap.h"
3899 +#include <bitmap.h>
3900 +#include <debug.h>
3901 +#include <stdio.h>
3902 +#include "vm/frame.h"
3903 +#include "vm/page.h"
3904 +#include "devices/disk.h"
3905 +#include "threads/synch.h"
3906 +#include "threads/vaddr.h"
3907 +
3908 +/* The swap disk. */
3909 +static struct disk *swap_disk;
3910 +
3911 +/* Used swap pages. */
3912 +static struct bitmap *swap_bitmap;
3913 +
3914 +/* Protects swap_bitmap. */
3915 +static struct lock swap_lock;
3916 +
3917 +/* Number of sectors per page. */
3918 +#define PAGE_SECTORS (PGSIZE / DISK_SECTOR_SIZE)
3919 +
3920 +/* Sets up swap. */
3921 +void
3922 +swap_init (void) 
3923 +{
3924 +  swap_disk = disk_get (1, 1);
3925 +  if (swap_disk == NULL) 
3926 +    {
3927 +      printf ("no swap disk--swap disabled\n");
3928 +      swap_bitmap = bitmap_create (0);
3929 +    }
3930 +  else
3931 +    swap_bitmap = bitmap_create (disk_size (swap_disk) / PAGE_SECTORS);
3932 +  if (swap_bitmap == NULL)
3933 +    PANIC ("couldn't create swap bitmap");
3934 +  lock_init (&swap_lock);
3935 +}
3936 +
3937 +/* Swaps in page P, which must have a locked frame
3938 +   (and be swapped out). */
3939 +void
3940 +swap_in (struct page *p) 
3941 +{
3942 +  size_t i;
3943 +  
3944 +  ASSERT (p->frame != NULL);
3945 +  ASSERT (lock_held_by_current_thread (&p->frame->lock));
3946 +  ASSERT (p->sector != (disk_sector_t) -1);
3947 +
3948 +  for (i = 0; i < PAGE_SECTORS; i++)
3949 +    disk_read (swap_disk, p->sector + i,
3950 +               p->frame->base + i * DISK_SECTOR_SIZE);
3951 +  bitmap_reset (swap_bitmap, p->sector / PAGE_SECTORS);
3952 +  p->sector = (disk_sector_t) -1;
3953 +}
3954 +
3955 +/* Swaps out page P, which must have a locked frame. */
3956 +bool
3957 +swap_out (struct page *p) 
3958 +{
3959 +  size_t slot;
3960 +  size_t i;
3961 +
3962 +  ASSERT (p->frame != NULL);
3963 +  ASSERT (lock_held_by_current_thread (&p->frame->lock));
3964 +
3965 +  lock_acquire (&swap_lock);
3966 +  slot = bitmap_scan_and_flip (swap_bitmap, 0, 1, false);
3967 +  lock_release (&swap_lock);
3968 +  if (slot == BITMAP_ERROR) 
3969 +    return false; 
3970 +
3971 +  p->sector = slot * PAGE_SECTORS;
3972 +  for (i = 0; i < PAGE_SECTORS; i++)
3973 +    disk_write (swap_disk, p->sector + i,
3974 +                p->frame->base + i * DISK_SECTOR_SIZE);
3975 +  
3976 +  p->private = false;
3977 +  p->file = NULL;
3978 +  p->file_offset = 0;
3979 +  p->file_bytes = 0;
3980 +
3981 +  return true;
3982 +}
3983 Index: src/vm/swap.h
3984 diff -u src/vm/swap.h~ src/vm/swap.h
3985 --- src/vm/swap.h~
3986 +++ src/vm/swap.h
3987 @@ -0,0 +1,11 @@
3988 +#ifndef VM_SWAP_H
3989 +#define VM_SWAP_H 1
3990 +
3991 +#include <stdbool.h>
3992 +
3993 +struct page;
3994 +void swap_init (void);
3995 +void swap_in (struct page *);
3996 +bool swap_out (struct page *);
3997 +
3998 +#endif /* vm/swap.h */