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