Add suggested implementations for filesys syscalls.
[pintos-anon] / doc / userprog.texi
1 @node Project 2--User Programs, Project 3--Virtual Memory, Project 1--Threads, Top
2 @chapter Project 2: User Programs
3
4 Now that you've worked with Pintos and are becoming familiar with its
5 infrastructure and thread package, it's time to start working on the
6 parts of the system that allow running user programs.
7 The base code already supports loading and
8 running user programs, but no I/O or interactivity
9 is possible.  In this project, you will enable programs to interact with
10 the OS via system calls.
11
12 You will be working out of the @file{userprog} directory for this
13 assignment.  However, you will also be interacting with almost every
14 other part of the code for this assignment. We will describe the
15 relevant parts below.
16
17 You can build project 2 on top of your project 1 submission or you can
18 start with a fresh copy.  No code from project 1 is required for this
19 assignment.  The ``alarm clock'' functionality may be useful in later
20 projects, but it is not strictly required.
21
22 @menu
23 * Project 2 Background::        
24 * Project 2 Requirements::      
25 * Project 2 FAQ::               
26 * 80x86 Calling Convention::    
27 @end menu
28
29 @node Project 2 Background
30 @section Background
31
32 Up to now, all of the code you have run under Pintos has been part
33 of the operating system kernel.  This means, for example, that all the
34 test code from the last assignment ran as part of the kernel, with
35 full access to privileged parts of the system.  Once we start running
36 user programs on top of the operating system, this is no longer true.
37 This project deals with consequences of the change.
38
39 We allow more than one user program to run at a time.  User
40 programs are written and compiled to work under the illusion that they
41 have the entire machine.  This means that when you load and
42 run multiple processes at a time, you must manage memory, scheduling,
43 and other state correctly to maintain this illusion.
44
45 In the previous project, we compiled our test code directly into your
46 kernel, so we had to require certain specific function interfaces within
47 the kernel.  From now on, we will test your operating system by running
48 user programs.  This gives you much greater freedom.  You must make sure
49 that the user program interface meets the specifications described here,
50 but given that constraint you are free to restructure or rewrite kernel
51 code however you wish.
52
53 @menu
54 * Project 2 Source Files::      
55 * Using the File System::       
56 * How User Programs Work::      
57 * Virtual Memory Layout::       
58 * Accessing User Memory::       
59 @end menu
60
61 @node Project 2 Source Files
62 @subsection Source Files
63
64 The easiest way to get an overview of the programming you will be
65 doing is to simply go over each part you'll be working with.  In
66 @file{userprog}, you'll find a small number of files, but here is
67 where the bulk of your work will be:
68
69 @table @file
70 @item process.c
71 @itemx process.h
72 Loads ELF binaries and starts processes.
73
74 @item pagedir.c
75 @itemx pagedir.h
76 A simple manager for 80@var{x}86 page directories and page tables.
77 Although you probably won't want to modify this code for this project,
78 you may want to call some of its functions.
79
80 @item syscall.c
81 @itemx syscall.h
82 Whenever a user process wants to access some kernel functionality, it
83 invokes a system call.  This is a skeleton system call
84 handler.  Currently, it just prints a message and terminates the user
85 process.  In part 2 of this project you will add code to do everything
86 else needed by system calls.
87
88 @item exception.c
89 @itemx exception.h
90 When a user process performs a privileged or prohibited operation, it
91 traps into the kernel as an ``exception'' or ``fault.''@footnote{We
92 will treat these terms as synonymous.  There is no standard
93 distinction between them, although Intel processor manuals define
94 them slightly differently on 80@var{x}86.}  These files handle
95 exceptions.  Currently all exceptions simply print a message and
96 terminate the process.  Some, but not all, solutions to project 2
97 require modifying @func{page_fault} in this file.
98
99 @item gdt.c
100 @itemx gdt.h
101 The 80@var{x}86 is a segmented architecture.  The Global Descriptor
102 Table (GDT) is a table that describes the segments in use.  These
103 files set up the GDT.  @strong{You should not need to modify these
104 files for any of the projects.}  You can read the code if
105 you're interested in how the GDT works.
106
107 @item tss.c
108 @itemx tss.h
109 The Task-State Segment (TSS) is used for 80@var{x}86 architectural
110 task switching.  Pintos uses the TSS only for switching stacks when a
111 user process enters an interrupt handler, as does Linux.  @strong{You
112 should not need to modify these files for any of the projects.}
113 You can read the code if you're interested in how the TSS
114 works.
115 @end table
116
117 @node Using the File System
118 @subsection Using the File System
119
120 You will need to use some file system code for this project.  First,
121 user programs are loaded from the file system.  Second, many of the
122 system calls you must implement deal with the file system.  However,
123 the focus of this project is not on the file system code, so we have
124 provided a simple file system in the @file{filesys} directory.  You
125 will want to look over the @file{filesys.h} and @file{file.h}
126 interfaces to understand how to use the file system, and especially
127 its many limitations.  @strong{You should not modify the file system
128 code for this project.}  Proper use of the file system routines now
129 will make life much easier for project 4, when you improve the file
130 system implementation.  Until then, you will have to put up with the
131 following limitations:
132
133 @itemize @bullet
134 @item
135 No synchronization.  Concurrent accesses will interfere with one
136 another.  You should use a global lock to ensure that only one process at a
137 time is executing file system code.
138
139 @item
140 File size is fixed at creation time.  The root directory is
141 represented as a file, so the number of files that may be created is also
142 limited.
143
144 @item
145 File data is allocated as a single extent, that is, data in a single
146 file must occupy a contiguous range of sectors on disk.  External
147 fragmentation can therefore become a serious problem as a file system is
148 used over time.
149
150 @item
151 No subdirectories.
152
153 @item
154 File names are limited to 14 characters.
155
156 @item
157 A system crash mid-operation may corrupt the disk in a way
158 that cannot be repaired automatically.  There is no file system repair
159 tool anyway.
160 @end itemize
161
162 One important feature is included:
163
164 @itemize @bullet
165 @item
166 Unix-like semantics for @func{filesys_remove} are implemented.
167 That is, if a file is open when it is removed, its blocks
168 are not deallocated and it may still be accessed by any
169 threads that have it open until the last one closes it.  @xref{Removing
170 an Open File}, for more information.
171 @end itemize
172
173 You need to be able to create simulated disks.  The
174 @command{pintos-mkdisk} program provides this functionality.  From the
175 @file{userprog/build} directory, execute @code{pintos-mkdisk fs.dsk 2}.
176 This command creates a 2 MB simulated disk named @file{fs.dsk}.  Then
177 format the disk by passing @option{-f -q} on the kernel's command
178 line: @code{pintos -f -q}.  The @option{-f} option causes the disk to be
179 formatted, and @option{-q} causes Pintos to exit as soon as the format
180 is done.
181
182 You'll need a way to copy files in and out of the simulated file system.
183 The @code{pintos} @option{-p} (``put'') and @option{-g} (``get'')
184 options do this.  To copy @file{@var{file}} into the
185 Pintos file system, use the command @file{pintos -p @var{file} -- -q}.
186 (The @samp{--} is needed because @option{-p} is for the @command{pintos}
187 script, not for the simulated kernel.)  To copy it to the Pintos file
188 system under the name @file{@var{newname}}, add @option{-a
189 @var{newname}}: @file{pintos -p @var{file} -a @var{newname} -- -q}.  The
190 commands for copying files out of a VM are similar, but substitute
191 @option{-g} for @option{-p}.
192
193 Incidentally, these commands work by passing special commands
194 @command{put} and @command{get} on the kernel's command line and copying
195 to and from a special simulated ``scratch'' disk.  If you're very
196 curious, you can look at the @command{pintos} program as well as
197 @file{filesys/fsutil.c} to learn the implementation details.
198
199 Here's a summary of how to create and format a disk, copy the
200 @command{echo} program into the new disk, and then run @command{echo},
201 passing argument @code{x}.  (Argument passing won't work until
202 you've implemented it.)  It assumes
203 that you've already built the
204 examples in @file{examples} and that the current directory is
205 @file{userprog/build}:
206
207 @example
208 pintos-mkdisk fs.dsk 2
209 pintos -f -q
210 pintos -p ../../examples/echo -a echo -- -q
211 pintos -q run 'echo x'
212 @end example
213
214 The three final steps can actually be combined into a single command:
215
216 @example
217 pintos-mkdisk fs.dsk 2
218 pintos -p ../../examples/echo -a echo -- -f -q run 'echo x'
219 @end example
220
221 If you don't want to keep the file system disk around for later use or
222 inspection, you can even combine all four steps into a single command.
223 The @code{--fs-disk=2} option creates a temporary disk just for the
224 duration of the @command{pintos} run.  The Pintos automatic test suite
225 makes extensive use of this syntax:
226
227 @example
228 pintos --fs-disk=2 -p ../../examples/echo -a echo -- -f -q run 'echo x'
229 @end example
230
231 You can delete a file from the Pintos file system using the @code{rm
232 @var{file}} kernel action, e.g.@: @code{pintos -q rm @var{file}}.  Also,
233 @command{ls} lists the files in the file system and @code{cat
234 @var{file}} prints a file's contents to the display.
235
236 @node How User Programs Work
237 @subsection How User Programs Work
238
239 Pintos can run normal C programs.  In fact, Pintos can run any program
240 you want, as long as it's compiled into the proper file format and uses
241 only the system calls you implement.  Notably, @func{malloc} cannot be
242 implemented because none of the system calls required for this project
243 allow for memory allocation.  Pintos also can't run programs that use
244 floating point operations, since the kernel doesn't save and restore the
245 processor's floating-point unit when switching threads.
246
247 The @file{src/examples} directory contains a few sample user
248 programs.  The @file{Makefile} in this directory
249 compiles the provided examples, and you can edit it
250 compile your own programs as well.
251
252 Pintos loads @dfn{ELF} executables.  ELF is a file format used by Linux,
253 Solaris, and many other operating systems for object files,
254 shared libraries, and executables.  You can actually use any compiler
255 and linker that output 80@var{x}86 ELF executables to produce programs
256 for Pintos.  (We've provided compilers and linkers that should do just
257 fine.)
258
259 You should realize immediately that, until you copy a
260 test program to the emulated disk, Pintos will be unable to do
261 useful work.  You won't be able to do
262 interesting things until you copy a variety of programs to the disk.
263 You might want to create a clean reference disk and copy that
264 over whenever you trash your @file{fs.dsk} beyond a useful state,
265 which may happen occasionally while debugging.
266
267 @node Virtual Memory Layout
268 @subsection Virtual Memory Layout
269
270 Virtual memory in Pintos is divided into two regions: user virtual
271 memory and kernel virtual memory.  User virtual memory ranges from
272 virtual address 0 up to @code{PHYS_BASE}, which is defined in
273 @file{threads/mmu.h} and defaults to @t{0xc0000000} (3 GB).  Kernel
274 virtual memory occupies the rest of the virtual address space, from
275 @code{PHYS_BASE} up to 4 GB.
276
277 User virtual memory is per-process.
278 When the kernel switches from one process to another, it
279 also switches user virtual address spaces by changing the processor's
280 page directory base register (see @func{pagedir_activate} in
281 @file{userprog/pagedir.c}).  @struct{thread} contains a pointer to a
282 process's page directory.
283
284 Kernel virtual memory is global.  It is always mapped the same way,
285 regardless of what user process or kernel thread is running.  In
286 Pintos, kernel virtual memory is mapped one-to-one to physical
287 memory, starting at @code{PHYS_BASE}.  That is, virtual address
288 @code{PHYS_ADDR} accesses physical
289 address 0, virtual address @code{PHYS_ADDR} + @t{0x1234} access
290 physical address @t{0x1234}, and so on up to the size of the machine's
291 physical memory.
292
293 A user program can only access its own user virtual memory.  An attempt to
294 access kernel virtual memory causes a page fault, handled by
295 @func{page_fault} in @file{userprog/exception.c}, and the process
296 will be terminated.  Kernel threads can access both kernel virtual
297 memory and, if a user process is running, the user virtual memory of
298 the running process.  However, even in the kernel, an attempt to
299 access memory at a user virtual address that doesn't have a page
300 mapped into it will cause a page fault.
301
302 You must handle memory fragmentation gracefully, that is, a process that
303 needs @var{N} pages of user virtual memory must not require those pages
304 to be contiguous in kernel virtual memory.
305
306 @menu
307 * Typical Memory Layout::       
308 @end menu
309
310 @node Typical Memory Layout
311 @subsubsection Typical Memory Layout
312
313 Conceptually, each process is
314 free to lay out its own user virtual memory however it
315 chooses.  In practice, user virtual memory is laid out like this:
316
317 @html
318 <CENTER>
319 @end html
320 @example
321 @group
322    PHYS_BASE +----------------------------------+
323              |            user stack            |
324              |                 |                |
325              |                 |                |
326              |                 V                |
327              |          grows downward          |
328              |                                  |
329              |                                  |
330              |                                  |
331              |                                  |
332              |           grows upward           |
333              |                 ^                |
334              |                 |                |
335              |                 |                |
336              +----------------------------------+
337              | uninitialized data segment (BSS) |
338              +----------------------------------+
339              |     initialized data segment     |
340              +----------------------------------+
341              |           code segment           |
342   0x08048000 +----------------------------------+
343              |                                  |
344              |                                  |
345              |                                  |
346              |                                  |
347              |                                  |
348            0 +----------------------------------+
349 @end group
350 @end example
351 @html
352 </CENTER>
353 @end html
354
355 In this project, the user stack is fixed in size, but in project 3 it
356 will be allowed to grow.  Traditionally, the size of the uninitialized
357 data segment can be adjusted with a system call, but you will not have
358 to implement this.
359
360 The code segment in Pintos starts at user virtual address
361 @t{0x08084000}, approximately 128 MB from the bottom of the address
362 space.  This value is specified in @bibref{SysV-i386} and has no deep
363 significance.
364
365 The linker sets the layout of a user program in memory, as directed by a
366 ``linker script'' that tells it the names and locations of the various
367 program segments.  You can learn more about linker scripts by reading
368 the ``Scripts'' chapter in the linker manual, accessible via @samp{info
369 ld}.
370
371 To view the layout of a particular executable, run @command{objdump}
372 (80@var{x}86) or @command{i386-elf-objdump} (SPARC) with the @option{-p}
373 option.
374
375 @node Accessing User Memory
376 @subsection Accessing User Memory
377
378 As part of a system
379 call, the kernel must often access memory through pointers provided by a user
380 program.  The kernel must be very careful about doing so, because
381 the user can pass a null pointer, a pointer to
382 unmapped virtual memory, or a pointer to kernel virtual address space
383 (above @code{PHYS_BASE}).  All of these types of invalid pointers must
384 be rejected without harm to the kernel or other running processes, by
385 terminating the offending process and freeing its resources.
386
387 There are at least two reasonable ways to do this correctly.  The
388 first method is to verify
389 the validity of a user-provided pointer, then dereference it.  If you
390 choose this route, you'll want to look at the functions in
391 @file{userprog/pagedir.c} and in @file{threads/mmu.h}.  This is the
392 simplest way to handle user memory access.
393
394 The second method is to check only that a user
395 pointer points below @code{PHYS_BASE}, then dereference it.
396 An invalid user pointer will cause a ``page fault'' that you can
397 handle by modifying the code for @func{page_fault} in
398 @file{userprog/exception.cc}.  This technique is normally faster
399 because it takes advantage of the processor's MMU, so it tends to be
400 used in real kernels (including Linux).
401
402 In either case, you need to make sure not to ``leak'' resources.  For
403 example, suppose that your system call has acquired a lock or
404 allocated a page of memory.  If you encounter an invalid user pointer
405 afterward, you must still be sure to release the lock or free the page
406 of memory.  If you choose to verify user pointers before dereferencing
407 them, this should be straightforward.  It's more difficult to handle
408 if an invalid pointer causes a page fault,
409 because there's no way to return an error code from a memory access.
410 Therefore, for those who want to try the latter technique, we'll
411 provide a little bit of helpful code:
412
413 @verbatim
414 /* Tries to copy a byte from user address USRC to kernel address KDST.
415    Returns true if successful, false if USRC is invalid. */
416 static inline bool get_user (uint8_t *kdst, const uint8_t *usrc) {
417   int eax;
418   asm ("movl $1f, %%eax; movb %2, %%al; movb %%al, %0; 1:"
419        : "=m" (*kdst), "=&a" (eax) : "m" (*usrc));
420   return eax != 0;
421 }
422
423 /* Tries to write BYTE to user address UDST.
424    Returns true if successful, false if UDST is invalid. */
425 static inline bool put_user (uint8_t *udst, uint8_t byte) {
426   int eax;
427   asm ("movl $1f, %%eax; movb %b2, %0; 1:"
428        : "=m" (*udst), "=&a" (eax) : "r" (byte));
429   return eax != 0;
430 }
431 @end verbatim
432
433 Each of these functions assumes that the user address has already been
434 verified to be below @code{PHYS_BASE}.  They also assume that you've
435 modified @func{page_fault} so that a page fault in the kernel causes
436 @code{eax} to be set to 0 and its former value copied into @code{eip}.
437
438 @node Project 2 Requirements
439 @section Requirements
440
441 @menu
442 * Project 2 Design Document::   
443 * Process Termination Messages::  
444 * Argument Passing::            
445 * System Calls::                
446 * Denying Writes to Executables::  
447 @end menu
448
449 @node Project 2 Design Document
450 @subsection Design Document
451
452 Before you turn in your project, you must copy @uref{userprog.tmpl, ,
453 the project 2 design document template} into your source tree under the
454 name @file{pintos/src/userprog/DESIGNDOC} and fill it in.  We recommend
455 that you read the design document template before you start working on
456 the project.  @xref{Project Documentation}, for a sample design document
457 that goes along with a fictitious project.
458
459 @node Process Termination Messages
460 @subsection Process Termination Messages
461
462 Whenever a user process terminates, because it called @code{exit}
463 or for any other reason, print the process's name
464 and exit code, formatted as if printed by @code{printf ("%s:
465 exit(%d)\n", @dots{});}.  The name printed should be the full name
466 passed to @func{process_execute}, omitting command-line arguments.
467 Do not print these messages when a kernel thread that is not a user
468 process terminates, or
469 when the @code{halt} system call is invoked.  The message is optional
470 when a process fails to load.
471
472 Aside from this, don't print any other
473 messages that Pintos as provided doesn't already print.  You may find
474 extra messages useful during debugging, but they will confuse the
475 grading scripts and thus lower your score.
476
477 @node Argument Passing
478 @subsection Argument Passing
479
480 Currently, @func{process_execute} does not support passing arguments to
481 new processes.  Implement this functionality, by extending
482 @func{process_execute} so that instead of simply taking a program file
483 name as its argument, it divides it into words at spaces.  The first
484 word is the program name, the second word is the first argument, and so
485 on.  That is, @code{process_execute("grep foo bar")} should run
486 @command{grep} passing two arguments @code{foo} and @code{bar}.
487
488 Within a command line, multiple spaces are equivalent to a single space,
489 so that @code{process_execute("grep foo bar")} is equivalent to our
490 original example.  You can impose a reasonable limit on the length of
491 the command line arguments.  For example, you could limit the arguments
492 to those that will fit in a single page (4 kB).
493
494 You can parse argument strings any way you like.  If you're lost,
495 look at @func{strtok_r}, prototyped in @file{lib/string.h} and
496 implemented with thorough comments in @file{lib/string.c}.  You can
497 find more about it by looking at the man page (run @code{man strtok_r}
498 at the prompt).
499
500 @xref{Program Startup Details}, for information on exactly how you
501 need to set up the stack.
502
503 @node System Calls
504 @subsection System Calls
505
506 Implement the system call handler in @file{userprog/syscall.c}.  The
507 skeleton implementation we provide ``handles'' system calls by
508 terminating the process.  It will need to retrieve the system call
509 number, then any system call arguments, and carry appropriate actions.
510
511 Implement the following system calls.  The prototypes listed are those
512 seen by a user program that includes @file{lib/user/syscall.h}.  System
513 call numbers for each system call are defined in
514 @file{lib/syscall-nr.h}:
515
516 @deftypefn {System Call} void halt (void)
517 Terminates Pintos by calling @func{power_off} (declared in
518 @file{threads/init.h}).  Note that this should be seldom used, since
519 then you lose some information about possible deadlock situations,
520 etc.
521 @end deftypefn
522
523 @deftypefn {System Call} void exit (int @var{status})
524 Terminates the current user program, returning @var{status} to the
525 kernel.  If the process's parent @code{wait}s for it (see below), this
526 is the status
527 that will be returned.  Conventionally, a @var{status} of 0 indicates
528 success and nonzero values indicate errors.
529 @end deftypefn
530
531 @deftypefn {System Call} pid_t exec (const char *@var{cmd_line})
532 Runs the executable whose name is given in @var{cmd_line}, passing any
533 given arguments, and returns the new process's program id (pid).  Must
534 return pid -1, which otherwise should not be a valid pid, if
535 the program cannot load or run for any reason.
536 @end deftypefn
537
538 @deftypefn {System Call} int wait (pid_t @var{pid})
539 Waits for process @var{pid} to die and returns the status it passed to
540 @code{exit}.  Returns -1 if @var{pid}
541 was terminated by the kernel (i.e.@: killed due to an exception).  If
542 @var{pid} is invalid or if it was not a child of the
543 calling thread, or if @code{wait} has already been successfully
544 called for the given @var{pid}, returns -1 immediately, without
545 waiting.
546
547 You must ensure that Pintos does not terminate until the initial
548 process exits.  The supplied Pintos code tries to do this by calling
549 @func{process_wait} (in @file{userprog/process.c}) from @func{main}
550 (in @file{threads/init.c}).  We suggest that you implement
551 @func{process_wait} according to the comment at the top of the
552 function and then implement the @code{wait} system call in terms of
553 @func{process_wait}.
554
555 All of a process's resources, including its @struct{thread}, must be
556 freed whether its parent ever waits for it or not, and regardless of
557 whether the child exits before or after its parent.
558
559 Children are not inherited: if @var{A} has child @var{B} and
560 @var{B} has child @var{C}, then @code{wait(C)} always returns immediately
561 when called from @var{A}, even if @var{B} is dead.
562
563 Consider all the ways a wait can occur: nested waits (@var{A} waits
564 for @var{B}, then @var{B} waits for @var{C}), multiple waits (@var{A}
565 waits for @var{B}, then @var{A} waits for @var{C}), and so on.
566 @end deftypefn
567
568 @deftypefn {System Call} bool create (const char *@var{file}, unsigned @var{initial_size})
569 Creates a new file called @var{file} initially @var{initial_size} bytes
570 in size.  Returns true if successful, false otherwise.
571
572 Consider implementing this function in terms of @func{filesys_create}.
573 @end deftypefn
574
575 @deftypefn {System Call} bool remove (const char *@var{file})
576 Deletes the file called @var{file}.  Returns true if successful, false
577 otherwise.
578
579 Consider implementing this function in terms of @func{filesys_remove}.
580 @end deftypefn
581
582 @deftypefn {System Call} int open (const char *@var{file})
583 Opens the file called @var{file}.  Returns a nonnegative integer handle
584 called a ``file descriptor'' (fd), or -1 if the file could not be
585 opened.  All open files associated with a process should be closed
586 when the process exits or is terminated.
587
588 File descriptors numbered 0 and 1 are reserved for the console: fd 0
589 is standard input (@code{stdin}), fd 1 is standard output
590 (@code{stdout}).  These special file descriptors are valid as system
591 call arguments only as explicitly described below.
592
593 Consider implementing this function in terms of @func{filesys_open}.
594 @end deftypefn
595
596 @deftypefn {System Call} int filesize (int @var{fd})
597 Returns the size, in bytes, of the file open as @var{fd}.
598
599 Consider implementing this function in terms of @func{file_length}.
600 @end deftypefn
601
602 @deftypefn {System Call} int read (int @var{fd}, void *@var{buffer}, unsigned @var{size})
603 Reads @var{size} bytes from the file open as @var{fd} into
604 @var{buffer}.  Returns the number of bytes actually read (0 at end of
605 file), or -1 if the file could not be read (due to a condition other
606 than end of file).  Fd 0 reads from the keyboard using
607 @func{kbd_getc}.
608
609 Consider implementing this function in terms of @func{file_read}.
610 @end deftypefn
611
612 @deftypefn {System Call} int write (int @var{fd}, const void *@var{buffer}, unsigned @var{size})
613 Writes @var{size} bytes from @var{buffer} to the open file @var{fd}.
614 Returns the number of bytes actually written, or -1 if the file could
615 not be written.
616
617 Writing past end-of-file would normally extend the file, but file growth
618 is not implemented by the basic file system.  The expected behavior is
619 to write as many bytes as possible up to end-of-file and return the
620 actual number written, or -1 if no bytes could be written at all.
621
622 Fd 1 writes to the console.  Your code to write to the console should
623 write all of @var{buffer} in one call to @func{putbuf}, at least as
624 long as @var{size} is not bigger than a few hundred bytes.  Otherwise,
625 lines of text output by different processes may end up interleaved on
626 the console, confusing both human readers and our grading scripts.
627
628 Consider implementing this function in terms of @func{file_write}.
629 @end deftypefn
630
631 @deftypefn {System Call} void seek (int @var{fd}, unsigned @var{position})
632 Changes the next byte to be read or written in open file @var{fd} to
633 @var{position}, expressed in bytes from the beginning of the file.
634 (Thus, a @var{position} of 0 is the file's start.)
635
636 A seek past the current end of a file is not an error.  A later read
637 obtains 0 bytes, indicating end of file.  A later write extends the
638 file, filling any unwritten gap with zeros.  (However, in Pintos files
639 have a fixed length until project 4 is complete, so writes past end of
640 file will return an error.)  These semantics are implemented in the
641 file system and do not require any special effort in system call
642 implementation.
643
644 Consider implementing this function in terms of @func{file_seek}.
645 @end deftypefn
646
647 @deftypefn {System Call} unsigned tell (int @var{fd})
648 Returns the position of the next byte to be read or written in open
649 file @var{fd}, expressed in bytes from the beginning of the file.
650
651 Consider implementing this function in terms of @func{file_tell}.
652 @end deftypefn
653
654 @deftypefn {System Call} void close (int @var{fd})
655 Closes file descriptor @var{fd}.
656
657 Consider implementing this function in terms of @func{file_close}.
658 @end deftypefn
659
660 The file defines other syscalls.  Ignore them for now.  You will
661 implement some of them in project 3 and the rest in project 4, so be
662 sure to design your system with extensibility in mind.
663
664 To implement syscalls, you need to provide ways to read and write data
665 in user virtual address space.
666 You need this ability before you can
667 even obtain the system call number, because the system call number is
668 on the user's stack in the user's virtual address space.
669 This can be a bit tricky: what if the user provides an invalid
670 pointer, a pointer into kernel memory, or a block
671 partially in one of those regions?  You should handle these cases by
672 terminating the user process.  We recommend
673 writing and testing this code before implementing any other system
674 call functionality.
675
676 You must synchronize system calls so that
677 any number of user processes can make them at once.  In particular, it
678 is not safe to call into the file system code provided in the
679 @file{filesys} directory from multiple threads at once.  For now, we
680 recommend adding a single lock that controls access to the file system
681 code.  You should acquire this lock before calling any functions in
682 the @file{filesys} directory, and release it afterward.  Don't forget
683 that @func{process_execute} also accesses files.  @strong{For now, we
684 recommend against modifying code in the @file{filesys} directory.}
685
686 We have provided you a user-level function for each system call in
687 @file{lib/user/syscall.c}.  These provide a way for user processes to
688 invoke each system call from a C program.  Each uses a little inline
689 assembly code to invoke the system call and (if appropriate) returns the
690 system call's return value.
691
692 When you're done with this part, and forevermore, Pintos should be
693 bulletproof.  Nothing that a user program can do should ever cause the
694 OS to crash, panic, fail an assertion, or otherwise malfunction.  It is
695 important to emphasize this point: our tests will try to break your
696 system calls in many, many ways.  You need to think of all the corner
697 cases and handle them.  The sole way a user program should be able to
698 cause the OS to halt is by invoking the @code{halt} system call.
699
700 If a system call is passed an invalid argument, acceptable options
701 include returning an error value (for those calls that return a
702 value), returning an undefined value, or terminating the process.
703
704 @xref{System Call Details}, for details on how system calls work.
705
706 @node Denying Writes to Executables
707 @subsection Denying Writes to Executables
708
709 Add code to deny writes to files in use as executables.  Many OSes do
710 this because of the unpredictable results if a process tried to run code
711 that was in the midst of being changed on disk.  This is especially
712 important once virtual memory is implemented in project 3, but it can't
713 hurt even now.
714
715 You can use @func{file_deny_write} to prevent writes to an open file.
716 Calling @func{file_allow_write} on the file will re-enable them (unless
717 the file is denied writes by another opener).  Closing a file will also
718 re-enable writes.
719
720 @node Project 2 FAQ
721 @section FAQ
722
723 @table @asis
724 @item How much code will I need to write?
725
726 Here's a summary of our reference solution, produced by the
727 @command{diffstat} program.  The final row gives total lines inserted
728 and deleted; a changed line counts as both an insertion and a deletion.
729
730 @verbatim
731  threads/thread.c     |   13 
732  threads/thread.h     |   26 +
733  userprog/exception.c |    8 
734  userprog/process.c   |  247 ++++++++++++++--
735  userprog/syscall.c   |  468 ++++++++++++++++++++++++++++++-
736  userprog/syscall.h   |    1 
737  6 files changed, 725 insertions(+), 38 deletions(-)
738 @end verbatim
739
740 @item The kernel always panics when I run @code{pintos -p @var{file} -- -q}.
741
742 Did you format the disk (with @samp{pintos -f})?
743
744 Is your file name too long?  The file system limits file names to 14
745 characters.  A command like @samp{pintos -p ../../examples/echo -- -q}
746 will exceed the limit.  Use @samp{pintos -p ../../examples/echo -a echo
747 -- -q} to put the file under the name @file{echo} instead.
748
749 Is the file system full?
750
751 Does the file system already contain 16 files?  The base Pintos file
752 system has a 16-file limit.
753
754 The file system may be so fragmented that there's not enough contiguous
755 space for your file.
756
757 @item When I run @code{pintos -p ../file --}, @file{file} isn't copied.
758
759 Files are written under the name you refer to them, by default, so in
760 this case the file copied in would be named @file{../file}.  You
761 probably want to run @code{pintos -p ../file -a file --} instead.
762
763 @item All my user programs die with page faults.
764
765 This will happen if you haven't implemented argument passing
766 (or haven't done so correctly).  The basic C library for user programs tries
767 to read @var{argc} and @var{argv} off the stack.  If the stack
768 isn't properly set up, this causes a page fault.
769
770 @item All my user programs die with @code{system call!}
771
772 You'll have to implement system calls before you see anything else.
773 Every reasonable program tries to make at least one system call
774 (@func{exit}) and most programs make more than that.  Notably,
775 @func{printf} invokes the @code{write} system call.  The default system
776 call handler just prints @samp{system call!} and terminates the program.
777 Until then, you can use @func{hex_dump} to convince yourself that
778 argument passing is implemented correctly (@pxref{Program Startup Details}).
779
780 @item How can I can disassemble user programs?
781
782 The @command{objdump} (80@var{x}86) or @command{i386-elf-objdump}
783 (SPARC) utility can disassemble entire user
784 programs or object files.  Invoke it as @code{objdump -d
785 @var{file}}.  You can use @code{gdb}'s
786 @command{disassemble} command to disassemble individual functions
787 (@pxref{gdb}).
788
789 @item Why do many C include files not work in Pintos programs?
790
791 The C library we provide is very limited.  It does not include many of
792 the features that are expected of a real operating system's C library.
793 The C library must be built specifically for the operating system (and
794 architecture), since it must make system calls for I/O and memory
795 allocation.  (Not all functions do, of course, but usually the library
796 is compiled as a unit.)
797
798 @item Can I use lib@var{foo} in my Pintos programs?
799
800 The chances are good that lib@var{foo} uses parts of the C library
801 that Pintos doesn't implement.  It will probably take at least some
802 porting effort to make it work under Pintos.  Notably, the Pintos
803 user program C library does not have a @func{malloc} implementation.
804
805 @item How do I compile new user programs?
806
807 Modify @file{src/examples/Makefile}, then run @command{make}.
808
809 @item Can I run user programs under a debugger?
810
811 Yes, with some limitations.  @xref{Debugging User Programs}.
812
813 @item What's the difference between @code{tid_t} and @code{pid_t}?
814
815 A @code{tid_t} identifies a kernel thread, which may have a user
816 process running in it (if created with @func{process_execute}) or not
817 (if created with @func{thread_create}).  It is a data type used only
818 in the kernel.
819
820 A @code{pid_t} identifies a user process.  It is used by user
821 processes and the kernel in the @code{exec} and @code{wait} system
822 calls.
823
824 You can choose whatever suitable types you like for @code{tid_t} and
825 @code{pid_t}.  By default, they're both @code{int}.  You can make them
826 a one-to-one mapping, so that the same values in both identify the
827 same process, or you can use a more complex mapping.  It's up to you.
828
829 @item Keyboard input doesn't work with @command{pintos} option @option{-v}.
830
831 Serial input isn't implemented.  Don't use @option{-v} if you
832 want to use the shell or otherwise need keyboard input.
833 @end table
834
835 @menu
836 * Argument Passing FAQ::        
837 * System Calls FAQ::            
838 @end menu
839
840 @node Argument Passing FAQ
841 @subsection Argument Passing FAQ
842
843 @table @asis
844 @item Isn't the top of stack off the top of user virtual memory?
845
846 The top of stack is at @code{PHYS_BASE}, typically @t{0xc0000000}, which
847 is also where kernel virtual memory starts.
848 But when the processor pushes data on the stack, it decrements the stack
849 pointer first.  Thus, the first (4-byte) value pushed on the stack
850 will be at address @t{0xbffffffc}.
851
852 @item Is @code{PHYS_BASE} fixed?
853
854 No.  You should be able to support @code{PHYS_BASE} values that are
855 any multiple of @t{0x10000000} from @t{0x80000000} to @t{0xf0000000},
856 simply via recompilation.
857 @end table
858
859 @node System Calls FAQ
860 @subsection System Calls FAQ
861
862 @table @asis
863 @item Can I just cast a @code{struct file *} to get a file descriptor?
864 @itemx Can I just cast a @code{struct thread *} to a @code{pid_t}?
865
866 You will have to make these design decisions yourself.
867 Most operating systems do distinguish between file
868 descriptors (or pids) and the addresses of their kernel data
869 structures.  You might want to give some thought as to why they do so
870 before committing yourself.
871
872 @item Can I set a maximum number of open files per process?
873
874 It is better not to set an arbitrary limit.  You may impose a limit of
875 128 open files per process, if necessary.
876
877 @item What happens when an open file is removed?
878 @anchor{Removing an Open File}
879
880 You should implement the standard Unix semantics for files.  That is, when
881 a file is removed any process which has a file descriptor for that file
882 may continue to use that descriptor.  This means that
883 they can read and write from the file.  The file will not have a name,
884 and no other processes will be able to open it, but it will continue
885 to exist until all file descriptors referring to the file are closed
886 or the machine shuts down.
887
888 @item How can I run user programs that need more than 4 kB stack space?
889
890 You may modify the stack setup code to allocate more than one page of
891 stack space for each process.  In the next project, you will implement a
892 better solution.
893 @end table
894
895 @node 80x86 Calling Convention
896 @section 80@var{x}86 Calling Convention
897
898 This section summarizes important points of the convention used for
899 normal function calls on 32-bit 80@var{x}86 implementations of Unix.
900 Some details are omitted for brevity.  If you do want all the details,
901 you can refer to @bibref{SysV-i386}.
902
903 The basic calling convention works like this:
904
905 @enumerate 1
906 @item
907 The caller pushes each of the function's arguments on the stack one by
908 one, normally using the @code{PUSH} assembly language instruction.
909 Arguments are pushed in right-to-left order.
910
911 @item
912 The caller pushes the address of its next instruction (the @dfn{return
913 address}) on the stack and jumps to the first instruction of the callee.
914 A single 80@var{x}86 instruction, @code{CALL}, does both.
915
916 @item
917 The callee executes.  When it takes control, the stack pointer points to
918 the return address, the first argument is just above it, the second
919 argument is just above the first argument, and so on.
920
921 @item
922 If the callee has a return value, it stores it into register @code{EAX}.
923
924 @item
925 The callee returns by popping the return address from the stack and
926 jumping to the location it specifies, using the 80@var{x}86 @code{RET}
927 instruction.
928
929 @item
930 The caller pops the arguments off the stack.
931 @end enumerate
932
933 Consider a function @func{f} that takes three @code{int} arguments.
934 This diagram shows a sample stack frame as seen by the callee at the
935 beginning of step 3 above, supposing that @func{f} is invoked as
936 @code{f(1, 2, 3)}.  The stack addresses are arbitrary:
937
938 @html
939 <CENTER>
940 @end html
941 @example
942                              +----------------+
943                   0xbffffe7c |        3       |
944                              +----------------+
945                   0xbffffe78 |        2       |
946                              +----------------+
947                   0xbffffe74 |        1       |
948                              +----------------+
949 stack pointer --> 0xbffffe70 | return address |
950                              +----------------+
951 @end example
952 @html
953 </CENTER>
954 @end html
955
956 @menu
957 * Program Startup Details::     
958 * System Call Details::         
959 @end menu
960
961 @node Program Startup Details
962 @subsection Program Startup Details
963
964 The Pintos C library for user programs designates @func{_start}, in
965 @file{lib/user/entry.c}, as the entry point for user programs.  This
966 function is a wrapper around @func{main} that calls @func{exit} if
967 @func{main} returns:
968
969 @example
970 void
971 _start (int argc, char *argv[]) 
972 @{
973   exit (main (argc, argv));
974 @}
975 @end example
976
977 The kernel is responsible for setting up the arguments for the initial
978 function on the stack, in accordance with the calling convention
979 explained in the preceding section, before it allows the user program to
980 begin executing.
981
982 Consider the following example command: @samp{/bin/ls -l foo bar}.
983 First, the kernel must break the command into words, as @samp{/bin/ls},
984 @samp{-l}, @samp{foo}, and @samp{bar}, and place them at the top of the
985 stack.  Order doesn't matter, because they will be referenced through
986 pointers.
987
988 Then, push the address of each string plus a null pointer sentinel, on
989 the stack, in right-to-left order.  These are the elements of
990 @code{argv}.  The order ensure that @code{argv[0]} is at the lowest
991 virtual address.  Word-aligned accesses are faster than unaligned
992 accesses, so for best performance round the stack pointer down to a
993 multiple of 4 before the first push.
994
995 Then, push @code{argv} (the address of @code{argv[0]}) and @code{argc},
996 in that order.  Finally, push a fake ``return address'': although the
997 entry function will never return, its stack frame must have the same
998 structure as any other.
999
1000 The table below show the state of the stack and the relevant registers
1001 right before the beginning of the user program, assuming
1002 @code{PHYS_BASE} is @t{0xc0000000}:
1003
1004 @html
1005 <CENTER>
1006 @end html
1007 @multitable {@t{0xbfffffff}} {return address} {@t{/bin/ls\0}} {@code{void (*) ()}}
1008 @item Address @tab Name @tab Data @tab Type
1009 @item @t{0xbffffffc} @tab @code{argv[3][@dots{}]} @tab @samp{bar\0} @tab @code{char[4]}
1010 @item @t{0xbffffff8} @tab @code{argv[2][@dots{}]} @tab @samp{foo\0} @tab @code{char[4]}
1011 @item @t{0xbffffff5} @tab @code{argv[1][@dots{}]} @tab @samp{-l\0} @tab @code{char[3]}
1012 @item @t{0xbfffffed} @tab @code{argv[0][@dots{}]} @tab @samp{/bin/ls\0} @tab @code{char[8]}
1013 @item @t{0xbfffffec} @tab word-align @tab 0 @tab @code{uint8_t}
1014 @item @t{0xbfffffe8} @tab @code{argv[4]} @tab @t{0} @tab @code{char *}
1015 @item @t{0xbfffffe4} @tab @code{argv[3]} @tab @t{0xbffffffc} @tab @code{char *}
1016 @item @t{0xbfffffe0} @tab @code{argv[2]} @tab @t{0xbffffff8} @tab @code{char *}
1017 @item @t{0xbfffffdc} @tab @code{argv[1]} @tab @t{0xbffffff5} @tab @code{char *}
1018 @item @t{0xbfffffd8} @tab @code{argv[0]} @tab @t{0xbfffffed} @tab @code{char *}
1019 @item @t{0xbfffffd4} @tab @code{argv} @tab @t{0xbfffffd8} @tab @code{char **}
1020 @item @t{0xbfffffd0} @tab @code{argc} @tab 4 @tab @code{int}
1021 @item @t{0xbfffffcc} @tab return address @tab 0 @tab @code{void (*) ()}
1022 @end multitable
1023 @html
1024 </CENTER>
1025 @end html
1026
1027 In this example, the stack pointer would be initialized to
1028 @t{0xbfffffcc}.
1029
1030 As shown above, your code should start the stack at the very top of
1031 the user virtual address space, in the page just below virtual address
1032 @code{PHYS_BASE} (defined in @file{threads/mmu.h}).
1033
1034 You may find the non-standard @func{hex_dump} function, declared in
1035 @file{<stdio.h>}, useful for debugging your argument passing code.
1036 Here's what it would show in the above example:
1037
1038 @verbatim
1039 bfffffc0                                      00 00 00 00 |            ....|
1040 bfffffd0  04 00 00 00 d8 ff ff bf-ed ff ff bf f5 ff ff bf |................|
1041 bfffffe0  f8 ff ff bf fc ff ff bf-00 00 00 00 00 2f 62 69 |............./bi|
1042 bffffff0  6e 2f 6c 73 00 2d 6c 00-66 6f 6f 00 62 61 72 00 |n/ls.-l.foo.bar.|
1043 @end verbatim
1044
1045 @node System Call Details
1046 @subsection System Call Details
1047
1048 The first project already dealt with one way that the operating system
1049 can regain control from a user program: interrupts from timers and I/O
1050 devices.  These are ``external'' interrupts, because they are caused
1051 by entities outside the CPU (@pxref{External Interrupt Handling}).
1052
1053 The operating system also deals with software exceptions, which are
1054 events that occur in program code (@pxref{Internal Interrupt
1055 Handling}).  These can be errors such as a page fault or division by
1056 zero.  Exceptions are also the means by which a user program
1057 can request services (``system calls'') from the operating system.
1058
1059 In the 80@var{x}86 architecture, the @samp{int} instruction is the
1060 most commonly used means for invoking system calls.  This instruction
1061 is handled in the same way as other software exceptions.  In Pintos,
1062 user programs invoke @samp{int $0x30} to make a system call.  The
1063 system call number and any additional arguments are expected to be
1064 pushed on the stack in the normal fashion before invoking the
1065 interrupt.
1066
1067 Thus, when the system call handler @func{syscall_handler} gets control,
1068 the system call number is in the 32-bit word at the caller's stack
1069 pointer, the first argument is in the 32-bit word at the next higher
1070 address, and so on.  The caller's stack pointer is accessible to
1071 @func{syscall_handler} as the @samp{esp} member of the
1072 @struct{intr_frame} passed to it.  (@struct{intr_frame} is on the kernel
1073 stack.)
1074
1075 The 80@var{x}86 convention for function return values is to place them
1076 in the @code{EAX} register.  System calls that return a value can do
1077 so by modifying the @samp{eax} member of @struct{intr_frame}.
1078
1079 You should try to avoid writing large amounts of repetitive code for
1080 implementing system calls.  Each system call argument, whether an
1081 integer or a pointer, takes up 4 bytes on the stack.  You should be able
1082 to take advantage of this to avoid writing much near-identical code for
1083 retrieving each system call's arguments from the stack.