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