[
  {
    "path": ".cvsignore",
    "content": "*.asm\n*.d\n*.sym\n_*\nkernel\nuser1\nuserfs\nusertests\nxv6.img\nvectors.S\nbochsout.txt\nbootblock\nbootother\nbootother.out\nparport.out\nfmt\n"
  },
  {
    "path": ".dir-locals.el",
    "content": "((c-mode\n  (indent-tabs-mode . nil)\n  (c-file-style . \"bsd\")\n  (c-basic-offset . 2)))\n"
  },
  {
    "path": ".gdbinit.tmpl",
    "content": "set $lastcs = -1\n\ndefine hook-stop\n  # There doesn't seem to be a good way to detect if we're in 16- or\n  # 32-bit mode, but in 32-bit mode we always run with CS == 8 in the\n  # kernel and CS == 35 in user space\n  if $cs == 8 || $cs == 35\n    if $lastcs != 8 && $lastcs != 35\n      set architecture i386\n    end\n    x/i $pc\n  else\n    if $lastcs == -1 || $lastcs == 8 || $lastcs == 35\n      set architecture i8086\n    end\n    # Translate the segment:offset into a physical address\n    printf \"[%4x:%4x] \", $cs, $eip\n    x/i $cs*16+$eip\n  end\n  set $lastcs = $cs\nend\n\necho + target remote localhost:1234\\n\ntarget remote localhost:1234\n\necho + symbol-file kernel\\n\nsymbol-file kernel\n"
  },
  {
    "path": ".gitignore",
    "content": "*~\n_*\n*.o\n*.d\n*.asm\n*.sym\n*.img\nvectors.S\nbootblock\nentryother\ninitcode\ninitcode.out\nkernel\nkernelmemfs\nmkfs\n.gdbinit\n"
  },
  {
    "path": "BUGS",
    "content": "formatting:\n\tneed to fix PAGEBREAK mechanism\n\nsh:\n\tcan't always runcmd in child -- breaks cd.\n\tmaybe should hard-code PATH=/ ?\n\n"
  },
  {
    "path": "LICENSE",
    "content": "The xv6 software is:\n\nCopyright (c) 2006-2018 Frans Kaashoek, Robert Morris, Russ Cox,\n                        Massachusetts Institute of Technology\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n"
  },
  {
    "path": "Makefile",
    "content": "OBJS = \\\n\tbio.o\\\n\tconsole.o\\\n\texec.o\\\n\tfile.o\\\n\tfs.o\\\n\tide.o\\\n\tioapic.o\\\n\tkalloc.o\\\n\tkbd.o\\\n\tlapic.o\\\n\tlog.o\\\n\tmain.o\\\n\tmp.o\\\n\tpicirq.o\\\n\tpipe.o\\\n\tproc.o\\\n\tsleeplock.o\\\n\tspinlock.o\\\n\tstring.o\\\n\tswtch.o\\\n\tsyscall.o\\\n\tsysfile.o\\\n\tsysproc.o\\\n\ttrapasm.o\\\n\ttrap.o\\\n\tuart.o\\\n\tvectors.o\\\n\tvm.o\\\n\n# Cross-compiling (e.g., on Mac OS X)\n# TOOLPREFIX = i386-jos-elf\n\n# Using native tools (e.g., on X86 Linux)\n#TOOLPREFIX = \n\n# Try to infer the correct TOOLPREFIX if not set\nifndef TOOLPREFIX\nTOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/dev/null 2>&1; \\\n\tthen echo 'i386-jos-elf-'; \\\n\telif objdump -i 2>&1 | grep 'elf32-i386' >/dev/null 2>&1; \\\n\tthen echo ''; \\\n\telse echo \"***\" 1>&2; \\\n\techo \"*** Error: Couldn't find an i386-*-elf version of GCC/binutils.\" 1>&2; \\\n\techo \"*** Is the directory with i386-jos-elf-gcc in your PATH?\" 1>&2; \\\n\techo \"*** If your i386-*-elf toolchain is installed with a command\" 1>&2; \\\n\techo \"*** prefix other than 'i386-jos-elf-', set your TOOLPREFIX\" 1>&2; \\\n\techo \"*** environment variable to that prefix and run 'make' again.\" 1>&2; \\\n\techo \"*** To turn off this error, run 'gmake TOOLPREFIX= ...'.\" 1>&2; \\\n\techo \"***\" 1>&2; exit 1; fi)\nendif\n\n# If the makefile can't find QEMU, specify its path here\n# QEMU = qemu-system-i386\n\n# Try to infer the correct QEMU\nifndef QEMU\nQEMU = $(shell if which qemu > /dev/null; \\\n\tthen echo qemu; exit; \\\n\telif which qemu-system-i386 > /dev/null; \\\n\tthen echo qemu-system-i386; exit; \\\n\telif which qemu-system-x86_64 > /dev/null; \\\n\tthen echo qemu-system-x86_64; exit; \\\n\telse \\\n\tqemu=/Applications/Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu; \\\n\tif test -x $$qemu; then echo $$qemu; exit; fi; fi; \\\n\techo \"***\" 1>&2; \\\n\techo \"*** Error: Couldn't find a working QEMU executable.\" 1>&2; \\\n\techo \"*** Is the directory containing the qemu binary in your PATH\" 1>&2; \\\n\techo \"*** or have you tried setting the QEMU variable in Makefile?\" 1>&2; \\\n\techo \"***\" 1>&2; exit 1)\nendif\n\nCC = $(TOOLPREFIX)gcc\nAS = $(TOOLPREFIX)gas\nLD = $(TOOLPREFIX)ld\nOBJCOPY = $(TOOLPREFIX)objcopy\nOBJDUMP = $(TOOLPREFIX)objdump\nCFLAGS = -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer\nCFLAGS += $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector)\nASFLAGS = -m32 -gdwarf-2 -Wa,-divide\n# FreeBSD ld wants ``elf_i386_fbsd''\nLDFLAGS += -m $(shell $(LD) -V | grep elf_i386 2>/dev/null | head -n 1)\n\n# Disable PIE when possible (for Ubuntu 16.10 toolchain)\nifneq ($(shell $(CC) -dumpspecs 2>/dev/null | grep -e '[^f]no-pie'),)\nCFLAGS += -fno-pie -no-pie\nendif\nifneq ($(shell $(CC) -dumpspecs 2>/dev/null | grep -e '[^f]nopie'),)\nCFLAGS += -fno-pie -nopie\nendif\n\nxv6.img: bootblock kernel\n\tdd if=/dev/zero of=xv6.img count=10000\n\tdd if=bootblock of=xv6.img conv=notrunc\n\tdd if=kernel of=xv6.img seek=1 conv=notrunc\n\nxv6memfs.img: bootblock kernelmemfs\n\tdd if=/dev/zero of=xv6memfs.img count=10000\n\tdd if=bootblock of=xv6memfs.img conv=notrunc\n\tdd if=kernelmemfs of=xv6memfs.img seek=1 conv=notrunc\n\nbootblock: bootasm.S bootmain.c\n\t$(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c\n\t$(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S\n\t$(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o\n\t$(OBJDUMP) -S bootblock.o > bootblock.asm\n\t$(OBJCOPY) -S -O binary -j .text bootblock.o bootblock\n\t./sign.pl bootblock\n\nentryother: entryother.S\n\t$(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c entryother.S\n\t$(LD) $(LDFLAGS) -N -e start -Ttext 0x7000 -o bootblockother.o entryother.o\n\t$(OBJCOPY) -S -O binary -j .text bootblockother.o entryother\n\t$(OBJDUMP) -S bootblockother.o > entryother.asm\n\ninitcode: initcode.S\n\t$(CC) $(CFLAGS) -nostdinc -I. -c initcode.S\n\t$(LD) $(LDFLAGS) -N -e start -Ttext 0 -o initcode.out initcode.o\n\t$(OBJCOPY) -S -O binary initcode.out initcode\n\t$(OBJDUMP) -S initcode.o > initcode.asm\n\nkernel: $(OBJS) entry.o entryother initcode kernel.ld\n\t$(LD) $(LDFLAGS) -T kernel.ld -o kernel entry.o $(OBJS) -b binary initcode entryother\n\t$(OBJDUMP) -S kernel > kernel.asm\n\t$(OBJDUMP) -t kernel | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernel.sym\n\n# kernelmemfs is a copy of kernel that maintains the\n# disk image in memory instead of writing to a disk.\n# This is not so useful for testing persistent storage or\n# exploring disk buffering implementations, but it is\n# great for testing the kernel on real hardware without\n# needing a scratch disk.\nMEMFSOBJS = $(filter-out ide.o,$(OBJS)) memide.o\nkernelmemfs: $(MEMFSOBJS) entry.o entryother initcode kernel.ld fs.img\n\t$(LD) $(LDFLAGS) -T kernel.ld -o kernelmemfs entry.o  $(MEMFSOBJS) -b binary initcode entryother fs.img\n\t$(OBJDUMP) -S kernelmemfs > kernelmemfs.asm\n\t$(OBJDUMP) -t kernelmemfs | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernelmemfs.sym\n\ntags: $(OBJS) entryother.S _init\n\tetags *.S *.c\n\nvectors.S: vectors.pl\n\t./vectors.pl > vectors.S\n\nULIB = ulib.o usys.o printf.o umalloc.o\n\n_%: %.o $(ULIB)\n\t$(LD) $(LDFLAGS) -N -e main -Ttext 0 -o $@ $^\n\t$(OBJDUMP) -S $@ > $*.asm\n\t$(OBJDUMP) -t $@ | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > $*.sym\n\n_forktest: forktest.o $(ULIB)\n\t# forktest has less library code linked in - needs to be small\n\t# in order to be able to max out the proc table.\n\t$(LD) $(LDFLAGS) -N -e main -Ttext 0 -o _forktest forktest.o ulib.o usys.o\n\t$(OBJDUMP) -S _forktest > forktest.asm\n\nmkfs: mkfs.c fs.h\n\tgcc -Werror -Wall -o mkfs mkfs.c\n\n# Prevent deletion of intermediate files, e.g. cat.o, after first build, so\n# that disk image changes after first build are persistent until clean.  More\n# details:\n# http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html\n.PRECIOUS: %.o\n\nUPROGS=\\\n\t_cat\\\n\t_echo\\\n\t_forktest\\\n\t_grep\\\n\t_init\\\n\t_kill\\\n\t_ln\\\n\t_ls\\\n\t_mkdir\\\n\t_rm\\\n\t_sh\\\n\t_stressfs\\\n\t_usertests\\\n\t_wc\\\n\t_zombie\\\n\nfs.img: mkfs README $(UPROGS)\n\t./mkfs fs.img README $(UPROGS)\n\n-include *.d\n\nclean: \n\trm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \\\n\t*.o *.d *.asm *.sym vectors.S bootblock entryother \\\n\tinitcode initcode.out kernel xv6.img fs.img kernelmemfs \\\n\txv6memfs.img mkfs .gdbinit \\\n\t$(UPROGS)\n\n# make a printout\nFILES = $(shell grep -v '^\\#' runoff.list)\nPRINT = runoff.list runoff.spec README toc.hdr toc.ftr $(FILES)\n\nxv6.pdf: $(PRINT)\n\t./runoff\n\tls -l xv6.pdf\n\nprint: xv6.pdf\n\n# run in emulators\n\nbochs : fs.img xv6.img\n\tif [ ! -e .bochsrc ]; then ln -s dot-bochsrc .bochsrc; fi\n\tbochs -q\n\n# try to generate a unique GDB port\nGDBPORT = $(shell expr `id -u` % 5000 + 25000)\n# QEMU's gdb stub command line changed in 0.11\nQEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \\\n\tthen echo \"-gdb tcp::$(GDBPORT)\"; \\\n\telse echo \"-s -p $(GDBPORT)\"; fi)\nifndef CPUS\nCPUS := 2\nendif\nQEMUOPTS = -drive file=fs.img,index=1,media=disk,format=raw -drive file=xv6.img,index=0,media=disk,format=raw -smp $(CPUS) -m 512 $(QEMUEXTRA)\n\nqemu: fs.img xv6.img\n\t$(QEMU) -serial mon:stdio $(QEMUOPTS)\n\nqemu-memfs: xv6memfs.img\n\t$(QEMU) -drive file=xv6memfs.img,index=0,media=disk,format=raw -smp $(CPUS) -m 256\n\nqemu-nox: fs.img xv6.img\n\t$(QEMU) -nographic $(QEMUOPTS)\n\n.gdbinit: .gdbinit.tmpl\n\tsed \"s/localhost:1234/localhost:$(GDBPORT)/\" < $^ > $@\n\nqemu-gdb: fs.img xv6.img .gdbinit\n\t@echo \"*** Now run 'gdb'.\" 1>&2\n\t$(QEMU) -serial mon:stdio $(QEMUOPTS) -S $(QEMUGDB)\n\nqemu-nox-gdb: fs.img xv6.img .gdbinit\n\t@echo \"*** Now run 'gdb'.\" 1>&2\n\t$(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB)\n\n# CUT HERE\n# prepare dist for students\n# after running make dist, probably want to\n# rename it to rev0 or rev1 or so on and then\n# check in that version.\n\nEXTRA=\\\n\tmkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\\\n\tln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\\\n\tprintf.c umalloc.c\\\n\tREADME dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\\\n\t.gdbinit.tmpl gdbutil\\\n\ndist:\n\trm -rf dist\n\tmkdir dist\n\tfor i in $(FILES); \\\n\tdo \\\n\t\tgrep -v PAGEBREAK $$i >dist/$$i; \\\n\tdone\n\tsed '/CUT HERE/,$$d' Makefile >dist/Makefile\n\techo >dist/runoff.spec\n\tcp $(EXTRA) dist\n\ndist-test:\n\trm -rf dist\n\tmake dist\n\trm -rf dist-test\n\tmkdir dist-test\n\tcp dist/* dist-test\n\tcd dist-test; $(MAKE) print\n\tcd dist-test; $(MAKE) bochs || true\n\tcd dist-test; $(MAKE) qemu\n\n# update this rule (change rev#) when it is time to\n# make a new revision.\ntar:\n\trm -rf /tmp/xv6\n\tmkdir -p /tmp/xv6\n\tcp dist/* dist/.gdbinit.tmpl /tmp/xv6\n\t(cd /tmp; tar cf - xv6) | gzip >xv6-rev10.tar.gz  # the next one will be 10 (9/17)\n\n.PHONY: dist-test dist\n"
  },
  {
    "path": "Notes",
    "content": "bochs 2.2.6:\n./configure --enable-smp --enable-disasm --enable-debugger --enable-all-optimizations --enable-4meg-pages --enable-global-pages --enable-pae --disable-reset-on-triple-fault\nbochs CVS after 2.2.6:\n./configure --enable-smp --enable-disasm --enable-debugger --enable-all-optimizations --enable-4meg-pages --enable-global-pages --enable-pae \n\nbootmain.c doesn't work right if the ELF sections aren't\nsector-aligned. so you can't use ld -N. and the sections may also need\nto be non-zero length, only really matters for tiny \"kernels\".\n\nkernel loaded at 1 megabyte. stack same place that bootasm.S left it.\n\nkinit() should find real mem size\n  and rescue useable memory below 1 meg\n\nno paging, no use of page table hardware, just segments\n\nno user area: no magic kernel stack mapping\n  so no copying of kernel stack during fork\n  though there is a kernel stack page for each process\n\nno kernel malloc(), just kalloc() for user core\n\nuser pointers aren't valid in the kernel\n\nare interrupts turned on in the kernel? yes.\n\npass curproc explicitly, or implicit from cpu #?\n  e.g. argument to newproc()?\n  hmm, you need a global curproc[cpu] for trap() &c\n\nno stack expansion\n\ntest running out of memory, process slots\n\nwe can't really use a separate stack segment, since stack addresses\nneed to work correctly as ordinary pointers. the same may be true of\ndata vs text. how can we have a gap between data and stack, so that\nboth can grow, without committing 4GB of physical memory? does this\nmean we need paging?\n\nperhaps have fixed-size stack, put it in the data segment?\n\noops, if kernel stack is in contiguous user phys mem, then moving\nusers' memory (e.g. to expand it) will wreck any pointers into the\nkernel stack.\n\ndo we need to set fs and gs? so user processes can't abuse them?\n\nsetupsegs() may modify current segment table, is that legal?\n\ntrap() ought to lgdt on return, since currently only done in swtch()\n\nprotect hardware interrupt vectors from user INT instructions?\n\ntest out-of-fd cases for creating pipe.\ntest pipe reader closes then write\ntest two readers, two writers.\ntest children being inherited by grandparent &c\n\nsome sleep()s should be interruptible by kill()\n\nlocks\n  init_lock\n    sequences CPU startup\n  proc_table_lock\n    also protects next_pid\n  per-fd lock *just* protects count read-modify-write\n    also maybe freeness?\n  memory allocator\n  printf\n\nin general, the table locks protect both free-ness and\n  public variables of table elements\n  in many cases you can use table elements w/o a lock\n  e.g. if you are the process, or you are using an fd\n\nlock order\n  per-pipe lock\n  proc_table_lock fd_table_lock kalloc_lock\n  console_lock\n\ndo you have to be holding the mutex in order to call wakeup()? yes\n\ndevice interrupts don't clear FL_IF\n  so a recursive timer interrupt is possible\n\nwhat does inode->busy mean?\n  might be held across disk reads\n  no-one is allowed to do anything to the inode\n  protected by inode_table_lock\ninode->count counts in-memory pointers to the struct\n  prevents inode[] element from being re-used\n  protected by inode_table_lock\n\nblocks and inodes have ad-hoc sleep-locks\n  provide a single mechanism?\n\nkalloc() can return 0; do callers handle this right?\n\ntest: one process unlinks a file while another links to it\ntest: one process opens a file while another deletes it\ntest: deadlock d/.. vs ../d, two processes.\ntest: dup() shared fd->off\ntest: does echo foo > x truncate x?\n\nsh: ioredirection incorrect now we have pipes\nsh: chain of pipes won't work, also ugly that parent closes fdarray entries too\nsh: dynamic memory allocation?\nsh: should sh support ; () &\nsh: stop stdin on ctrl-d (for cat > y)\n\nreally should have bdwrite() for file content\n  and make some inode updates async\n  so soft updates make sense\n\ndisk scheduling\necho foo > bar should truncate bar\n  so O_CREATE should not truncate\n  but O_TRUNC should\n\nmake it work on a real machine\nrelease before acquire at end of sleep?\ncheck 2nd disk (i.e. if not in .bochsrc)\n"
  },
  {
    "path": "README",
    "content": "NOTE: we have stopped maintaining the x86 version of xv6, and switched\nour efforts to the RISC-V version\n(https://github.com/mit-pdos/xv6-riscv.git)\n\nxv6 is a re-implementation of Dennis Ritchie's and Ken Thompson's Unix\nVersion 6 (v6).  xv6 loosely follows the structure and style of v6,\nbut is implemented for a modern x86-based multiprocessor using ANSI C.\n\nACKNOWLEDGMENTS\n\nxv6 is inspired by John Lions's Commentary on UNIX 6th Edition (Peer\nto Peer Communications; ISBN: 1-57398-013-7; 1st edition (June 14,\n2000)). See also https://pdos.csail.mit.edu/6.828/, which\nprovides pointers to on-line resources for v6.\n\nxv6 borrows code from the following sources:\n    JOS (asm.h, elf.h, mmu.h, bootasm.S, ide.c, console.c, and others)\n    Plan 9 (entryother.S, mp.h, mp.c, lapic.c)\n    FreeBSD (ioapic.c)\n    NetBSD (console.c)\n\nThe following people have made contributions: Russ Cox (context switching,\nlocking), Cliff Frey (MP), Xiao Yu (MP), Nickolai Zeldovich, and Austin\nClements.\n\nWe are also grateful for the bug reports and patches contributed by Silas\nBoyd-Wickizer, Anton Burtsev, Cody Cutler, Mike CAT, Tej Chajed, eyalz800,\nNelson Elhage, Saar Ettinger, Alice Ferrazzi, Nathaniel Filardo, Peter\nFroehlich, Yakir Goaron,Shivam Handa, Bryan Henry, Jim Huang, Alexander\nKapshuk, Anders Kaseorg, kehao95, Wolfgang Keller, Eddie Kohler, Austin\nLiew, Imbar Marinescu, Yandong Mao, Matan Shabtay, Hitoshi Mitake, Carmi\nMerimovich, Mark Morrissey, mtasm, Joel Nider, Greg Price, Ayan Shafqat,\nEldar Sehayek, Yongming Shen, Cam Tenny, tyfkda, Rafael Ubal, Warren\nToomey, Stephen Tu, Pablo Ventura, Xi Wang, Keiichi Watanabe, Nicolas\nWolovick, wxdao, Grant Wu, Jindong Zhang, Icenowy Zheng, and Zou Chang Wei.\n\nThe code in the files that constitute xv6 is\nCopyright 2006-2018 Frans Kaashoek, Robert Morris, and Russ Cox.\n\nERROR REPORTS\n\nWe don't process error reports (see note on top of this file).\n\nBUILDING AND RUNNING XV6\n\nTo build xv6 on an x86 ELF machine (like Linux or FreeBSD), run\n\"make\". On non-x86 or non-ELF machines (like OS X, even on x86), you\nwill need to install a cross-compiler gcc suite capable of producing\nx86 ELF binaries (see https://pdos.csail.mit.edu/6.828/).\nThen run \"make TOOLPREFIX=i386-jos-elf-\". Now install the QEMU PC\nsimulator and run \"make qemu\"."
  },
  {
    "path": "TRICKS",
    "content": "This file lists subtle things that might not be commented \nas well as they should be in the source code and that\nmight be worth pointing out in a longer explanation or in class.\n\n---\n\n[2009/07/12: No longer relevant; forkret1 changed\nand this is now cleaner.]\n\nforkret1 in trapasm.S is called with a tf argument.\nIn order to use it, forkret1 copies the tf pointer into\n%esp and then jumps to trapret, which pops the \nregister state out of the trap frame.  If an interrupt\ncame in between the mov tf, %esp and the iret that\ngoes back out to user space, the interrupt stack frame\nwould end up scribbling over the tf and whatever memory\nlay under it.\n\nWhy is this safe?  Because forkret1 is only called\nthe first time a process returns to user space, and\nat that point, cp->tf is set to point to a trap frame\nconstructed at the top of cp's kernel stack.  So tf \n*is* a valid %esp that can hold interrupt state.\n\nIf other tf's were used in forkret1, we could add\na cli before the mov tf, %esp.\n\n---\n\nIn pushcli, must cli() no matter what.  It is not safe to do\n\n  if(cpus[cpu()].ncli == 0)\n    cli();\n  cpus[cpu()].ncli++;\n\nbecause if interrupts are off then we might call cpu(), get\nrescheduled to a different cpu, look at cpus[oldcpu].ncli,\nand wrongly decide not to disable interrupts on the new cpu.\n\nInstead do \n\n  cli();\n  cpus[cpu()].ncli++;\n\nalways.\n\n---\n\nThere is a (harmless) race in pushcli, which does\n\n\teflags = readeflags();\n\tcli();\n\tif(c->ncli++ == 0)\n\t\tc->intena = eflags & FL_IF;\n\nConsider a bottom-level pushcli.  \nIf interrupts are disabled already, then the right thing\nhappens: read_eflags finds that FL_IF is not set,\nand intena = 0.  If interrupts are enabled, then\nit is less clear that the right thing happens:\nthe readeflags can execute, then the process\ncan get preempted and rescheduled on another cpu,\nand then once it starts running, perhaps with \ninterrupts disabled (can happen since the scheduler\nonly enables interrupts once per scheduling loop,\nnot every time it schedules a process), it will \nincorrectly record that interrupts *were* enabled.\nThis doesn't matter, because if it was safe to be\nrunning with interrupts enabled before the context\nswitch, it is still safe (and arguably more correct)\nto run with them enabled after the context switch too.\n\nIn fact it would be safe if scheduler always set\n\tc->intena = 1;\nbefore calling swtch, and perhaps it should.\n\n---\n\nThe x86's processor-ordering memory model \nmatches spin locks well, so no explicit memory\nsynchronization instructions are required in\nacquire and release.  \n\nConsider two sequences of code on different CPUs:\n\nCPU0\nA;\nrelease(lk);\n\nand\n\nCPU1\nacquire(lk);\nB;\n\nWe want to make sure that:\n  - all reads in B see the effects of writes in A.\n  - all reads in A do *not* see the effects of writes in B.\n \nThe x86 guarantees that writes in A will go out\nto memory before the write of lk->locked = 0 in \nrelease(lk).  It further guarantees that CPU1 \nwill observe CPU0's write of lk->locked = 0 only\nafter observing the earlier writes by CPU0.\nSo any reads in B are guaranteed to observe the\neffects of writes in A.\n\nAccording to the Intel manual behavior spec, the\nsecond condition requires a serialization instruction\nin release, to avoid reads in A happening after giving\nup lk.  No Intel SMP processor in existence actually\nmoves reads down after writes, but the language in\nthe spec allows it.  There is no telling whether future\nprocessors will need it.\n\n---\n\nThe code in fork needs to read np->pid before\nsetting np->state to RUNNABLE.  The following\nis not a correct way to do this:\n\n\tint\n\tfork(void)\n\t{\n\t  ...\n\t  np->state = RUNNABLE;\n\t  return np->pid; // oops\n\t}\n\nAfter setting np->state to RUNNABLE, some other CPU\nmight run the process, it might exit, and then it might\nget reused for a different process (with a new pid), all\nbefore the return statement.  So it's not safe to just\n\"return np->pid\". Even saving a copy of np->pid before\nsetting np->state isn't safe, since the compiler is\nallowed to re-order statements.\n\nThe real code saves a copy of np->pid, then acquires a lock\naround the write to np->state. The acquire() prevents the\ncompiler from re-ordering.\n"
  },
  {
    "path": "asm.h",
    "content": "//\n// assembler macros to create x86 segments\n//\n\n#define SEG_NULLASM                                             \\\n        .word 0, 0;                                             \\\n        .byte 0, 0, 0, 0\n\n// The 0xC0 means the limit is in 4096-byte units\n// and (for executable segments) 32-bit mode.\n#define SEG_ASM(type,base,lim)                                  \\\n        .word (((lim) >> 12) & 0xffff), ((base) & 0xffff);      \\\n        .byte (((base) >> 16) & 0xff), (0x90 | (type)),         \\\n                (0xC0 | (((lim) >> 28) & 0xf)), (((base) >> 24) & 0xff)\n\n#define STA_X     0x8       // Executable segment\n#define STA_W     0x2       // Writeable (non-executable segments)\n#define STA_R     0x2       // Readable (executable segments)\n"
  },
  {
    "path": "bio.c",
    "content": "// Buffer cache.\n//\n// The buffer cache is a linked list of buf structures holding\n// cached copies of disk block contents.  Caching disk blocks\n// in memory reduces the number of disk reads and also provides\n// a synchronization point for disk blocks used by multiple processes.\n//\n// Interface:\n// * To get a buffer for a particular disk block, call bread.\n// * After changing buffer data, call bwrite to write it to disk.\n// * When done with the buffer, call brelse.\n// * Do not use the buffer after calling brelse.\n// * Only one process at a time can use a buffer,\n//     so do not keep them longer than necessary.\n//\n// The implementation uses two state flags internally:\n// * B_VALID: the buffer data has been read from the disk.\n// * B_DIRTY: the buffer data has been modified\n//     and needs to be written to disk.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"buf.h\"\n\nstruct {\n  struct spinlock lock;\n  struct buf buf[NBUF];\n\n  // Linked list of all buffers, through prev/next.\n  // head.next is most recently used.\n  struct buf head;\n} bcache;\n\nvoid\nbinit(void)\n{\n  struct buf *b;\n\n  initlock(&bcache.lock, \"bcache\");\n\n//PAGEBREAK!\n  // Create linked list of buffers\n  bcache.head.prev = &bcache.head;\n  bcache.head.next = &bcache.head;\n  for(b = bcache.buf; b < bcache.buf+NBUF; b++){\n    b->next = bcache.head.next;\n    b->prev = &bcache.head;\n    initsleeplock(&b->lock, \"buffer\");\n    bcache.head.next->prev = b;\n    bcache.head.next = b;\n  }\n}\n\n// Look through buffer cache for block on device dev.\n// If not found, allocate a buffer.\n// In either case, return locked buffer.\nstatic struct buf*\nbget(uint dev, uint blockno)\n{\n  struct buf *b;\n\n  acquire(&bcache.lock);\n\n  // Is the block already cached?\n  for(b = bcache.head.next; b != &bcache.head; b = b->next){\n    if(b->dev == dev && b->blockno == blockno){\n      b->refcnt++;\n      release(&bcache.lock);\n      acquiresleep(&b->lock);\n      return b;\n    }\n  }\n\n  // Not cached; recycle an unused buffer.\n  // Even if refcnt==0, B_DIRTY indicates a buffer is in use\n  // because log.c has modified it but not yet committed it.\n  for(b = bcache.head.prev; b != &bcache.head; b = b->prev){\n    if(b->refcnt == 0 && (b->flags & B_DIRTY) == 0) {\n      b->dev = dev;\n      b->blockno = blockno;\n      b->flags = 0;\n      b->refcnt = 1;\n      release(&bcache.lock);\n      acquiresleep(&b->lock);\n      return b;\n    }\n  }\n  panic(\"bget: no buffers\");\n}\n\n// Return a locked buf with the contents of the indicated block.\nstruct buf*\nbread(uint dev, uint blockno)\n{\n  struct buf *b;\n\n  b = bget(dev, blockno);\n  if((b->flags & B_VALID) == 0) {\n    iderw(b);\n  }\n  return b;\n}\n\n// Write b's contents to disk.  Must be locked.\nvoid\nbwrite(struct buf *b)\n{\n  if(!holdingsleep(&b->lock))\n    panic(\"bwrite\");\n  b->flags |= B_DIRTY;\n  iderw(b);\n}\n\n// Release a locked buffer.\n// Move to the head of the MRU list.\nvoid\nbrelse(struct buf *b)\n{\n  if(!holdingsleep(&b->lock))\n    panic(\"brelse\");\n\n  releasesleep(&b->lock);\n\n  acquire(&bcache.lock);\n  b->refcnt--;\n  if (b->refcnt == 0) {\n    // no one is waiting for it.\n    b->next->prev = b->prev;\n    b->prev->next = b->next;\n    b->next = bcache.head.next;\n    b->prev = &bcache.head;\n    bcache.head.next->prev = b;\n    bcache.head.next = b;\n  }\n  \n  release(&bcache.lock);\n}\n//PAGEBREAK!\n// Blank page.\n\n"
  },
  {
    "path": "bootasm.S",
    "content": "#include \"asm.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n\n# Start the first CPU: switch to 32-bit protected mode, jump into C.\n# The BIOS loads this code from the first sector of the hard disk into\n# memory at physical address 0x7c00 and starts executing in real mode\n# with %cs=0 %ip=7c00.\n\n.code16                       # Assemble for 16-bit mode\n.globl start\nstart:\n  cli                         # BIOS enabled interrupts; disable\n\n  # Zero data segment registers DS, ES, and SS.\n  xorw    %ax,%ax             # Set %ax to zero\n  movw    %ax,%ds             # -> Data Segment\n  movw    %ax,%es             # -> Extra Segment\n  movw    %ax,%ss             # -> Stack Segment\n\n  # Physical address line A20 is tied to zero so that the first PCs \n  # with 2 MB would run software that assumed 1 MB.  Undo that.\nseta20.1:\n  inb     $0x64,%al               # Wait for not busy\n  testb   $0x2,%al\n  jnz     seta20.1\n\n  movb    $0xd1,%al               # 0xd1 -> port 0x64\n  outb    %al,$0x64\n\nseta20.2:\n  inb     $0x64,%al               # Wait for not busy\n  testb   $0x2,%al\n  jnz     seta20.2\n\n  movb    $0xdf,%al               # 0xdf -> port 0x60\n  outb    %al,$0x60\n\n  # Switch from real to protected mode.  Use a bootstrap GDT that makes\n  # virtual addresses map directly to physical addresses so that the\n  # effective memory map doesn't change during the transition.\n  lgdt    gdtdesc\n  movl    %cr0, %eax\n  orl     $CR0_PE, %eax\n  movl    %eax, %cr0\n\n//PAGEBREAK!\n  # Complete the transition to 32-bit protected mode by using a long jmp\n  # to reload %cs and %eip.  The segment descriptors are set up with no\n  # translation, so that the mapping is still the identity mapping.\n  ljmp    $(SEG_KCODE<<3), $start32\n\n.code32  # Tell assembler to generate 32-bit code now.\nstart32:\n  # Set up the protected-mode data segment registers\n  movw    $(SEG_KDATA<<3), %ax    # Our data segment selector\n  movw    %ax, %ds                # -> DS: Data Segment\n  movw    %ax, %es                # -> ES: Extra Segment\n  movw    %ax, %ss                # -> SS: Stack Segment\n  movw    $0, %ax                 # Zero segments not ready for use\n  movw    %ax, %fs                # -> FS\n  movw    %ax, %gs                # -> GS\n\n  # Set up the stack pointer and call into C.\n  movl    $start, %esp\n  call    bootmain\n\n  # If bootmain returns (it shouldn't), trigger a Bochs\n  # breakpoint if running under Bochs, then loop.\n  movw    $0x8a00, %ax            # 0x8a00 -> port 0x8a00\n  movw    %ax, %dx\n  outw    %ax, %dx\n  movw    $0x8ae0, %ax            # 0x8ae0 -> port 0x8a00\n  outw    %ax, %dx\nspin:\n  jmp     spin\n\n# Bootstrap GDT\n.p2align 2                                # force 4 byte alignment\ngdt:\n  SEG_NULLASM                             # null seg\n  SEG_ASM(STA_X|STA_R, 0x0, 0xffffffff)   # code seg\n  SEG_ASM(STA_W, 0x0, 0xffffffff)         # data seg\n\ngdtdesc:\n  .word   (gdtdesc - gdt - 1)             # sizeof(gdt) - 1\n  .long   gdt                             # address gdt\n\n"
  },
  {
    "path": "bootmain.c",
    "content": "// Boot loader.\n//\n// Part of the boot block, along with bootasm.S, which calls bootmain().\n// bootasm.S has put the processor into protected 32-bit mode.\n// bootmain() loads an ELF kernel image from the disk starting at\n// sector 1 and then jumps to the kernel entry routine.\n\n#include \"types.h\"\n#include \"elf.h\"\n#include \"x86.h\"\n#include \"memlayout.h\"\n\n#define SECTSIZE  512\n\nvoid readseg(uchar*, uint, uint);\n\nvoid\nbootmain(void)\n{\n  struct elfhdr *elf;\n  struct proghdr *ph, *eph;\n  void (*entry)(void);\n  uchar* pa;\n\n  elf = (struct elfhdr*)0x10000;  // scratch space\n\n  // Read 1st page off disk\n  readseg((uchar*)elf, 4096, 0);\n\n  // Is this an ELF executable?\n  if(elf->magic != ELF_MAGIC)\n    return;  // let bootasm.S handle error\n\n  // Load each program segment (ignores ph flags).\n  ph = (struct proghdr*)((uchar*)elf + elf->phoff);\n  eph = ph + elf->phnum;\n  for(; ph < eph; ph++){\n    pa = (uchar*)ph->paddr;\n    readseg(pa, ph->filesz, ph->off);\n    if(ph->memsz > ph->filesz)\n      stosb(pa + ph->filesz, 0, ph->memsz - ph->filesz);\n  }\n\n  // Call the entry point from the ELF header.\n  // Does not return!\n  entry = (void(*)(void))(elf->entry);\n  entry();\n}\n\nvoid\nwaitdisk(void)\n{\n  // Wait for disk ready.\n  while((inb(0x1F7) & 0xC0) != 0x40)\n    ;\n}\n\n// Read a single sector at offset into dst.\nvoid\nreadsect(void *dst, uint offset)\n{\n  // Issue command.\n  waitdisk();\n  outb(0x1F2, 1);   // count = 1\n  outb(0x1F3, offset);\n  outb(0x1F4, offset >> 8);\n  outb(0x1F5, offset >> 16);\n  outb(0x1F6, (offset >> 24) | 0xE0);\n  outb(0x1F7, 0x20);  // cmd 0x20 - read sectors\n\n  // Read data.\n  waitdisk();\n  insl(0x1F0, dst, SECTSIZE/4);\n}\n\n// Read 'count' bytes at 'offset' from kernel into physical address 'pa'.\n// Might copy more than asked.\nvoid\nreadseg(uchar* pa, uint count, uint offset)\n{\n  uchar* epa;\n\n  epa = pa + count;\n\n  // Round down to sector boundary.\n  pa -= offset % SECTSIZE;\n\n  // Translate from bytes to sectors; kernel starts at sector 1.\n  offset = (offset / SECTSIZE) + 1;\n\n  // If this is too slow, we could read lots of sectors at a time.\n  // We'd write more to memory than asked, but it doesn't matter --\n  // we load in increasing order.\n  for(; pa < epa; pa += SECTSIZE, offset++)\n    readsect(pa, offset);\n}\n"
  },
  {
    "path": "buf.h",
    "content": "struct buf {\n  int flags;\n  uint dev;\n  uint blockno;\n  struct sleeplock lock;\n  uint refcnt;\n  struct buf *prev; // LRU cache list\n  struct buf *next;\n  struct buf *qnext; // disk queue\n  uchar data[BSIZE];\n};\n#define B_VALID 0x2  // buffer has been read from disk\n#define B_DIRTY 0x4  // buffer needs to be written to disk\n\n"
  },
  {
    "path": "cat.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nchar buf[512];\n\nvoid\ncat(int fd)\n{\n  int n;\n\n  while((n = read(fd, buf, sizeof(buf))) > 0) {\n    if (write(1, buf, n) != n) {\n      printf(1, \"cat: write error\\n\");\n      exit();\n    }\n  }\n  if(n < 0){\n    printf(1, \"cat: read error\\n\");\n    exit();\n  }\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int fd, i;\n\n  if(argc <= 1){\n    cat(0);\n    exit();\n  }\n\n  for(i = 1; i < argc; i++){\n    if((fd = open(argv[i], 0)) < 0){\n      printf(1, \"cat: cannot open %s\\n\", argv[i]);\n      exit();\n    }\n    cat(fd);\n    close(fd);\n  }\n  exit();\n}\n"
  },
  {
    "path": "console.c",
    "content": "// Console input and output.\n// Input is from the keyboard or serial port.\n// Output is written to the screen and serial port.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"traps.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"file.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n\nstatic void consputc(int);\n\nstatic int panicked = 0;\n\nstatic struct {\n  struct spinlock lock;\n  int locking;\n} cons;\n\nstatic void\nprintint(int xx, int base, int sign)\n{\n  static char digits[] = \"0123456789abcdef\";\n  char buf[16];\n  int i;\n  uint x;\n\n  if(sign && (sign = xx < 0))\n    x = -xx;\n  else\n    x = xx;\n\n  i = 0;\n  do{\n    buf[i++] = digits[x % base];\n  }while((x /= base) != 0);\n\n  if(sign)\n    buf[i++] = '-';\n\n  while(--i >= 0)\n    consputc(buf[i]);\n}\n//PAGEBREAK: 50\n\n// Print to the console. only understands %d, %x, %p, %s.\nvoid\ncprintf(char *fmt, ...)\n{\n  int i, c, locking;\n  uint *argp;\n  char *s;\n\n  locking = cons.locking;\n  if(locking)\n    acquire(&cons.lock);\n\n  if (fmt == 0)\n    panic(\"null fmt\");\n\n  argp = (uint*)(void*)(&fmt + 1);\n  for(i = 0; (c = fmt[i] & 0xff) != 0; i++){\n    if(c != '%'){\n      consputc(c);\n      continue;\n    }\n    c = fmt[++i] & 0xff;\n    if(c == 0)\n      break;\n    switch(c){\n    case 'd':\n      printint(*argp++, 10, 1);\n      break;\n    case 'x':\n    case 'p':\n      printint(*argp++, 16, 0);\n      break;\n    case 's':\n      if((s = (char*)*argp++) == 0)\n        s = \"(null)\";\n      for(; *s; s++)\n        consputc(*s);\n      break;\n    case '%':\n      consputc('%');\n      break;\n    default:\n      // Print unknown % sequence to draw attention.\n      consputc('%');\n      consputc(c);\n      break;\n    }\n  }\n\n  if(locking)\n    release(&cons.lock);\n}\n\nvoid\npanic(char *s)\n{\n  int i;\n  uint pcs[10];\n\n  cli();\n  cons.locking = 0;\n  // use lapiccpunum so that we can call panic from mycpu()\n  cprintf(\"lapicid %d: panic: \", lapicid());\n  cprintf(s);\n  cprintf(\"\\n\");\n  getcallerpcs(&s, pcs);\n  for(i=0; i<10; i++)\n    cprintf(\" %p\", pcs[i]);\n  panicked = 1; // freeze other CPU\n  for(;;)\n    ;\n}\n\n//PAGEBREAK: 50\n#define BACKSPACE 0x100\n#define CRTPORT 0x3d4\nstatic ushort *crt = (ushort*)P2V(0xb8000);  // CGA memory\n\nstatic void\ncgaputc(int c)\n{\n  int pos;\n\n  // Cursor position: col + 80*row.\n  outb(CRTPORT, 14);\n  pos = inb(CRTPORT+1) << 8;\n  outb(CRTPORT, 15);\n  pos |= inb(CRTPORT+1);\n\n  if(c == '\\n')\n    pos += 80 - pos%80;\n  else if(c == BACKSPACE){\n    if(pos > 0) --pos;\n  } else\n    crt[pos++] = (c&0xff) | 0x0700;  // black on white\n\n  if(pos < 0 || pos > 25*80)\n    panic(\"pos under/overflow\");\n\n  if((pos/80) >= 24){  // Scroll up.\n    memmove(crt, crt+80, sizeof(crt[0])*23*80);\n    pos -= 80;\n    memset(crt+pos, 0, sizeof(crt[0])*(24*80 - pos));\n  }\n\n  outb(CRTPORT, 14);\n  outb(CRTPORT+1, pos>>8);\n  outb(CRTPORT, 15);\n  outb(CRTPORT+1, pos);\n  crt[pos] = ' ' | 0x0700;\n}\n\nvoid\nconsputc(int c)\n{\n  if(panicked){\n    cli();\n    for(;;)\n      ;\n  }\n\n  if(c == BACKSPACE){\n    uartputc('\\b'); uartputc(' '); uartputc('\\b');\n  } else\n    uartputc(c);\n  cgaputc(c);\n}\n\n#define INPUT_BUF 128\nstruct {\n  char buf[INPUT_BUF];\n  uint r;  // Read index\n  uint w;  // Write index\n  uint e;  // Edit index\n} input;\n\n#define C(x)  ((x)-'@')  // Control-x\n\nvoid\nconsoleintr(int (*getc)(void))\n{\n  int c, doprocdump = 0;\n\n  acquire(&cons.lock);\n  while((c = getc()) >= 0){\n    switch(c){\n    case C('P'):  // Process listing.\n      // procdump() locks cons.lock indirectly; invoke later\n      doprocdump = 1;\n      break;\n    case C('U'):  // Kill line.\n      while(input.e != input.w &&\n            input.buf[(input.e-1) % INPUT_BUF] != '\\n'){\n        input.e--;\n        consputc(BACKSPACE);\n      }\n      break;\n    case C('H'): case '\\x7f':  // Backspace\n      if(input.e != input.w){\n        input.e--;\n        consputc(BACKSPACE);\n      }\n      break;\n    default:\n      if(c != 0 && input.e-input.r < INPUT_BUF){\n        c = (c == '\\r') ? '\\n' : c;\n        input.buf[input.e++ % INPUT_BUF] = c;\n        consputc(c);\n        if(c == '\\n' || c == C('D') || input.e == input.r+INPUT_BUF){\n          input.w = input.e;\n          wakeup(&input.r);\n        }\n      }\n      break;\n    }\n  }\n  release(&cons.lock);\n  if(doprocdump) {\n    procdump();  // now call procdump() wo. cons.lock held\n  }\n}\n\nint\nconsoleread(struct inode *ip, char *dst, int n)\n{\n  uint target;\n  int c;\n\n  iunlock(ip);\n  target = n;\n  acquire(&cons.lock);\n  while(n > 0){\n    while(input.r == input.w){\n      if(myproc()->killed){\n        release(&cons.lock);\n        ilock(ip);\n        return -1;\n      }\n      sleep(&input.r, &cons.lock);\n    }\n    c = input.buf[input.r++ % INPUT_BUF];\n    if(c == C('D')){  // EOF\n      if(n < target){\n        // Save ^D for next time, to make sure\n        // caller gets a 0-byte result.\n        input.r--;\n      }\n      break;\n    }\n    *dst++ = c;\n    --n;\n    if(c == '\\n')\n      break;\n  }\n  release(&cons.lock);\n  ilock(ip);\n\n  return target - n;\n}\n\nint\nconsolewrite(struct inode *ip, char *buf, int n)\n{\n  int i;\n\n  iunlock(ip);\n  acquire(&cons.lock);\n  for(i = 0; i < n; i++)\n    consputc(buf[i] & 0xff);\n  release(&cons.lock);\n  ilock(ip);\n\n  return n;\n}\n\nvoid\nconsoleinit(void)\n{\n  initlock(&cons.lock, \"console\");\n\n  devsw[CONSOLE].write = consolewrite;\n  devsw[CONSOLE].read = consoleread;\n  cons.locking = 1;\n\n  ioapicenable(IRQ_KBD, 0);\n}\n\n"
  },
  {
    "path": "cuth",
    "content": "#!/usr/bin/perl\n\n$| = 1;\n\nsub writefile($@){\n\tmy ($file, @lines) = @_;\n\t\n\tsleep(1);\n\topen(F, \">$file\") || die \"open >$file: $!\";\n\tprint F @lines;\n\tclose(F);\n}\n\n# Cut out #include lines that don't contribute anything.\nfor($i=0; $i<@ARGV; $i++){\n\t$file = $ARGV[$i];\n\tif(!open(F, $file)){\n\t\tprint STDERR \"open $file: $!\\n\";\n\t\tnext;\n\t}\n\t@lines = <F>;\n\tclose(F);\n\t\n\t$obj = \"$file.o\";\n\t$obj =~ s/\\.c\\.o$/.o/;\n\tsystem(\"touch $file\");\n\n\tif(system(\"make CC='gcc -Werror' $obj >/dev/null 2>\\&1\") != 0){\n\t\tprint STDERR \"make $obj failed: $rv\\n\";\n\t\tnext;\n\t}\n\n\tsystem(\"cp $file =$file\");\n\tfor($j=@lines-1; $j>=0; $j--){\n\t\tif($lines[$j] =~ /^#include/){\n\t\t\t$old = $lines[$j];\n\t\t\t$lines[$j] = \"/* CUT-H */\\n\";\n\t\t\twritefile($file, @lines);\n\t\t\tif(system(\"make CC='gcc -Werror' $obj >/dev/null 2>\\&1\") != 0){\n\t\t\t\t$lines[$j] = $old;\n\t\t\t}else{\n\t\t\t\tprint STDERR \"$file $old\";\n\t\t\t}\n\t\t}\n\t}\n\twritefile($file, grep {!/CUT-H/} @lines);\n\tsystem(\"rm =$file\");\n}\n"
  },
  {
    "path": "date.h",
    "content": "struct rtcdate {\n  uint second;\n  uint minute;\n  uint hour;\n  uint day;\n  uint month;\n  uint year;\n};\n"
  },
  {
    "path": "defs.h",
    "content": "struct buf;\nstruct context;\nstruct file;\nstruct inode;\nstruct pipe;\nstruct proc;\nstruct rtcdate;\nstruct spinlock;\nstruct sleeplock;\nstruct stat;\nstruct superblock;\n\n// bio.c\nvoid            binit(void);\nstruct buf*     bread(uint, uint);\nvoid            brelse(struct buf*);\nvoid            bwrite(struct buf*);\n\n// console.c\nvoid            consoleinit(void);\nvoid            cprintf(char*, ...);\nvoid            consoleintr(int(*)(void));\nvoid            panic(char*) __attribute__((noreturn));\n\n// exec.c\nint             exec(char*, char**);\n\n// file.c\nstruct file*    filealloc(void);\nvoid            fileclose(struct file*);\nstruct file*    filedup(struct file*);\nvoid            fileinit(void);\nint             fileread(struct file*, char*, int n);\nint             filestat(struct file*, struct stat*);\nint             filewrite(struct file*, char*, int n);\n\n// fs.c\nvoid            readsb(int dev, struct superblock *sb);\nint             dirlink(struct inode*, char*, uint);\nstruct inode*   dirlookup(struct inode*, char*, uint*);\nstruct inode*   ialloc(uint, short);\nstruct inode*   idup(struct inode*);\nvoid            iinit(int dev);\nvoid            ilock(struct inode*);\nvoid            iput(struct inode*);\nvoid            iunlock(struct inode*);\nvoid            iunlockput(struct inode*);\nvoid            iupdate(struct inode*);\nint             namecmp(const char*, const char*);\nstruct inode*   namei(char*);\nstruct inode*   nameiparent(char*, char*);\nint             readi(struct inode*, char*, uint, uint);\nvoid            stati(struct inode*, struct stat*);\nint             writei(struct inode*, char*, uint, uint);\n\n// ide.c\nvoid            ideinit(void);\nvoid            ideintr(void);\nvoid            iderw(struct buf*);\n\n// ioapic.c\nvoid            ioapicenable(int irq, int cpu);\nextern uchar    ioapicid;\nvoid            ioapicinit(void);\n\n// kalloc.c\nchar*           kalloc(void);\nvoid            kfree(char*);\nvoid            kinit1(void*, void*);\nvoid            kinit2(void*, void*);\n\n// kbd.c\nvoid            kbdintr(void);\n\n// lapic.c\nvoid            cmostime(struct rtcdate *r);\nint             lapicid(void);\nextern volatile uint*    lapic;\nvoid            lapiceoi(void);\nvoid            lapicinit(void);\nvoid            lapicstartap(uchar, uint);\nvoid            microdelay(int);\n\n// log.c\nvoid            initlog(int dev);\nvoid            log_write(struct buf*);\nvoid            begin_op();\nvoid            end_op();\n\n// mp.c\nextern int      ismp;\nvoid            mpinit(void);\n\n// picirq.c\nvoid            picenable(int);\nvoid            picinit(void);\n\n// pipe.c\nint             pipealloc(struct file**, struct file**);\nvoid            pipeclose(struct pipe*, int);\nint             piperead(struct pipe*, char*, int);\nint             pipewrite(struct pipe*, char*, int);\n\n//PAGEBREAK: 16\n// proc.c\nint             cpuid(void);\nvoid            exit(void);\nint             fork(void);\nint             growproc(int);\nint             kill(int);\nstruct cpu*     mycpu(void);\nstruct proc*    myproc();\nvoid            pinit(void);\nvoid            procdump(void);\nvoid            scheduler(void) __attribute__((noreturn));\nvoid            sched(void);\nvoid            setproc(struct proc*);\nvoid            sleep(void*, struct spinlock*);\nvoid            userinit(void);\nint             wait(void);\nvoid            wakeup(void*);\nvoid            yield(void);\n\n// swtch.S\nvoid            swtch(struct context**, struct context*);\n\n// spinlock.c\nvoid            acquire(struct spinlock*);\nvoid            getcallerpcs(void*, uint*);\nint             holding(struct spinlock*);\nvoid            initlock(struct spinlock*, char*);\nvoid            release(struct spinlock*);\nvoid            pushcli(void);\nvoid            popcli(void);\n\n// sleeplock.c\nvoid            acquiresleep(struct sleeplock*);\nvoid            releasesleep(struct sleeplock*);\nint             holdingsleep(struct sleeplock*);\nvoid            initsleeplock(struct sleeplock*, char*);\n\n// string.c\nint             memcmp(const void*, const void*, uint);\nvoid*           memmove(void*, const void*, uint);\nvoid*           memset(void*, int, uint);\nchar*           safestrcpy(char*, const char*, int);\nint             strlen(const char*);\nint             strncmp(const char*, const char*, uint);\nchar*           strncpy(char*, const char*, int);\n\n// syscall.c\nint             argint(int, int*);\nint             argptr(int, char**, int);\nint             argstr(int, char**);\nint             fetchint(uint, int*);\nint             fetchstr(uint, char**);\nvoid            syscall(void);\n\n// timer.c\nvoid            timerinit(void);\n\n// trap.c\nvoid            idtinit(void);\nextern uint     ticks;\nvoid            tvinit(void);\nextern struct spinlock tickslock;\n\n// uart.c\nvoid            uartinit(void);\nvoid            uartintr(void);\nvoid            uartputc(int);\n\n// vm.c\nvoid            seginit(void);\nvoid            kvmalloc(void);\npde_t*          setupkvm(void);\nchar*           uva2ka(pde_t*, char*);\nint             allocuvm(pde_t*, uint, uint);\nint             deallocuvm(pde_t*, uint, uint);\nvoid            freevm(pde_t*);\nvoid            inituvm(pde_t*, char*, uint);\nint             loaduvm(pde_t*, char*, struct inode*, uint, uint);\npde_t*          copyuvm(pde_t*, uint);\nvoid            switchuvm(struct proc*);\nvoid            switchkvm(void);\nint             copyout(pde_t*, uint, void*, uint);\nvoid            clearpteu(pde_t *pgdir, char *uva);\n\n// number of elements in fixed-size array\n#define NELEM(x) (sizeof(x)/sizeof((x)[0]))\n"
  },
  {
    "path": "dot-bochsrc",
    "content": "# You may now use double quotes around pathnames, in case\n# your pathname includes spaces.\n\n#=======================================================================\n# CONFIG_INTERFACE\n#\n# The configuration interface is a series of menus or dialog boxes that\n# allows you to change all the settings that control Bochs's behavior.\n# There are two choices of configuration interface: a text mode version\n# called \"textconfig\" and a graphical version called \"wx\".  The text\n# mode version uses stdin/stdout and is always compiled in.  The graphical\n# version is only available when you use \"--with-wx\" on the configure \n# command.  If you do not write a config_interface line, Bochs will \n# choose a default for you.\n#\n# NOTE: if you use the \"wx\" configuration interface, you must also use\n# the \"wx\" display library.\n#=======================================================================\n#config_interface: textconfig\n#config_interface: wx\n\n#=======================================================================\n# DISPLAY_LIBRARY\n#\n# The display library is the code that displays the Bochs VGA screen.  Bochs \n# has a selection of about 10 different display library implementations for \n# different platforms.  If you run configure with multiple --with-* options, \n# the display_library command lets you choose which one you want to run with.\n# If you do not write a display_library line, Bochs will choose a default for\n# you.\n#\n# The choices are: \n#   x              use X windows interface, cross platform\n#   win32          use native win32 libraries\n#   carbon         use Carbon library (for MacOS X)\n#   beos           use native BeOS libraries\n#   macintosh      use MacOS pre-10\n#   amigaos        use native AmigaOS libraries\n#   sdl            use SDL library, cross platform\n#   svga           use SVGALIB library for Linux, allows graphics without X11\n#   term           text only, uses curses/ncurses library, cross platform\n#   rfb            provides an interface to AT&T's VNC viewer, cross platform\n#   wx             use wxWidgets library, cross platform\n#   nogui          no display at all\n#\n# NOTE: if you use the \"wx\" configuration interface, you must also use\n# the \"wx\" display library.\n#\n# Specific options:\n# Some display libraries now support specific option to control their\n# behaviour. See the examples below for currently supported options.\n#=======================================================================\n#display_library: amigaos\n#display_library: beos\n#display_library: carbon\n#display_library: macintosh\n#display_library: nogui\n#display_library: rfb, options=\"timeout=60\" # time to wait for client\n#display_library: sdl, options=\"fullscreen\" # startup in fullscreen mode\n#display_library: term\n#display_library: win32, options=\"legacyF12\" # use F12 to toggle mouse\n#display_library: wx\n#display_library: x\n\n#=======================================================================\n# ROMIMAGE:\n# The ROM BIOS controls what the PC does when it first powers on.\n# Normally, you can use a precompiled BIOS in the source or binary\n# distribution called BIOS-bochs-latest. The ROM BIOS is usually loaded\n# starting at address 0xf0000, and it is exactly 64k long.\n# You can also use the environment variable $BXSHARE to specify the\n# location of the BIOS.\n# The usage of external large BIOS images (up to 512k) at memory top is\n# now supported, but we still recommend to use the BIOS distributed with\n# Bochs. Now the start address can be calculated from image size.\n#=======================================================================\nromimage: file=$BXSHARE/BIOS-bochs-latest\n#romimage: file=mybios.bin, address=0xfff80000 # 512k at memory top\n#romimage: file=mybios.bin # calculate start address from image size\n\n#=======================================================================\n# CPU:\n# This defines cpu-related parameters inside Bochs:\n#\n#  COUNT:\n#  Set the number of processors when Bochs is compiled for SMP emulation.\n#  Bochs currently supports up to 8 processors. If Bochs is compiled\n#  without SMP support, it won't accept values different from 1.\n#\n#  IPS:\n#  Emulated Instructions Per Second.  This is the number of IPS that bochs\n#  is capable of running on your machine. You can recompile Bochs with\n#  --enable-show-ips option enabled, to find your workstation's capability.\n#  Measured IPS value will then be logged into your log file or status bar\n#  (if supported by the gui).\n#\n#  IPS is used to calibrate many time-dependent events within the bochs \n#  simulation.  For example, changing IPS affects the frequency of VGA\n#  updates, the duration of time before a key starts to autorepeat, and\n#  the measurement of BogoMips and other benchmarks.\n#\n#  Examples:\n#  Machine                                         Mips\n# ________________________________________________________________\n#  2.1Ghz Athlon XP with Linux 2.6/g++ 3.4         12 to 15 Mips\n#  1.6Ghz Intel P4 with Win2000/g++ 3.3             5 to  7 Mips\n#  650Mhz Athlon K-7 with Linux 2.4.4/egcs-2.91.66  2 to  2.5 Mips\n#  400Mhz Pentium II with Linux 2.0.36/egcs-1.0.3   1 to  1.8 Mips\n#=======================================================================\ncpu: count=2, ips=10000000\n\n#=======================================================================\n# MEGS\n# Set the number of Megabytes of physical memory you want to emulate. \n# The default is 32MB, most OS's won't need more than that.\n# The maximum amount of memory supported is 2048Mb.\n#=======================================================================\n#megs: 256\n#megs: 128\n#megs: 64\nmegs: 32\n#megs: 16\n#megs: 8\n\n#=======================================================================\n# OPTROMIMAGE[1-4]:\n# You may now load up to 4 optional ROM images. Be sure to use a \n# read-only area, typically between C8000 and EFFFF. These optional\n# ROM images should not overwrite the rombios (located at\n# F0000-FFFFF) and the videobios (located at C0000-C7FFF).\n# Those ROM images will be initialized by the bios if they contain \n# the right signature (0x55AA) and a valid checksum.\n# It can also be a convenient way to upload some arbitrary code/data\n# in the simulation, that can be retrieved by the boot loader\n#=======================================================================\n#optromimage1: file=optionalrom.bin, address=0xd0000\n#optromimage2: file=optionalrom.bin, address=0xd1000\n#optromimage3: file=optionalrom.bin, address=0xd2000\n#optromimage4: file=optionalrom.bin, address=0xd3000\n\n#optramimage1: file=/path/file1.img, address=0x0010000\n#optramimage2: file=/path/file2.img, address=0x0020000\n#optramimage3: file=/path/file3.img, address=0x0030000\n#optramimage4: file=/path/file4.img, address=0x0040000\n\n#=======================================================================\n# VGAROMIMAGE\n# You now need to load a VGA ROM BIOS into C0000.\n#=======================================================================\n#vgaromimage: file=bios/VGABIOS-elpin-2.40\nvgaromimage: file=$BXSHARE/VGABIOS-lgpl-latest\n#vgaromimage: file=bios/VGABIOS-lgpl-latest-cirrus\n\n#=======================================================================\n# VGA:\n# Here you can specify the display extension to be used. With the value\n# 'none' you can use standard VGA with no extension. Other supported\n# values are 'vbe' for Bochs VBE and 'cirrus' for Cirrus SVGA support.\n#=======================================================================\n#vga: extension=cirrus\n#vga: extension=vbe\nvga: extension=none\n\n#=======================================================================\n# FLOPPYA:\n# Point this to pathname of floppy image file or device\n# This should be of a bootable floppy(image/device) if you're\n# booting from 'a' (or 'floppy').\n#\n# You can set the initial status of the media to 'ejected' or 'inserted'.\n#   floppya: 2_88=path, status=ejected             (2.88M 3.5\" floppy)\n#   floppya: 1_44=path, status=inserted            (1.44M 3.5\" floppy)\n#   floppya: 1_2=path, status=ejected              (1.2M  5.25\" floppy)\n#   floppya: 720k=path, status=inserted            (720K  3.5\" floppy)\n#   floppya: 360k=path, status=inserted            (360K  5.25\" floppy)\n#   floppya: 320k=path, status=inserted            (320K  5.25\" floppy)\n#   floppya: 180k=path, status=inserted            (180K  5.25\" floppy)\n#   floppya: 160k=path, status=inserted            (160K  5.25\" floppy)\n#   floppya: image=path, status=inserted           (guess type from image size)\n#\n# The path should be the name of a disk image file.  On Unix, you can use a raw\n# device name such as /dev/fd0 on Linux.  On win32 platforms, use drive letters\n# such as a: or b: as the path.  The parameter 'image' works with image files\n# only. In that case the size must match one of the supported types.\n#=======================================================================\nfloppya: 1_44=/dev/fd0, status=inserted\n#floppya: image=../1.44, status=inserted\n#floppya: 1_44=/dev/fd0H1440, status=inserted\n#floppya: 1_2=../1_2, status=inserted\n#floppya: 1_44=a:, status=inserted\n#floppya: 1_44=a.img, status=inserted\n#floppya: 1_44=/dev/rfd0a, status=inserted\n\n#=======================================================================\n# FLOPPYB:\n# See FLOPPYA above for syntax\n#=======================================================================\n#floppyb: 1_44=b:, status=inserted\nfloppyb: 1_44=b.img, status=inserted\n\n#=======================================================================\n# ATA0, ATA1, ATA2, ATA3\n# ATA controller for hard disks and cdroms\n#\n# ata[0-3]: enabled=[0|1], ioaddr1=addr, ioaddr2=addr, irq=number\n# \n# These options enables up to 4 ata channels. For each channel\n# the two base io addresses and the irq must be specified.\n# \n# ata0 and ata1 are enabled by default with the values shown below\n#\n# Examples:\n#   ata0: enabled=1, ioaddr1=0x1f0, ioaddr2=0x3f0, irq=14\n#   ata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\n#   ata2: enabled=1, ioaddr1=0x1e8, ioaddr2=0x3e0, irq=11\n#   ata3: enabled=1, ioaddr1=0x168, ioaddr2=0x360, irq=9\n#=======================================================================\nata0: enabled=1, ioaddr1=0x1f0, ioaddr2=0x3f0, irq=14\nata1: enabled=1, ioaddr1=0x170, ioaddr2=0x370, irq=15\nata2: enabled=0, ioaddr1=0x1e8, ioaddr2=0x3e0, irq=11\nata3: enabled=0, ioaddr1=0x168, ioaddr2=0x360, irq=9\n\n#=======================================================================\n# ATA[0-3]-MASTER, ATA[0-3]-SLAVE\n#\n# This defines the type and characteristics of all attached ata devices:\n#   type=       type of attached device [disk|cdrom] \n#   mode=       only valid for disks [flat|concat|external|dll|sparse|vmware3]\n#   mode=       only valid for disks [undoable|growing|volatile]\n#   path=       path of the image\n#   cylinders=  only valid for disks\n#   heads=      only valid for disks\n#   spt=        only valid for disks\n#   status=     only valid for cdroms [inserted|ejected]\n#   biosdetect= type of biosdetection [none|auto], only for disks on ata0 [cmos]\n#   translation=type of translation of the bios, only for disks [none|lba|large|rechs|auto]\n#   model=      string returned by identify device command\n#   journal=    optional filename of the redolog for undoable and volatile disks\n#   \n# Point this at a hard disk image file, cdrom iso file, or physical cdrom\n# device.  To create a hard disk image, try running bximage.  It will help you\n# choose the size and then suggest a line that works with it.\n#\n# In UNIX it may be possible to use a raw device as a Bochs hard disk, \n# but WE DON'T RECOMMEND IT.  In Windows there is no easy way.\n#\n# In windows, the drive letter + colon notation should be used for cdroms.\n# Depending on versions of windows and drivers, you may only be able to \n# access the \"first\" cdrom in the system.  On MacOSX, use path=\"drive\"\n# to access the physical drive.\n#\n# The path is always mandatory. For flat hard disk images created with\n# bximage geometry autodetection can be used (cylinders=0 -> cylinders are\n# calculated using heads=16 and spt=63). For other hard disk images and modes\n# the cylinders, heads, and spt are mandatory.\n#\n# Default values are:\n#   mode=flat, biosdetect=auto, translation=auto, model=\"Generic 1234\"\n#\n# The biosdetect option has currently no effect on the bios\n#\n# Examples:\n#   ata0-master: type=disk, mode=flat, path=10M.sample, cylinders=306, heads=4, spt=17\n#   ata0-slave:  type=disk, mode=flat, path=20M.sample, cylinders=615, heads=4, spt=17\n#   ata1-master: type=disk, mode=flat, path=30M.sample, cylinders=615, heads=6, spt=17\n#   ata1-slave:  type=disk, mode=flat, path=46M.sample, cylinders=940, heads=6, spt=17\n#   ata2-master: type=disk, mode=flat, path=62M.sample, cylinders=940, heads=8, spt=17\n#   ata2-slave:  type=disk, mode=flat, path=112M.sample, cylinders=900, heads=15, spt=17\n#   ata3-master: type=disk, mode=flat, path=483M.sample, cylinders=1024, heads=15, spt=63\n#   ata3-slave:  type=cdrom, path=iso.sample, status=inserted\n#=======================================================================\nata0-master: type=disk, mode=flat, path=\"xv6.img\", cylinders=100, heads=10, spt=10\nata0-slave: type=disk, mode=flat, path=\"fs.img\", cylinders=1024, heads=1, spt=1\n#ata0-slave: type=cdrom, path=D:, status=inserted\n#ata0-slave: type=cdrom, path=/dev/cdrom, status=inserted\n#ata0-slave: type=cdrom, path=\"drive\", status=inserted\n#ata0-slave: type=cdrom, path=/dev/rcd0d, status=inserted \n\n#=======================================================================\n# BOOT:\n# This defines the boot sequence. Now you can specify up to 3 boot drives.\n# You can either boot from 'floppy', 'disk' or 'cdrom'\n# legacy 'a' and 'c' are also supported\n# Examples:\n#   boot: floppy\n#   boot: disk\n#   boot: cdrom\n#   boot: c\n#   boot: a\n#   boot: cdrom, floppy, disk\n#=======================================================================\n#boot: floppy\nboot: disk\n\n#=======================================================================\n# CLOCK:\n# This defines the parameters of the clock inside Bochs:\n#\n#  SYNC:\n#  TO BE COMPLETED (see Greg explanation in feature request #536329)\n#\n#  TIME0:\n#  Specifies the start (boot) time of the virtual machine. Use a time \n#  value as returned by the time(2) system call. If no time0 value is \n#  set or if time0 equal to 1 (special case) or if time0 equal 'local', \n#  the simulation will be started at the current local host time.\n#  If time0 equal to 2 (special case) or if time0 equal 'utc',\n#  the simulation will be started at the current utc time.\n#\n# Syntax:\n#  clock: sync=[none|slowdown|realtime|both], time0=[timeValue|local|utc]\n#\n# Example:\n#   clock: sync=none,     time0=local       # Now (localtime)\n#   clock: sync=slowdown, time0=315529200   # Tue Jan  1 00:00:00 1980\n#   clock: sync=none,     time0=631148400   # Mon Jan  1 00:00:00 1990\n#   clock: sync=realtime, time0=938581955   # Wed Sep 29 07:12:35 1999\n#   clock: sync=realtime, time0=946681200   # Sat Jan  1 00:00:00 2000\n#   clock: sync=none,     time0=1           # Now (localtime)\n#   clock: sync=none,     time0=utc         # Now (utc/gmt)\n# \n# Default value are sync=none, time0=local\n#=======================================================================\n#clock: sync=none, time0=local\n\n\n#=======================================================================\n# FLOPPY_BOOTSIG_CHECK: disabled=[0|1]\n# Enables or disables the 0xaa55 signature check on boot floppies\n# Defaults to disabled=0\n# Examples:\n#   floppy_bootsig_check: disabled=0\n#   floppy_bootsig_check: disabled=1\n#=======================================================================\n#floppy_bootsig_check: disabled=1\nfloppy_bootsig_check: disabled=0\n\n#=======================================================================\n# LOG:\n# Give the path of the log file you'd like Bochs debug and misc. verbiage\n# to be written to. If you don't use this option or set the filename to\n# '-' the output is written to the console. If you really don't want it,\n# make it \"/dev/null\" (Unix) or \"nul\" (win32). :^(\n#\n# Examples:\n#   log: ./bochs.out\n#   log: /dev/tty\n#=======================================================================\n#log: /dev/null\nlog: bochsout.txt\n\n#=======================================================================\n# LOGPREFIX:\n# This handles the format of the string prepended to each log line.\n# You may use those special tokens :\n#   %t : 11 decimal digits timer tick\n#   %i : 8 hexadecimal digits of cpu current eip (ignored in SMP configuration)\n#   %e : 1 character event type ('i'nfo, 'd'ebug, 'p'anic, 'e'rror)\n#   %d : 5 characters string of the device, between brackets\n# \n# Default : %t%e%d\n# Examples:\n#   logprefix: %t-%e-@%i-%d\n#   logprefix: %i%e%d\n#=======================================================================\n#logprefix: %t%e%d\n\n#=======================================================================\n# LOG CONTROLS\n#\n# Bochs now has four severity levels for event logging.\n#   panic: cannot proceed.  If you choose to continue after a panic, \n#          don't be surprised if you get strange behavior or crashes.\n#   error: something went wrong, but it is probably safe to continue the\n#          simulation.\n#   info: interesting or useful messages.\n#   debug: messages useful only when debugging the code.  This may\n#          spit out thousands per second.\n#\n# For events of each level, you can choose to crash, report, or ignore.\n# TODO: allow choice based on the facility: e.g. crash on panics from\n#       everything except the cdrom, and only report those.\n#\n# If you are experiencing many panics, it can be helpful to change\n# the panic action to report instead of fatal.  However, be aware\n# that anything executed after a panic is uncharted territory and can \n# cause bochs to become unstable.  The panic is a \"graceful exit,\" so\n# if you disable it you may get a spectacular disaster instead.\n#=======================================================================\npanic: action=ask\nerror: action=report\ninfo: action=report\ndebug: action=ignore\n#pass: action=fatal\n\n#=======================================================================\n# DEBUGGER_LOG:\n# Give the path of the log file you'd like Bochs to log debugger output.\n# If you really don't want it, make it /dev/null or '-'. :^(\n#\n# Examples:\n#   debugger_log: ./debugger.out\n#=======================================================================\n#debugger_log: /dev/null\n#debugger_log: debugger.out\ndebugger_log: -\n\n#=======================================================================\n# COM1, COM2, COM3, COM4:\n# This defines a serial port (UART type 16550A). In the 'term' you can specify\n# a device to use as com1. This can be a real serial line, or a pty.  To use\n# a pty (under X/Unix), create two windows (xterms, usually).  One of them will\n# run bochs, and the other will act as com1. Find out the tty the com1\n# window using the `tty' command, and use that as the `dev' parameter.\n# Then do `sleep 1000000' in the com1 window to keep the shell from\n# messing with things, and run bochs in the other window.  Serial I/O to\n# com1 (port 0x3f8) will all go to the other window.\n# Other serial modes are 'null' (no input/output), 'file' (output to a file\n# specified as the 'dev' parameter), 'raw' (use the real serial port - under\n# construction for win32), 'mouse' (standard serial mouse - requires\n# mouse option setting 'type=serial' or 'type=serial_wheel') and 'socket'\n# (connect a networking socket).\n#\n# Examples:\n#   com1: enabled=1, mode=null\n#   com1: enabled=1, mode=mouse\n#   com2: enabled=1, mode=file, dev=serial.out\n#   com3: enabled=1, mode=raw, dev=com1\n#   com3: enabled=1, mode=socket, dev=localhost:8888\n#=======================================================================\n#com1: enabled=1, mode=term, dev=/dev/ttyp9\n\n\n#=======================================================================\n# PARPORT1, PARPORT2:\n# This defines a parallel (printer) port. When turned on and an output file is\n# defined the emulated printer port sends characters printed by the guest OS\n# into the output file. On some platforms a device filename can be used to\n# send the data to the real parallel port (e.g. \"/dev/lp0\" on Linux, \"lpt1\" on\n# win32 platforms).\n#\n# Examples:\n#   parport1: enabled=1, file=\"parport.out\"\n#   parport2: enabled=1, file=\"/dev/lp0\"\n#   parport1: enabled=0\n#=======================================================================\nparport1: enabled=1, file=\"/dev/stdout\"\n\n#=======================================================================\n# SB16:\n# This defines the SB16 sound emulation. It can have several of the\n# following properties.\n# All properties are in the format sb16: property=value\n# midi: The filename is where the midi data is sent. This can be a\n#       device or just a file if you want to record the midi data.\n# midimode:\n#      0=no data\n#      1=output to device (system dependent. midi denotes the device driver)\n#      2=SMF file output, including headers\n#      3=output the midi data stream to the file (no midi headers and no\n#        delta times, just command and data bytes)\n# wave: This is the device/file where wave output is stored\n# wavemode:\n#      0=no data\n#      1=output to device (system dependent. wave denotes the device driver)\n#      2=VOC file output, incl. headers\n#      3=output the raw wave stream to the file\n# log:  The file to write the sb16 emulator messages to.\n# loglevel:\n#      0=no log\n#      1=resource changes, midi program and bank changes\n#      2=severe errors\n#      3=all errors\n#      4=all errors plus all port accesses\n#      5=all errors and port accesses plus a lot of extra info\n# dmatimer:\n#      microseconds per second for a DMA cycle.  Make it smaller to fix\n#      non-continuous sound.  750000 is usually a good value.  This needs a\n#      reasonably correct setting for the IPS parameter of the CPU option.\n#\n# For an example look at the next line:\n#=======================================================================\n\n#sb16: midimode=1, midi=/dev/midi00, wavemode=1, wave=/dev/dsp, loglevel=2, log=sb16.log, dmatimer=600000\n\n#=======================================================================\n# VGA_UPDATE_INTERVAL:\n# Video memory is scanned for updates and screen updated every so many\n# virtual seconds.  The default is 40000, about 25Hz. Keep in mind that\n# you must tweak the 'cpu: ips=N' directive to be as close to the number\n# of emulated instructions-per-second your workstation can do, for this\n# to be accurate.\n#\n# Examples:\n#   vga_update_interval: 250000\n#=======================================================================\nvga_update_interval: 300000\n\n# using for Winstone '98 tests\n#vga_update_interval:  100000\n\n#=======================================================================\n# KEYBOARD_SERIAL_DELAY:\n# Approximate time in microseconds that it takes one character to\n# be transfered from the keyboard to controller over the serial path.\n# Examples:\n#   keyboard_serial_delay: 200\n#=======================================================================\nkeyboard_serial_delay: 250\n\n#=======================================================================\n# KEYBOARD_PASTE_DELAY:\n# Approximate time in microseconds between attempts to paste\n# characters to the keyboard controller. This leaves time for the\n# guest os to deal with the flow of characters.  The ideal setting\n# depends on how your operating system processes characters.  The\n# default of 100000 usec (.1 seconds) was chosen because it works \n# consistently in Windows.\n#\n# If your OS is losing characters during a paste, increase the paste\n# delay until it stops losing characters.\n#\n# Examples:\n#   keyboard_paste_delay: 100000\n#=======================================================================\nkeyboard_paste_delay: 100000\n\n#=======================================================================\n# MOUSE: \n# This option prevents Bochs from creating mouse \"events\" unless a mouse\n# is  enabled. The hardware emulation itself is not disabled by this.\n# You can turn the mouse on by setting enabled to 1, or turn it off by\n# setting enabled to 0. Unless you have a particular reason for enabling\n# the mouse by default, it is recommended that you leave it off.\n# You can also toggle the mouse usage at runtime (control key + middle\n# mouse button on X11, SDL, wxWidgets and Win32).\n# With the mouse type option you can select the type of mouse to emulate.\n# The default value is 'ps2'. The other choices are 'imps2' (wheel mouse\n# on PS/2), 'serial', 'serial_wheel' (one com port requires setting\n# 'mode=mouse') and 'usb' (3-button mouse - one of the USB ports must be\n# connected with the 'mouse' device - requires PCI and USB support).\n#\n# Examples:\n#   mouse: enabled=1\n#   mouse: enabled=1, type=imps2\n#   mouse: enabled=1, type=serial\n#   mouse: enabled=0\n#=======================================================================\nmouse: enabled=0\n\n#=======================================================================\n# private_colormap: Request that the GUI create and use it's own\n#                   non-shared colormap.  This colormap will be used\n#                   when in the bochs window.  If not enabled, a\n#                   shared colormap scheme may be used.  Not implemented\n#                   on all GUI's.\n#\n# Examples:\n#   private_colormap: enabled=1\n#   private_colormap: enabled=0\n#=======================================================================\nprivate_colormap: enabled=0\n\n#=======================================================================\n# fullscreen: ONLY IMPLEMENTED ON AMIGA\n#             Request that Bochs occupy the entire screen instead of a \n#             window.\n#\n# Examples:\n#   fullscreen: enabled=0\n#   fullscreen: enabled=1\n#=======================================================================\n#fullscreen: enabled=0\n#screenmode: name=\"sample\"\n\n#=======================================================================\n# ne2k: NE2000 compatible ethernet adapter\n#\n# Examples:\n# ne2k: ioaddr=IOADDR, irq=IRQ, mac=MACADDR, ethmod=MODULE, ethdev=DEVICE, script=SCRIPT\n#\n# ioaddr, irq: You probably won't need to change ioaddr and irq, unless there\n# are IRQ conflicts.\n#\n# mac: The MAC address MUST NOT match the address of any machine on the net.\n# Also, the first byte must be an even number (bit 0 set means a multicast\n# address), and you cannot use ff:ff:ff:ff:ff:ff because that's the broadcast\n# address.  For the ethertap module, you must use fe:fd:00:00:00:01.  There may\n# be other restrictions too.  To be safe, just use the b0:c4... address.\n#\n# ethdev: The ethdev value is the name of the network interface on your host\n# platform.  On UNIX machines, you can get the name by running ifconfig.  On\n# Windows machines, you must run niclist to get the name of the ethdev.\n# Niclist source code is in misc/niclist.c and it is included in Windows \n# binary releases.\n#\n# script: The script value is optional, and is the name of a script that \n# is executed after bochs initialize the network interface. You can use \n# this script to configure this network interface, or enable masquerading.\n# This is mainly useful for the tun/tap devices that only exist during\n# Bochs execution. The network interface name is supplied to the script\n# as first parameter\n#\n# If you don't want to make connections to any physical networks,\n# you can use the following 'ethmod's to simulate a virtual network.\n#   null: All packets are discarded, but logged to a few files.\n#   arpback: ARP is simulated. Disabled by default.\n#   vde:  Virtual Distributed Ethernet\n#   vnet: ARP, ICMP-echo(ping), DHCP and read/write TFTP are simulated.\n#         The virtual host uses 192.168.10.1.\n#         DHCP assigns 192.168.10.2 to the guest.\n#         TFTP uses the ethdev value for the root directory and doesn't\n#         overwrite files.\n#\n#=======================================================================\n# ne2k: ioaddr=0x240, irq=9, mac=fe:fd:00:00:00:01, ethmod=fbsd, ethdev=en0 #macosx\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:00, ethmod=fbsd, ethdev=xl0\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:00, ethmod=linux, ethdev=eth0\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:01, ethmod=win32, ethdev=MYCARD\n# ne2k: ioaddr=0x240, irq=9, mac=fe:fd:00:00:00:01, ethmod=tap, ethdev=tap0\n# ne2k: ioaddr=0x240, irq=9, mac=fe:fd:00:00:00:01, ethmod=tuntap, ethdev=/dev/net/tun0, script=./tunconfig\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:01, ethmod=null, ethdev=eth0\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:01, ethmod=vde, ethdev=\"/tmp/vde.ctl\"\n# ne2k: ioaddr=0x240, irq=9, mac=b0:c4:20:00:00:01, ethmod=vnet, ethdev=\"c:/temp\"\n\n#=======================================================================\n# KEYBOARD_MAPPING:\n# This enables a remap of a physical localized keyboard to a \n# virtualized us keyboard, as the PC architecture expects.\n# If enabled, the keymap file must be specified.\n# \n# Examples:\n#   keyboard_mapping: enabled=1, map=gui/keymaps/x11-pc-de.map\n#=======================================================================\nkeyboard_mapping: enabled=0, map=\n\n#=======================================================================\n# KEYBOARD_TYPE:\n# Type of keyboard return by a \"identify keyboard\" command to the\n# keyboard controler. It must be one of \"xt\", \"at\" or \"mf\".\n# Defaults to \"mf\". It should be ok for almost everybody. A known\n# exception is french macs, that do have a \"at\"-like keyboard.\n#\n# Examples:\n#   keyboard_type: mf\n#=======================================================================\n#keyboard_type: mf\n\n#=======================================================================\n# USER_SHORTCUT:\n# This defines the keyboard shortcut to be sent when you press the \"user\"\n# button in the headerbar. The shortcut string is a combination of maximum\n# 3 key names (listed below) separated with a '-' character. The old-style\n# syntax (without the '-') still works for the key combinations supported\n# in Bochs 2.2.1.\n# Valid key names:\n# \"alt\", \"bksl\", \"bksp\", \"ctrl\", \"del\", \"down\", \"end\", \"enter\", \"esc\",\n# \"f1\", ... \"f12\", \"home\", \"ins\", \"left\", \"menu\", \"minus\", \"pgdwn\", \"pgup\",\n# \"plus\", \"right\", \"shift\", \"space\", \"tab\", \"up\", and \"win\".\n#\n# Example:\n#   user_shortcut: keys=ctrl-alt-del\n#=======================================================================\n#user_shortcut: keys=ctrl-alt-del\n\n#=======================================================================\n# I440FXSUPPORT:\n# This option controls the presence of the i440FX PCI chipset. You can\n# also specify the devices connected to PCI slots. Up to 5 slots are\n# available now. These devices are currently supported: ne2k, pcivga,\n# pcidev and pcipnic. If Bochs is compiled with Cirrus SVGA support\n# you'll have the additional choice 'cirrus'.\n#\n# Example:\n#   i440fxsupport: enabled=1, slot1=pcivga, slot2=ne2k\n#=======================================================================\n#i440fxsupport: enabled=1\n\n#=======================================================================\n# USB1:\n# This option controls the presence of the USB root hub which is a part\n# of the i440FX PCI chipset. With the portX option you can connect devices\n# to the hub (currently supported: 'mouse' and 'keypad'). If you connect\n# the mouse to one of the ports and use the mouse option 'type=usb' you'll\n# have a 3-button USB mouse.\n#\n# Example:\n#   usb1: enabled=1, port1=mouse, port2=keypad\n#=======================================================================\n#usb1: enabled=1\n\n#=======================================================================\n# CMOSIMAGE:\n# This defines image file that can be loaded into the CMOS RAM at startup.\n# The rtc_init parameter controls whether initialize the RTC with values stored\n# in the image. By default the time0 argument given to the clock option is used.\n# With 'rtc_init=image' the image is the source for the initial time.\n#\n# Example:\n#   cmosimage: file=cmos.img, rtc_init=image\n#=======================================================================\n#cmosimage: file=cmos.img, rtc_init=time0\n\n#=======================================================================\n# other stuff\n#=======================================================================\n#magic_break: enabled=1\n#load32bitOSImage: os=nullkernel, path=../kernel.img, iolog=../vga_io.log\n#load32bitOSImage: os=linux, path=../linux.img, iolog=../vga_io.log, initrd=../initrd.img\n#text_snapshot_check: enable\n\n#-------------------------\n# PCI host device mapping\n#-------------------------\n#pcidev: vendor=0x1234, device=0x5678\n\n#=======================================================================\n# GDBSTUB:\n# Enable GDB stub. See user documentation for details.\n# Default value is enabled=0.\n#=======================================================================\n#gdbstub: enabled=0, port=1234, text_base=0, data_base=0, bss_base=0\n\n#=======================================================================\n# IPS:\n# The IPS directive is DEPRECATED. Use the parameter IPS of the CPU\n# directive instead.\n#=======================================================================\n#ips: 10000000\n\n#=======================================================================\n# for Macintosh, use the style of pathnames in the following\n# examples.\n#\n# vgaromimage: :bios:VGABIOS-elpin-2.40\n# romimage: file=:bios:BIOS-bochs-latest, address=0xf0000\n# floppya: 1_44=[fd:], status=inserted\n#=======================================================================\n"
  },
  {
    "path": "echo.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(int argc, char *argv[])\n{\n  int i;\n\n  for(i = 1; i < argc; i++)\n    printf(1, \"%s%s\", argv[i], i+1 < argc ? \" \" : \"\\n\");\n  exit();\n}\n"
  },
  {
    "path": "elf.h",
    "content": "// Format of an ELF executable file\n\n#define ELF_MAGIC 0x464C457FU  // \"\\x7FELF\" in little endian\n\n// File header\nstruct elfhdr {\n  uint magic;  // must equal ELF_MAGIC\n  uchar elf[12];\n  ushort type;\n  ushort machine;\n  uint version;\n  uint entry;\n  uint phoff;\n  uint shoff;\n  uint flags;\n  ushort ehsize;\n  ushort phentsize;\n  ushort phnum;\n  ushort shentsize;\n  ushort shnum;\n  ushort shstrndx;\n};\n\n// Program section header\nstruct proghdr {\n  uint type;\n  uint off;\n  uint vaddr;\n  uint paddr;\n  uint filesz;\n  uint memsz;\n  uint flags;\n  uint align;\n};\n\n// Values for Proghdr type\n#define ELF_PROG_LOAD           1\n\n// Flag bits for Proghdr flags\n#define ELF_PROG_FLAG_EXEC      1\n#define ELF_PROG_FLAG_WRITE     2\n#define ELF_PROG_FLAG_READ      4\n"
  },
  {
    "path": "entry.S",
    "content": "# The xv6 kernel starts executing in this file. This file is linked with\n# the kernel C code, so it can refer to kernel symbols such as main().\n# The boot block (bootasm.S and bootmain.c) jumps to entry below.\n        \n# Multiboot header, for multiboot boot loaders like GNU Grub.\n# http://www.gnu.org/software/grub/manual/multiboot/multiboot.html\n#\n# Using GRUB 2, you can boot xv6 from a file stored in a\n# Linux file system by copying kernel or kernelmemfs to /boot\n# and then adding this menu entry:\n#\n# menuentry \"xv6\" {\n# \tinsmod ext2\n# \tset root='(hd0,msdos1)'\n# \tset kernel='/boot/kernel'\n# \techo \"Loading ${kernel}...\"\n# \tmultiboot ${kernel} ${kernel}\n# \tboot\n# }\n\n#include \"asm.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"param.h\"\n\n# Multiboot header.  Data to direct multiboot loader.\n.p2align 2\n.text\n.globl multiboot_header\nmultiboot_header:\n  #define magic 0x1badb002\n  #define flags 0\n  .long magic\n  .long flags\n  .long (-magic-flags)\n\n# By convention, the _start symbol specifies the ELF entry point.\n# Since we haven't set up virtual memory yet, our entry point is\n# the physical address of 'entry'.\n.globl _start\n_start = V2P_WO(entry)\n\n# Entering xv6 on boot processor, with paging off.\n.globl entry\nentry:\n  # Turn on page size extension for 4Mbyte pages\n  movl    %cr4, %eax\n  orl     $(CR4_PSE), %eax\n  movl    %eax, %cr4\n  # Set page directory\n  movl    $(V2P_WO(entrypgdir)), %eax\n  movl    %eax, %cr3\n  # Turn on paging.\n  movl    %cr0, %eax\n  orl     $(CR0_PG|CR0_WP), %eax\n  movl    %eax, %cr0\n\n  # Set up the stack pointer.\n  movl $(stack + KSTACKSIZE), %esp\n\n  # Jump to main(), and switch to executing at\n  # high addresses. The indirect call is needed because\n  # the assembler produces a PC-relative instruction\n  # for a direct jump.\n  mov $main, %eax\n  jmp *%eax\n\n.comm stack, KSTACKSIZE\n"
  },
  {
    "path": "entryother.S",
    "content": "#include \"asm.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n\t\n# Each non-boot CPU (\"AP\") is started up in response to a STARTUP\n# IPI from the boot CPU.  Section B.4.2 of the Multi-Processor\n# Specification says that the AP will start in real mode with CS:IP\n# set to XY00:0000, where XY is an 8-bit value sent with the\n# STARTUP. Thus this code must start at a 4096-byte boundary.\n#\n# Because this code sets DS to zero, it must sit\n# at an address in the low 2^16 bytes.\n#\n# Startothers (in main.c) sends the STARTUPs one at a time.\n# It copies this code (start) at 0x7000.  It puts the address of\n# a newly allocated per-core stack in start-4,the address of the\n# place to jump to (mpenter) in start-8, and the physical address\n# of entrypgdir in start-12.\n#\n# This code combines elements of bootasm.S and entry.S.\n\n.code16           \n.globl start\nstart:\n  cli            \n\n  # Zero data segment registers DS, ES, and SS.\n  xorw    %ax,%ax\n  movw    %ax,%ds\n  movw    %ax,%es\n  movw    %ax,%ss\n\n  # Switch from real to protected mode.  Use a bootstrap GDT that makes\n  # virtual addresses map directly to physical addresses so that the\n  # effective memory map doesn't change during the transition.\n  lgdt    gdtdesc\n  movl    %cr0, %eax\n  orl     $CR0_PE, %eax\n  movl    %eax, %cr0\n\n  # Complete the transition to 32-bit protected mode by using a long jmp\n  # to reload %cs and %eip.  The segment descriptors are set up with no\n  # translation, so that the mapping is still the identity mapping.\n  ljmpl    $(SEG_KCODE<<3), $(start32)\n\n//PAGEBREAK!\n.code32  # Tell assembler to generate 32-bit code now.\nstart32:\n  # Set up the protected-mode data segment registers\n  movw    $(SEG_KDATA<<3), %ax    # Our data segment selector\n  movw    %ax, %ds                # -> DS: Data Segment\n  movw    %ax, %es                # -> ES: Extra Segment\n  movw    %ax, %ss                # -> SS: Stack Segment\n  movw    $0, %ax                 # Zero segments not ready for use\n  movw    %ax, %fs                # -> FS\n  movw    %ax, %gs                # -> GS\n\n  # Turn on page size extension for 4Mbyte pages\n  movl    %cr4, %eax\n  orl     $(CR4_PSE), %eax\n  movl    %eax, %cr4\n  # Use entrypgdir as our initial page table\n  movl    (start-12), %eax\n  movl    %eax, %cr3\n  # Turn on paging.\n  movl    %cr0, %eax\n  orl     $(CR0_PE|CR0_PG|CR0_WP), %eax\n  movl    %eax, %cr0\n\n  # Switch to the stack allocated by startothers()\n  movl    (start-4), %esp\n  # Call mpenter()\n  call\t *(start-8)\n\n  movw    $0x8a00, %ax\n  movw    %ax, %dx\n  outw    %ax, %dx\n  movw    $0x8ae0, %ax\n  outw    %ax, %dx\nspin:\n  jmp     spin\n\n.p2align 2\ngdt:\n  SEG_NULLASM\n  SEG_ASM(STA_X|STA_R, 0, 0xffffffff)\n  SEG_ASM(STA_W, 0, 0xffffffff)\n\n\ngdtdesc:\n  .word   (gdtdesc - gdt - 1)\n  .long   gdt\n\n"
  },
  {
    "path": "exec.c",
    "content": "#include \"types.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"defs.h\"\n#include \"x86.h\"\n#include \"elf.h\"\n\nint\nexec(char *path, char **argv)\n{\n  char *s, *last;\n  int i, off;\n  uint argc, sz, sp, ustack[3+MAXARG+1];\n  struct elfhdr elf;\n  struct inode *ip;\n  struct proghdr ph;\n  pde_t *pgdir, *oldpgdir;\n  struct proc *curproc = myproc();\n\n  begin_op();\n\n  if((ip = namei(path)) == 0){\n    end_op();\n    cprintf(\"exec: fail\\n\");\n    return -1;\n  }\n  ilock(ip);\n  pgdir = 0;\n\n  // Check ELF header\n  if(readi(ip, (char*)&elf, 0, sizeof(elf)) != sizeof(elf))\n    goto bad;\n  if(elf.magic != ELF_MAGIC)\n    goto bad;\n\n  if((pgdir = setupkvm()) == 0)\n    goto bad;\n\n  // Load program into memory.\n  sz = 0;\n  for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){\n    if(readi(ip, (char*)&ph, off, sizeof(ph)) != sizeof(ph))\n      goto bad;\n    if(ph.type != ELF_PROG_LOAD)\n      continue;\n    if(ph.memsz < ph.filesz)\n      goto bad;\n    if(ph.vaddr + ph.memsz < ph.vaddr)\n      goto bad;\n    if((sz = allocuvm(pgdir, sz, ph.vaddr + ph.memsz)) == 0)\n      goto bad;\n    if(ph.vaddr % PGSIZE != 0)\n      goto bad;\n    if(loaduvm(pgdir, (char*)ph.vaddr, ip, ph.off, ph.filesz) < 0)\n      goto bad;\n  }\n  iunlockput(ip);\n  end_op();\n  ip = 0;\n\n  // Allocate two pages at the next page boundary.\n  // Make the first inaccessible.  Use the second as the user stack.\n  sz = PGROUNDUP(sz);\n  if((sz = allocuvm(pgdir, sz, sz + 2*PGSIZE)) == 0)\n    goto bad;\n  clearpteu(pgdir, (char*)(sz - 2*PGSIZE));\n  sp = sz;\n\n  // Push argument strings, prepare rest of stack in ustack.\n  for(argc = 0; argv[argc]; argc++) {\n    if(argc >= MAXARG)\n      goto bad;\n    sp = (sp - (strlen(argv[argc]) + 1)) & ~3;\n    if(copyout(pgdir, sp, argv[argc], strlen(argv[argc]) + 1) < 0)\n      goto bad;\n    ustack[3+argc] = sp;\n  }\n  ustack[3+argc] = 0;\n\n  ustack[0] = 0xffffffff;  // fake return PC\n  ustack[1] = argc;\n  ustack[2] = sp - (argc+1)*4;  // argv pointer\n\n  sp -= (3+argc+1) * 4;\n  if(copyout(pgdir, sp, ustack, (3+argc+1)*4) < 0)\n    goto bad;\n\n  // Save program name for debugging.\n  for(last=s=path; *s; s++)\n    if(*s == '/')\n      last = s+1;\n  safestrcpy(curproc->name, last, sizeof(curproc->name));\n\n  // Commit to the user image.\n  oldpgdir = curproc->pgdir;\n  curproc->pgdir = pgdir;\n  curproc->sz = sz;\n  curproc->tf->eip = elf.entry;  // main\n  curproc->tf->esp = sp;\n  switchuvm(curproc);\n  freevm(oldpgdir);\n  return 0;\n\n bad:\n  if(pgdir)\n    freevm(pgdir);\n  if(ip){\n    iunlockput(ip);\n    end_op();\n  }\n  return -1;\n}\n"
  },
  {
    "path": "fcntl.h",
    "content": "#define O_RDONLY  0x000\n#define O_WRONLY  0x001\n#define O_RDWR    0x002\n#define O_CREATE  0x200\n"
  },
  {
    "path": "file.c",
    "content": "//\n// File descriptors\n//\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"fs.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"file.h\"\n\nstruct devsw devsw[NDEV];\nstruct {\n  struct spinlock lock;\n  struct file file[NFILE];\n} ftable;\n\nvoid\nfileinit(void)\n{\n  initlock(&ftable.lock, \"ftable\");\n}\n\n// Allocate a file structure.\nstruct file*\nfilealloc(void)\n{\n  struct file *f;\n\n  acquire(&ftable.lock);\n  for(f = ftable.file; f < ftable.file + NFILE; f++){\n    if(f->ref == 0){\n      f->ref = 1;\n      release(&ftable.lock);\n      return f;\n    }\n  }\n  release(&ftable.lock);\n  return 0;\n}\n\n// Increment ref count for file f.\nstruct file*\nfiledup(struct file *f)\n{\n  acquire(&ftable.lock);\n  if(f->ref < 1)\n    panic(\"filedup\");\n  f->ref++;\n  release(&ftable.lock);\n  return f;\n}\n\n// Close file f.  (Decrement ref count, close when reaches 0.)\nvoid\nfileclose(struct file *f)\n{\n  struct file ff;\n\n  acquire(&ftable.lock);\n  if(f->ref < 1)\n    panic(\"fileclose\");\n  if(--f->ref > 0){\n    release(&ftable.lock);\n    return;\n  }\n  ff = *f;\n  f->ref = 0;\n  f->type = FD_NONE;\n  release(&ftable.lock);\n\n  if(ff.type == FD_PIPE)\n    pipeclose(ff.pipe, ff.writable);\n  else if(ff.type == FD_INODE){\n    begin_op();\n    iput(ff.ip);\n    end_op();\n  }\n}\n\n// Get metadata about file f.\nint\nfilestat(struct file *f, struct stat *st)\n{\n  if(f->type == FD_INODE){\n    ilock(f->ip);\n    stati(f->ip, st);\n    iunlock(f->ip);\n    return 0;\n  }\n  return -1;\n}\n\n// Read from file f.\nint\nfileread(struct file *f, char *addr, int n)\n{\n  int r;\n\n  if(f->readable == 0)\n    return -1;\n  if(f->type == FD_PIPE)\n    return piperead(f->pipe, addr, n);\n  if(f->type == FD_INODE){\n    ilock(f->ip);\n    if((r = readi(f->ip, addr, f->off, n)) > 0)\n      f->off += r;\n    iunlock(f->ip);\n    return r;\n  }\n  panic(\"fileread\");\n}\n\n//PAGEBREAK!\n// Write to file f.\nint\nfilewrite(struct file *f, char *addr, int n)\n{\n  int r;\n\n  if(f->writable == 0)\n    return -1;\n  if(f->type == FD_PIPE)\n    return pipewrite(f->pipe, addr, n);\n  if(f->type == FD_INODE){\n    // write a few blocks at a time to avoid exceeding\n    // the maximum log transaction size, including\n    // i-node, indirect block, allocation blocks,\n    // and 2 blocks of slop for non-aligned writes.\n    // this really belongs lower down, since writei()\n    // might be writing a device like the console.\n    int max = ((MAXOPBLOCKS-1-1-2) / 2) * 512;\n    int i = 0;\n    while(i < n){\n      int n1 = n - i;\n      if(n1 > max)\n        n1 = max;\n\n      begin_op();\n      ilock(f->ip);\n      if ((r = writei(f->ip, addr + i, f->off, n1)) > 0)\n        f->off += r;\n      iunlock(f->ip);\n      end_op();\n\n      if(r < 0)\n        break;\n      if(r != n1)\n        panic(\"short filewrite\");\n      i += r;\n    }\n    return i == n ? n : -1;\n  }\n  panic(\"filewrite\");\n}\n\n"
  },
  {
    "path": "file.h",
    "content": "struct file {\n  enum { FD_NONE, FD_PIPE, FD_INODE } type;\n  int ref; // reference count\n  char readable;\n  char writable;\n  struct pipe *pipe;\n  struct inode *ip;\n  uint off;\n};\n\n\n// in-memory copy of an inode\nstruct inode {\n  uint dev;           // Device number\n  uint inum;          // Inode number\n  int ref;            // Reference count\n  struct sleeplock lock; // protects everything below here\n  int valid;          // inode has been read from disk?\n\n  short type;         // copy of disk inode\n  short major;\n  short minor;\n  short nlink;\n  uint size;\n  uint addrs[NDIRECT+1];\n};\n\n// table mapping major device number to\n// device functions\nstruct devsw {\n  int (*read)(struct inode*, char*, int);\n  int (*write)(struct inode*, char*, int);\n};\n\nextern struct devsw devsw[];\n\n#define CONSOLE 1\n"
  },
  {
    "path": "forktest.c",
    "content": "// Test that fork fails gracefully.\n// Tiny executable so that the limit can be filling the proc table.\n\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\n#define N  1000\n\nvoid\nprintf(int fd, const char *s, ...)\n{\n  write(fd, s, strlen(s));\n}\n\nvoid\nforktest(void)\n{\n  int n, pid;\n\n  printf(1, \"fork test\\n\");\n\n  for(n=0; n<N; n++){\n    pid = fork();\n    if(pid < 0)\n      break;\n    if(pid == 0)\n      exit();\n  }\n\n  if(n == N){\n    printf(1, \"fork claimed to work N times!\\n\", N);\n    exit();\n  }\n\n  for(; n > 0; n--){\n    if(wait() < 0){\n      printf(1, \"wait stopped early\\n\");\n      exit();\n    }\n  }\n\n  if(wait() != -1){\n    printf(1, \"wait got too many\\n\");\n    exit();\n  }\n\n  printf(1, \"fork test OK\\n\");\n}\n\nint\nmain(void)\n{\n  forktest();\n  exit();\n}\n"
  },
  {
    "path": "fs.c",
    "content": "// File system implementation.  Five layers:\n//   + Blocks: allocator for raw disk blocks.\n//   + Log: crash recovery for multi-step updates.\n//   + Files: inode allocator, reading, writing, metadata.\n//   + Directories: inode with special contents (list of other inodes!)\n//   + Names: paths like /usr/rtm/xv6/fs.c for convenient naming.\n//\n// This file contains the low-level file system manipulation\n// routines.  The (higher-level) system call implementations\n// are in sysfile.c.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"stat.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"buf.h\"\n#include \"file.h\"\n\n#define min(a, b) ((a) < (b) ? (a) : (b))\nstatic void itrunc(struct inode*);\n// there should be one superblock per disk device, but we run with\n// only one device\nstruct superblock sb; \n\n// Read the super block.\nvoid\nreadsb(int dev, struct superblock *sb)\n{\n  struct buf *bp;\n\n  bp = bread(dev, 1);\n  memmove(sb, bp->data, sizeof(*sb));\n  brelse(bp);\n}\n\n// Zero a block.\nstatic void\nbzero(int dev, int bno)\n{\n  struct buf *bp;\n\n  bp = bread(dev, bno);\n  memset(bp->data, 0, BSIZE);\n  log_write(bp);\n  brelse(bp);\n}\n\n// Blocks.\n\n// Allocate a zeroed disk block.\nstatic uint\nballoc(uint dev)\n{\n  int b, bi, m;\n  struct buf *bp;\n\n  bp = 0;\n  for(b = 0; b < sb.size; b += BPB){\n    bp = bread(dev, BBLOCK(b, sb));\n    for(bi = 0; bi < BPB && b + bi < sb.size; bi++){\n      m = 1 << (bi % 8);\n      if((bp->data[bi/8] & m) == 0){  // Is block free?\n        bp->data[bi/8] |= m;  // Mark block in use.\n        log_write(bp);\n        brelse(bp);\n        bzero(dev, b + bi);\n        return b + bi;\n      }\n    }\n    brelse(bp);\n  }\n  panic(\"balloc: out of blocks\");\n}\n\n// Free a disk block.\nstatic void\nbfree(int dev, uint b)\n{\n  struct buf *bp;\n  int bi, m;\n\n  bp = bread(dev, BBLOCK(b, sb));\n  bi = b % BPB;\n  m = 1 << (bi % 8);\n  if((bp->data[bi/8] & m) == 0)\n    panic(\"freeing free block\");\n  bp->data[bi/8] &= ~m;\n  log_write(bp);\n  brelse(bp);\n}\n\n// Inodes.\n//\n// An inode describes a single unnamed file.\n// The inode disk structure holds metadata: the file's type,\n// its size, the number of links referring to it, and the\n// list of blocks holding the file's content.\n//\n// The inodes are laid out sequentially on disk at\n// sb.startinode. Each inode has a number, indicating its\n// position on the disk.\n//\n// The kernel keeps a cache of in-use inodes in memory\n// to provide a place for synchronizing access\n// to inodes used by multiple processes. The cached\n// inodes include book-keeping information that is\n// not stored on disk: ip->ref and ip->valid.\n//\n// An inode and its in-memory representation go through a\n// sequence of states before they can be used by the\n// rest of the file system code.\n//\n// * Allocation: an inode is allocated if its type (on disk)\n//   is non-zero. ialloc() allocates, and iput() frees if\n//   the reference and link counts have fallen to zero.\n//\n// * Referencing in cache: an entry in the inode cache\n//   is free if ip->ref is zero. Otherwise ip->ref tracks\n//   the number of in-memory pointers to the entry (open\n//   files and current directories). iget() finds or\n//   creates a cache entry and increments its ref; iput()\n//   decrements ref.\n//\n// * Valid: the information (type, size, &c) in an inode\n//   cache entry is only correct when ip->valid is 1.\n//   ilock() reads the inode from\n//   the disk and sets ip->valid, while iput() clears\n//   ip->valid if ip->ref has fallen to zero.\n//\n// * Locked: file system code may only examine and modify\n//   the information in an inode and its content if it\n//   has first locked the inode.\n//\n// Thus a typical sequence is:\n//   ip = iget(dev, inum)\n//   ilock(ip)\n//   ... examine and modify ip->xxx ...\n//   iunlock(ip)\n//   iput(ip)\n//\n// ilock() is separate from iget() so that system calls can\n// get a long-term reference to an inode (as for an open file)\n// and only lock it for short periods (e.g., in read()).\n// The separation also helps avoid deadlock and races during\n// pathname lookup. iget() increments ip->ref so that the inode\n// stays cached and pointers to it remain valid.\n//\n// Many internal file system functions expect the caller to\n// have locked the inodes involved; this lets callers create\n// multi-step atomic operations.\n//\n// The icache.lock spin-lock protects the allocation of icache\n// entries. Since ip->ref indicates whether an entry is free,\n// and ip->dev and ip->inum indicate which i-node an entry\n// holds, one must hold icache.lock while using any of those fields.\n//\n// An ip->lock sleep-lock protects all ip-> fields other than ref,\n// dev, and inum.  One must hold ip->lock in order to\n// read or write that inode's ip->valid, ip->size, ip->type, &c.\n\nstruct {\n  struct spinlock lock;\n  struct inode inode[NINODE];\n} icache;\n\nvoid\niinit(int dev)\n{\n  int i = 0;\n  \n  initlock(&icache.lock, \"icache\");\n  for(i = 0; i < NINODE; i++) {\n    initsleeplock(&icache.inode[i].lock, \"inode\");\n  }\n\n  readsb(dev, &sb);\n  cprintf(\"sb: size %d nblocks %d ninodes %d nlog %d logstart %d\\\n inodestart %d bmap start %d\\n\", sb.size, sb.nblocks,\n          sb.ninodes, sb.nlog, sb.logstart, sb.inodestart,\n          sb.bmapstart);\n}\n\nstatic struct inode* iget(uint dev, uint inum);\n\n//PAGEBREAK!\n// Allocate an inode on device dev.\n// Mark it as allocated by  giving it type type.\n// Returns an unlocked but allocated and referenced inode.\nstruct inode*\nialloc(uint dev, short type)\n{\n  int inum;\n  struct buf *bp;\n  struct dinode *dip;\n\n  for(inum = 1; inum < sb.ninodes; inum++){\n    bp = bread(dev, IBLOCK(inum, sb));\n    dip = (struct dinode*)bp->data + inum%IPB;\n    if(dip->type == 0){  // a free inode\n      memset(dip, 0, sizeof(*dip));\n      dip->type = type;\n      log_write(bp);   // mark it allocated on the disk\n      brelse(bp);\n      return iget(dev, inum);\n    }\n    brelse(bp);\n  }\n  panic(\"ialloc: no inodes\");\n}\n\n// Copy a modified in-memory inode to disk.\n// Must be called after every change to an ip->xxx field\n// that lives on disk, since i-node cache is write-through.\n// Caller must hold ip->lock.\nvoid\niupdate(struct inode *ip)\n{\n  struct buf *bp;\n  struct dinode *dip;\n\n  bp = bread(ip->dev, IBLOCK(ip->inum, sb));\n  dip = (struct dinode*)bp->data + ip->inum%IPB;\n  dip->type = ip->type;\n  dip->major = ip->major;\n  dip->minor = ip->minor;\n  dip->nlink = ip->nlink;\n  dip->size = ip->size;\n  memmove(dip->addrs, ip->addrs, sizeof(ip->addrs));\n  log_write(bp);\n  brelse(bp);\n}\n\n// Find the inode with number inum on device dev\n// and return the in-memory copy. Does not lock\n// the inode and does not read it from disk.\nstatic struct inode*\niget(uint dev, uint inum)\n{\n  struct inode *ip, *empty;\n\n  acquire(&icache.lock);\n\n  // Is the inode already cached?\n  empty = 0;\n  for(ip = &icache.inode[0]; ip < &icache.inode[NINODE]; ip++){\n    if(ip->ref > 0 && ip->dev == dev && ip->inum == inum){\n      ip->ref++;\n      release(&icache.lock);\n      return ip;\n    }\n    if(empty == 0 && ip->ref == 0)    // Remember empty slot.\n      empty = ip;\n  }\n\n  // Recycle an inode cache entry.\n  if(empty == 0)\n    panic(\"iget: no inodes\");\n\n  ip = empty;\n  ip->dev = dev;\n  ip->inum = inum;\n  ip->ref = 1;\n  ip->valid = 0;\n  release(&icache.lock);\n\n  return ip;\n}\n\n// Increment reference count for ip.\n// Returns ip to enable ip = idup(ip1) idiom.\nstruct inode*\nidup(struct inode *ip)\n{\n  acquire(&icache.lock);\n  ip->ref++;\n  release(&icache.lock);\n  return ip;\n}\n\n// Lock the given inode.\n// Reads the inode from disk if necessary.\nvoid\nilock(struct inode *ip)\n{\n  struct buf *bp;\n  struct dinode *dip;\n\n  if(ip == 0 || ip->ref < 1)\n    panic(\"ilock\");\n\n  acquiresleep(&ip->lock);\n\n  if(ip->valid == 0){\n    bp = bread(ip->dev, IBLOCK(ip->inum, sb));\n    dip = (struct dinode*)bp->data + ip->inum%IPB;\n    ip->type = dip->type;\n    ip->major = dip->major;\n    ip->minor = dip->minor;\n    ip->nlink = dip->nlink;\n    ip->size = dip->size;\n    memmove(ip->addrs, dip->addrs, sizeof(ip->addrs));\n    brelse(bp);\n    ip->valid = 1;\n    if(ip->type == 0)\n      panic(\"ilock: no type\");\n  }\n}\n\n// Unlock the given inode.\nvoid\niunlock(struct inode *ip)\n{\n  if(ip == 0 || !holdingsleep(&ip->lock) || ip->ref < 1)\n    panic(\"iunlock\");\n\n  releasesleep(&ip->lock);\n}\n\n// Drop a reference to an in-memory inode.\n// If that was the last reference, the inode cache entry can\n// be recycled.\n// If that was the last reference and the inode has no links\n// to it, free the inode (and its content) on disk.\n// All calls to iput() must be inside a transaction in\n// case it has to free the inode.\nvoid\niput(struct inode *ip)\n{\n  acquiresleep(&ip->lock);\n  if(ip->valid && ip->nlink == 0){\n    acquire(&icache.lock);\n    int r = ip->ref;\n    release(&icache.lock);\n    if(r == 1){\n      // inode has no links and no other references: truncate and free.\n      itrunc(ip);\n      ip->type = 0;\n      iupdate(ip);\n      ip->valid = 0;\n    }\n  }\n  releasesleep(&ip->lock);\n\n  acquire(&icache.lock);\n  ip->ref--;\n  release(&icache.lock);\n}\n\n// Common idiom: unlock, then put.\nvoid\niunlockput(struct inode *ip)\n{\n  iunlock(ip);\n  iput(ip);\n}\n\n//PAGEBREAK!\n// Inode content\n//\n// The content (data) associated with each inode is stored\n// in blocks on the disk. The first NDIRECT block numbers\n// are listed in ip->addrs[].  The next NINDIRECT blocks are\n// listed in block ip->addrs[NDIRECT].\n\n// Return the disk block address of the nth block in inode ip.\n// If there is no such block, bmap allocates one.\nstatic uint\nbmap(struct inode *ip, uint bn)\n{\n  uint addr, *a;\n  struct buf *bp;\n\n  if(bn < NDIRECT){\n    if((addr = ip->addrs[bn]) == 0)\n      ip->addrs[bn] = addr = balloc(ip->dev);\n    return addr;\n  }\n  bn -= NDIRECT;\n\n  if(bn < NINDIRECT){\n    // Load indirect block, allocating if necessary.\n    if((addr = ip->addrs[NDIRECT]) == 0)\n      ip->addrs[NDIRECT] = addr = balloc(ip->dev);\n    bp = bread(ip->dev, addr);\n    a = (uint*)bp->data;\n    if((addr = a[bn]) == 0){\n      a[bn] = addr = balloc(ip->dev);\n      log_write(bp);\n    }\n    brelse(bp);\n    return addr;\n  }\n\n  panic(\"bmap: out of range\");\n}\n\n// Truncate inode (discard contents).\n// Only called when the inode has no links\n// to it (no directory entries referring to it)\n// and has no in-memory reference to it (is\n// not an open file or current directory).\nstatic void\nitrunc(struct inode *ip)\n{\n  int i, j;\n  struct buf *bp;\n  uint *a;\n\n  for(i = 0; i < NDIRECT; i++){\n    if(ip->addrs[i]){\n      bfree(ip->dev, ip->addrs[i]);\n      ip->addrs[i] = 0;\n    }\n  }\n\n  if(ip->addrs[NDIRECT]){\n    bp = bread(ip->dev, ip->addrs[NDIRECT]);\n    a = (uint*)bp->data;\n    for(j = 0; j < NINDIRECT; j++){\n      if(a[j])\n        bfree(ip->dev, a[j]);\n    }\n    brelse(bp);\n    bfree(ip->dev, ip->addrs[NDIRECT]);\n    ip->addrs[NDIRECT] = 0;\n  }\n\n  ip->size = 0;\n  iupdate(ip);\n}\n\n// Copy stat information from inode.\n// Caller must hold ip->lock.\nvoid\nstati(struct inode *ip, struct stat *st)\n{\n  st->dev = ip->dev;\n  st->ino = ip->inum;\n  st->type = ip->type;\n  st->nlink = ip->nlink;\n  st->size = ip->size;\n}\n\n//PAGEBREAK!\n// Read data from inode.\n// Caller must hold ip->lock.\nint\nreadi(struct inode *ip, char *dst, uint off, uint n)\n{\n  uint tot, m;\n  struct buf *bp;\n\n  if(ip->type == T_DEV){\n    if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].read)\n      return -1;\n    return devsw[ip->major].read(ip, dst, n);\n  }\n\n  if(off > ip->size || off + n < off)\n    return -1;\n  if(off + n > ip->size)\n    n = ip->size - off;\n\n  for(tot=0; tot<n; tot+=m, off+=m, dst+=m){\n    bp = bread(ip->dev, bmap(ip, off/BSIZE));\n    m = min(n - tot, BSIZE - off%BSIZE);\n    memmove(dst, bp->data + off%BSIZE, m);\n    brelse(bp);\n  }\n  return n;\n}\n\n// PAGEBREAK!\n// Write data to inode.\n// Caller must hold ip->lock.\nint\nwritei(struct inode *ip, char *src, uint off, uint n)\n{\n  uint tot, m;\n  struct buf *bp;\n\n  if(ip->type == T_DEV){\n    if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].write)\n      return -1;\n    return devsw[ip->major].write(ip, src, n);\n  }\n\n  if(off > ip->size || off + n < off)\n    return -1;\n  if(off + n > MAXFILE*BSIZE)\n    return -1;\n\n  for(tot=0; tot<n; tot+=m, off+=m, src+=m){\n    bp = bread(ip->dev, bmap(ip, off/BSIZE));\n    m = min(n - tot, BSIZE - off%BSIZE);\n    memmove(bp->data + off%BSIZE, src, m);\n    log_write(bp);\n    brelse(bp);\n  }\n\n  if(n > 0 && off > ip->size){\n    ip->size = off;\n    iupdate(ip);\n  }\n  return n;\n}\n\n//PAGEBREAK!\n// Directories\n\nint\nnamecmp(const char *s, const char *t)\n{\n  return strncmp(s, t, DIRSIZ);\n}\n\n// Look for a directory entry in a directory.\n// If found, set *poff to byte offset of entry.\nstruct inode*\ndirlookup(struct inode *dp, char *name, uint *poff)\n{\n  uint off, inum;\n  struct dirent de;\n\n  if(dp->type != T_DIR)\n    panic(\"dirlookup not DIR\");\n\n  for(off = 0; off < dp->size; off += sizeof(de)){\n    if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))\n      panic(\"dirlookup read\");\n    if(de.inum == 0)\n      continue;\n    if(namecmp(name, de.name) == 0){\n      // entry matches path element\n      if(poff)\n        *poff = off;\n      inum = de.inum;\n      return iget(dp->dev, inum);\n    }\n  }\n\n  return 0;\n}\n\n// Write a new directory entry (name, inum) into the directory dp.\nint\ndirlink(struct inode *dp, char *name, uint inum)\n{\n  int off;\n  struct dirent de;\n  struct inode *ip;\n\n  // Check that name is not present.\n  if((ip = dirlookup(dp, name, 0)) != 0){\n    iput(ip);\n    return -1;\n  }\n\n  // Look for an empty dirent.\n  for(off = 0; off < dp->size; off += sizeof(de)){\n    if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))\n      panic(\"dirlink read\");\n    if(de.inum == 0)\n      break;\n  }\n\n  strncpy(de.name, name, DIRSIZ);\n  de.inum = inum;\n  if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))\n    panic(\"dirlink\");\n\n  return 0;\n}\n\n//PAGEBREAK!\n// Paths\n\n// Copy the next path element from path into name.\n// Return a pointer to the element following the copied one.\n// The returned path has no leading slashes,\n// so the caller can check *path=='\\0' to see if the name is the last one.\n// If no name to remove, return 0.\n//\n// Examples:\n//   skipelem(\"a/bb/c\", name) = \"bb/c\", setting name = \"a\"\n//   skipelem(\"///a//bb\", name) = \"bb\", setting name = \"a\"\n//   skipelem(\"a\", name) = \"\", setting name = \"a\"\n//   skipelem(\"\", name) = skipelem(\"////\", name) = 0\n//\nstatic char*\nskipelem(char *path, char *name)\n{\n  char *s;\n  int len;\n\n  while(*path == '/')\n    path++;\n  if(*path == 0)\n    return 0;\n  s = path;\n  while(*path != '/' && *path != 0)\n    path++;\n  len = path - s;\n  if(len >= DIRSIZ)\n    memmove(name, s, DIRSIZ);\n  else {\n    memmove(name, s, len);\n    name[len] = 0;\n  }\n  while(*path == '/')\n    path++;\n  return path;\n}\n\n// Look up and return the inode for a path name.\n// If parent != 0, return the inode for the parent and copy the final\n// path element into name, which must have room for DIRSIZ bytes.\n// Must be called inside a transaction since it calls iput().\nstatic struct inode*\nnamex(char *path, int nameiparent, char *name)\n{\n  struct inode *ip, *next;\n\n  if(*path == '/')\n    ip = iget(ROOTDEV, ROOTINO);\n  else\n    ip = idup(myproc()->cwd);\n\n  while((path = skipelem(path, name)) != 0){\n    ilock(ip);\n    if(ip->type != T_DIR){\n      iunlockput(ip);\n      return 0;\n    }\n    if(nameiparent && *path == '\\0'){\n      // Stop one level early.\n      iunlock(ip);\n      return ip;\n    }\n    if((next = dirlookup(ip, name, 0)) == 0){\n      iunlockput(ip);\n      return 0;\n    }\n    iunlockput(ip);\n    ip = next;\n  }\n  if(nameiparent){\n    iput(ip);\n    return 0;\n  }\n  return ip;\n}\n\nstruct inode*\nnamei(char *path)\n{\n  char name[DIRSIZ];\n  return namex(path, 0, name);\n}\n\nstruct inode*\nnameiparent(char *path, char *name)\n{\n  return namex(path, 1, name);\n}\n"
  },
  {
    "path": "fs.h",
    "content": "// On-disk file system format.\n// Both the kernel and user programs use this header file.\n\n\n#define ROOTINO 1  // root i-number\n#define BSIZE 512  // block size\n\n// Disk layout:\n// [ boot block | super block | log | inode blocks |\n//                                          free bit map | data blocks]\n//\n// mkfs computes the super block and builds an initial file system. The\n// super block describes the disk layout:\nstruct superblock {\n  uint size;         // Size of file system image (blocks)\n  uint nblocks;      // Number of data blocks\n  uint ninodes;      // Number of inodes.\n  uint nlog;         // Number of log blocks\n  uint logstart;     // Block number of first log block\n  uint inodestart;   // Block number of first inode block\n  uint bmapstart;    // Block number of first free map block\n};\n\n#define NDIRECT 12\n#define NINDIRECT (BSIZE / sizeof(uint))\n#define MAXFILE (NDIRECT + NINDIRECT)\n\n// On-disk inode structure\nstruct dinode {\n  short type;           // File type\n  short major;          // Major device number (T_DEV only)\n  short minor;          // Minor device number (T_DEV only)\n  short nlink;          // Number of links to inode in file system\n  uint size;            // Size of file (bytes)\n  uint addrs[NDIRECT+1];   // Data block addresses\n};\n\n// Inodes per block.\n#define IPB           (BSIZE / sizeof(struct dinode))\n\n// Block containing inode i\n#define IBLOCK(i, sb)     ((i) / IPB + sb.inodestart)\n\n// Bitmap bits per block\n#define BPB           (BSIZE*8)\n\n// Block of free map containing bit for block b\n#define BBLOCK(b, sb) (b/BPB + sb.bmapstart)\n\n// Directory is a file containing a sequence of dirent structures.\n#define DIRSIZ 14\n\nstruct dirent {\n  ushort inum;\n  char name[DIRSIZ];\n};\n\n"
  },
  {
    "path": "gdbutil",
    "content": "# -*- gdb-script -*-\n\n# Utility functions to pretty-print x86 segment/interrupt descriptors.\n# To load this file, run \"source gdbutil\" in gdb.\n# printdesc and printdescs are the main entry points.\n\n# IA32 2007, Volume 3A, Table 3-2\nset $STS_T16A = 0x1\nset $STS_LDT  = 0x2\nset $STS_T16B = 0x3\nset $STS_CG16 = 0x4\nset $STS_TG   = 0x5\nset $STS_IG16 = 0x6\nset $STS_TG16 = 0x7\nset $STS_T32A = 0x9\nset $STS_T32B = 0xB\nset $STS_CG32 = 0xC\nset $STS_IG32 = 0xE\nset $STS_TG32 = 0xF\n\ndefine outputsts\n  while 1\n    if $arg0 == $STS_T16A\n      echo STS_T16A\n      loop_break\n    end\n    if $arg0 == $STS_LDT\n      echo STS_LDT\\ \n      loop_break\n    end\n    if $arg0 == $STS_T16B\n      echo STS_T16B\n      loop_break\n    end\n    if $arg0 == $STS_CG16\n      echo STS_CG16\n      loop_break\n    end\n    if $arg0 == $STS_TG\n      echo STS_TG\\ \\ \n      loop_break\n    end\n    if $arg0 == $STS_IG16\n      echo STS_IG16\n      loop_break\n    end\n    if $arg0 == $STS_TG16\n      echo STS_TG16\n      loop_break\n    end\n    if $arg0 == $STS_T32A\n      echo STS_T32A\n      loop_break\n    end\n    if $arg0 == $STS_T32B\n      echo STS_T32B\n      loop_break\n    end\n    if $arg0 == $STS_CG32\n      echo STS_CG32\n      loop_break\n    end\n    if $arg0 == $STS_IG32\n      echo STS_IG32\n      loop_break\n    end\n    if $arg0 == $STS_TG32\n      echo STS_TG32\n      loop_break\n    end\n    echo Reserved\n    loop_break\n  end\nend  \n\n# IA32 2007, Volume 3A, Table 3-1\nset $STA_X = 0x8\nset $STA_E = 0x4\nset $STA_C = 0x4\nset $STA_W = 0x2\nset $STA_R = 0x2\nset $STA_A = 0x1\n\ndefine outputsta\n  if $arg0 & $STA_X\n    # Code segment\n    echo code\n    if $arg0 & $STA_C\n      echo |STA_C\n    end\n    if $arg0 & $STA_R\n      echo |STA_R\n    end\n  else\n    # Data segment\n    echo data\n    if $arg0 & $STA_E\n      echo |STA_E\n    end\n    if $arg0 & $STA_W\n      echo |STA_W\n    end\n  end\n  if $arg0 & $STA_A\n    echo |STA_A\n  else\n    printf \"      \"\n  end\nend\n\n# xv6-specific\nset $SEG_KCODE = 1\nset $SEG_KDATA = 2\nset $SEG_KCPU  = 3\nset $SEG_UCODE = 4\nset $SEG_UDATA = 5\nset $SEG_TSS   = 6\n\ndefine outputcs\n  if ($arg0 & 4) == 0\n    if $arg0 >> 3 == $SEG_KCODE\n      printf \"SEG_KCODE<<3\"\n    end\n    if $arg0 >> 3 == $SEG_KDATA\n      printf \"SEG_KDATA<<3\"\n    end\n    if $arg0 >> 3 == $SEG_KCPU\n      printf \"SEG_KCPU<<3\"\n    end\n    if $arg0 >> 3 == $SEG_UCODE\n      printf \"SEG_UCODE<<3\"\n    end\n    if $arg0 >> 3 == $SEG_UDATA\n      printf \"SEG_UDATA<<3\"\n    end\n    if $arg0 >> 3 == $SEG_TSS\n      printf \"SEG_TSS<<3\"\n    end\n    if ($arg0 >> 3 < 1) + ($arg0 >> 3 > 6)\n      printf \"GDT[%d]\", $arg0 >> 3\n    end\n  else\n    printf \"LDT[%d]\", $arg0 >> 3\n  end\n  if ($arg0 & 3) > 0\n    printf \"|\"\n    outputdpl ($arg0&3)\n  end\nend\n\ndefine outputdpl\n  if $arg0 == 0\n    printf \"DPL_KERN\"\n  else\n    if $arg0 == 3\n      printf \"DPL_USER\"\n    else\n      printf \"DPL%d\", $arg0\n    end\n  end\nend\n\ndefine printdesc\n  if $argc != 1\n    echo Usage: printdesc expr\n  else\n    _printdesc ((uint*)&($arg0))[0] ((uint*)&($arg0))[1]\n    printf \"\\n\"\n  end\nend\n\ndocument printdesc\nPrint an x86 segment or gate descriptor.\nprintdesc EXPR\nEXPR must evaluate to a descriptor value.  It can be of any C type.\nend\n\ndefine _printdesc\n  _printdesc1 $arg0 $arg1 ($arg1>>15&1) ($arg1>>13&3) ($arg1>>12&1) ($arg1>>8&15)\nend\n\ndefine _printdesc1\n  # 2:P 3:DPL 4:S 5:Type\n  if $arg2 == 0\n    printf \"P = 0 (Not present)\"\n  else\n    printf \"type = \"\n    if $arg4 == 0\n      # System segment\n      outputsts $arg5\n      printf \" (0x%x)    \", $arg5\n      _printsysdesc $arg0 $arg1 $arg5\n    else\n      # Code/data segment\n      outputsta $arg5\n      printf \"  \"\n      _printsegdesc $arg0 $arg1\n    end\n\n    printf \"  DPL = \"\n    outputdpl $arg3\n    printf \" (%d)\", $arg3\n  end\nend\n\ndefine _printsysdesc\n  # 2:Type\n  # GDB's || is buggy\n  if ($arg2 == $STS_TG) + (($arg2&7) == $STS_IG16) + (($arg2&7) == $STS_TG16)\n    # Gate descriptor\n    _printgate $arg2 ($arg0>>16) ($arg0&0xFFFF) ($arg1>>16)\n  else\n    # System segment descriptor\n    _printsegdesc $arg0 $arg1\n  end\nend\n\ndefine _printgate\n  # IA32 2007, Voume 3A, Figure 5-2\n  # 0:Type 1:CS 2:Offset 15..0 3:Offset 31..16\n  printf \"CS = \"\n  outputcs $arg1\n  printf \" (%d)\", $arg1\n\n  if (($arg0&7) == $STS_IG16) + (($arg0&7) == $STS_TG16)\n    printf \"  Offset = \"\n    output/a $arg3 << 16 | $arg2\n  end\nend\n\ndefine _printsegdesc\n  # IA32 20007, Volume 3A, Figure 3-8 and Figure 4-1\n  _printsegdesc1 ($arg0>>16) ($arg1&0xFF) ($arg1>>24) ($arg0&0xFFFF) ($arg1>>16&15) ($arg1>>23&1)\n  if ($arg1>>12&1) == 1\n    printf \"  AVL = %d\", $arg1>>20&1\n    if ($arg1>>11&1) == 0\n      # Data segment\n      if ($arg1>>22&1) == 0\n        printf \"  B = small (0) \"\n      else\n        printf \"  B = big (1)   \"\n      end\n    else\n      # Code segment\n      printf \"  D = \"\n      if ($arg1>>22&1) == 0\n        printf \"16-bit (0)\"\n      else\n        printf \"32-bit (1)\"\n      end\n    end\n  end\nend\n\ndefine _printsegdesc1\n  # 0:Base 0..15  1:Base 16..23  2:Base 24..32  3:Limit 0..15  4:Limit 16..19  5:G\n  printf \"base = 0x%08x\", $arg0 | ($arg1<<16) | ($arg2<<24)\n  printf \"  limit = 0x\"\n  if $arg5 == 0\n    printf \"%08x\", $arg3 | ($arg4<<16)\n  else\n    printf \"%08x\", (($arg3 | ($arg4<<16)) << 12) | 0xFFF\n  end\nend\n\ndefine printdescs\n  if $argc < 1 || $argc > 2\n    echo Usage: printdescs expr [count]\n  else\n    if $argc == 1\n      _printdescs ($arg0) (sizeof($arg0)/sizeof(($arg0)[0]))\n    else\n      _printdescs ($arg0) ($arg1)\n    end\n  end\nend\n\ndocument printdescs\nPrint an array of x86 segment or gate descriptors.\nprintdescs EXPR [COUNT]\nEXPR must evaluate to an array of descriptors.\nend\n\ndefine _printdescs\n  set $i = 0\n  while $i < $arg1\n    printf \"[%d] \", $i\n    printdesc $arg0[$i]\n    set $i = $i + 1\n  end\nend\n"
  },
  {
    "path": "grep.c",
    "content": "// Simple grep.  Only supports ^ . * $ operators.\n\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nchar buf[1024];\nint match(char*, char*);\n\nvoid\ngrep(char *pattern, int fd)\n{\n  int n, m;\n  char *p, *q;\n\n  m = 0;\n  while((n = read(fd, buf+m, sizeof(buf)-m-1)) > 0){\n    m += n;\n    buf[m] = '\\0';\n    p = buf;\n    while((q = strchr(p, '\\n')) != 0){\n      *q = 0;\n      if(match(pattern, p)){\n        *q = '\\n';\n        write(1, p, q+1 - p);\n      }\n      p = q+1;\n    }\n    if(p == buf)\n      m = 0;\n    if(m > 0){\n      m -= p - buf;\n      memmove(buf, p, m);\n    }\n  }\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int fd, i;\n  char *pattern;\n\n  if(argc <= 1){\n    printf(2, \"usage: grep pattern [file ...]\\n\");\n    exit();\n  }\n  pattern = argv[1];\n\n  if(argc <= 2){\n    grep(pattern, 0);\n    exit();\n  }\n\n  for(i = 2; i < argc; i++){\n    if((fd = open(argv[i], 0)) < 0){\n      printf(1, \"grep: cannot open %s\\n\", argv[i]);\n      exit();\n    }\n    grep(pattern, fd);\n    close(fd);\n  }\n  exit();\n}\n\n// Regexp matcher from Kernighan & Pike,\n// The Practice of Programming, Chapter 9.\n\nint matchhere(char*, char*);\nint matchstar(int, char*, char*);\n\nint\nmatch(char *re, char *text)\n{\n  if(re[0] == '^')\n    return matchhere(re+1, text);\n  do{  // must look at empty string\n    if(matchhere(re, text))\n      return 1;\n  }while(*text++ != '\\0');\n  return 0;\n}\n\n// matchhere: search for re at beginning of text\nint matchhere(char *re, char *text)\n{\n  if(re[0] == '\\0')\n    return 1;\n  if(re[1] == '*')\n    return matchstar(re[0], re+2, text);\n  if(re[0] == '$' && re[1] == '\\0')\n    return *text == '\\0';\n  if(*text!='\\0' && (re[0]=='.' || re[0]==*text))\n    return matchhere(re+1, text+1);\n  return 0;\n}\n\n// matchstar: search for c*re at beginning of text\nint matchstar(int c, char *re, char *text)\n{\n  do{  // a * matches zero or more instances\n    if(matchhere(re, text))\n      return 1;\n  }while(*text!='\\0' && (*text++==c || c=='.'));\n  return 0;\n}\n\n"
  },
  {
    "path": "ide.c",
    "content": "// Simple PIO-based (non-DMA) IDE driver code.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n#include \"traps.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"buf.h\"\n\n#define SECTOR_SIZE   512\n#define IDE_BSY       0x80\n#define IDE_DRDY      0x40\n#define IDE_DF        0x20\n#define IDE_ERR       0x01\n\n#define IDE_CMD_READ  0x20\n#define IDE_CMD_WRITE 0x30\n#define IDE_CMD_RDMUL 0xc4\n#define IDE_CMD_WRMUL 0xc5\n\n// idequeue points to the buf now being read/written to the disk.\n// idequeue->qnext points to the next buf to be processed.\n// You must hold idelock while manipulating queue.\n\nstatic struct spinlock idelock;\nstatic struct buf *idequeue;\n\nstatic int havedisk1;\nstatic void idestart(struct buf*);\n\n// Wait for IDE disk to become ready.\nstatic int\nidewait(int checkerr)\n{\n  int r;\n\n  while(((r = inb(0x1f7)) & (IDE_BSY|IDE_DRDY)) != IDE_DRDY)\n    ;\n  if(checkerr && (r & (IDE_DF|IDE_ERR)) != 0)\n    return -1;\n  return 0;\n}\n\nvoid\nideinit(void)\n{\n  int i;\n\n  initlock(&idelock, \"ide\");\n  ioapicenable(IRQ_IDE, ncpu - 1);\n  idewait(0);\n\n  // Check if disk 1 is present\n  outb(0x1f6, 0xe0 | (1<<4));\n  for(i=0; i<1000; i++){\n    if(inb(0x1f7) != 0){\n      havedisk1 = 1;\n      break;\n    }\n  }\n\n  // Switch back to disk 0.\n  outb(0x1f6, 0xe0 | (0<<4));\n}\n\n// Start the request for b.  Caller must hold idelock.\nstatic void\nidestart(struct buf *b)\n{\n  if(b == 0)\n    panic(\"idestart\");\n  if(b->blockno >= FSSIZE)\n    panic(\"incorrect blockno\");\n  int sector_per_block =  BSIZE/SECTOR_SIZE;\n  int sector = b->blockno * sector_per_block;\n  int read_cmd = (sector_per_block == 1) ? IDE_CMD_READ :  IDE_CMD_RDMUL;\n  int write_cmd = (sector_per_block == 1) ? IDE_CMD_WRITE : IDE_CMD_WRMUL;\n\n  if (sector_per_block > 7) panic(\"idestart\");\n\n  idewait(0);\n  outb(0x3f6, 0);  // generate interrupt\n  outb(0x1f2, sector_per_block);  // number of sectors\n  outb(0x1f3, sector & 0xff);\n  outb(0x1f4, (sector >> 8) & 0xff);\n  outb(0x1f5, (sector >> 16) & 0xff);\n  outb(0x1f6, 0xe0 | ((b->dev&1)<<4) | ((sector>>24)&0x0f));\n  if(b->flags & B_DIRTY){\n    outb(0x1f7, write_cmd);\n    outsl(0x1f0, b->data, BSIZE/4);\n  } else {\n    outb(0x1f7, read_cmd);\n  }\n}\n\n// Interrupt handler.\nvoid\nideintr(void)\n{\n  struct buf *b;\n\n  // First queued buffer is the active request.\n  acquire(&idelock);\n\n  if((b = idequeue) == 0){\n    release(&idelock);\n    return;\n  }\n  idequeue = b->qnext;\n\n  // Read data if needed.\n  if(!(b->flags & B_DIRTY) && idewait(1) >= 0)\n    insl(0x1f0, b->data, BSIZE/4);\n\n  // Wake process waiting for this buf.\n  b->flags |= B_VALID;\n  b->flags &= ~B_DIRTY;\n  wakeup(b);\n\n  // Start disk on next buf in queue.\n  if(idequeue != 0)\n    idestart(idequeue);\n\n  release(&idelock);\n}\n\n//PAGEBREAK!\n// Sync buf with disk.\n// If B_DIRTY is set, write buf to disk, clear B_DIRTY, set B_VALID.\n// Else if B_VALID is not set, read buf from disk, set B_VALID.\nvoid\niderw(struct buf *b)\n{\n  struct buf **pp;\n\n  if(!holdingsleep(&b->lock))\n    panic(\"iderw: buf not locked\");\n  if((b->flags & (B_VALID|B_DIRTY)) == B_VALID)\n    panic(\"iderw: nothing to do\");\n  if(b->dev != 0 && !havedisk1)\n    panic(\"iderw: ide disk 1 not present\");\n\n  acquire(&idelock);  //DOC:acquire-lock\n\n  // Append b to idequeue.\n  b->qnext = 0;\n  for(pp=&idequeue; *pp; pp=&(*pp)->qnext)  //DOC:insert-queue\n    ;\n  *pp = b;\n\n  // Start disk if necessary.\n  if(idequeue == b)\n    idestart(b);\n\n  // Wait for request to finish.\n  while((b->flags & (B_VALID|B_DIRTY)) != B_VALID){\n    sleep(b, &idelock);\n  }\n\n\n  release(&idelock);\n}\n"
  },
  {
    "path": "init.c",
    "content": "// init: The initial user-level program\n\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"fcntl.h\"\n\nchar *argv[] = { \"sh\", 0 };\n\nint\nmain(void)\n{\n  int pid, wpid;\n\n  if(open(\"console\", O_RDWR) < 0){\n    mknod(\"console\", 1, 1);\n    open(\"console\", O_RDWR);\n  }\n  dup(0);  // stdout\n  dup(0);  // stderr\n\n  for(;;){\n    printf(1, \"init: starting sh\\n\");\n    pid = fork();\n    if(pid < 0){\n      printf(1, \"init: fork failed\\n\");\n      exit();\n    }\n    if(pid == 0){\n      exec(\"sh\", argv);\n      printf(1, \"init: exec sh failed\\n\");\n      exit();\n    }\n    while((wpid=wait()) >= 0 && wpid != pid)\n      printf(1, \"zombie!\\n\");\n  }\n}\n"
  },
  {
    "path": "initcode.S",
    "content": "# Initial process execs /init.\n# This code runs in user space.\n\n#include \"syscall.h\"\n#include \"traps.h\"\n\n\n# exec(init, argv)\n.globl start\nstart:\n  pushl $argv\n  pushl $init\n  pushl $0  // where caller pc would be\n  movl $SYS_exec, %eax\n  int $T_SYSCALL\n\n# for(;;) exit();\nexit:\n  movl $SYS_exit, %eax\n  int $T_SYSCALL\n  jmp exit\n\n# char init[] = \"/init\\0\";\ninit:\n  .string \"/init\\0\"\n\n# char *argv[] = { init, 0 };\n.p2align 2\nargv:\n  .long init\n  .long 0\n\n"
  },
  {
    "path": "ioapic.c",
    "content": "// The I/O APIC manages hardware interrupts for an SMP system.\n// http://www.intel.com/design/chipsets/datashts/29056601.pdf\n// See also picirq.c.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"traps.h\"\n\n#define IOAPIC  0xFEC00000   // Default physical address of IO APIC\n\n#define REG_ID     0x00  // Register index: ID\n#define REG_VER    0x01  // Register index: version\n#define REG_TABLE  0x10  // Redirection table base\n\n// The redirection table starts at REG_TABLE and uses\n// two registers to configure each interrupt.\n// The first (low) register in a pair contains configuration bits.\n// The second (high) register contains a bitmask telling which\n// CPUs can serve that interrupt.\n#define INT_DISABLED   0x00010000  // Interrupt disabled\n#define INT_LEVEL      0x00008000  // Level-triggered (vs edge-)\n#define INT_ACTIVELOW  0x00002000  // Active low (vs high)\n#define INT_LOGICAL    0x00000800  // Destination is CPU id (vs APIC ID)\n\nvolatile struct ioapic *ioapic;\n\n// IO APIC MMIO structure: write reg, then read or write data.\nstruct ioapic {\n  uint reg;\n  uint pad[3];\n  uint data;\n};\n\nstatic uint\nioapicread(int reg)\n{\n  ioapic->reg = reg;\n  return ioapic->data;\n}\n\nstatic void\nioapicwrite(int reg, uint data)\n{\n  ioapic->reg = reg;\n  ioapic->data = data;\n}\n\nvoid\nioapicinit(void)\n{\n  int i, id, maxintr;\n\n  ioapic = (volatile struct ioapic*)IOAPIC;\n  maxintr = (ioapicread(REG_VER) >> 16) & 0xFF;\n  id = ioapicread(REG_ID) >> 24;\n  if(id != ioapicid)\n    cprintf(\"ioapicinit: id isn't equal to ioapicid; not a MP\\n\");\n\n  // Mark all interrupts edge-triggered, active high, disabled,\n  // and not routed to any CPUs.\n  for(i = 0; i <= maxintr; i++){\n    ioapicwrite(REG_TABLE+2*i, INT_DISABLED | (T_IRQ0 + i));\n    ioapicwrite(REG_TABLE+2*i+1, 0);\n  }\n}\n\nvoid\nioapicenable(int irq, int cpunum)\n{\n  // Mark interrupt edge-triggered, active high,\n  // enabled, and routed to the given cpunum,\n  // which happens to be that cpu's APIC ID.\n  ioapicwrite(REG_TABLE+2*irq, T_IRQ0 + irq);\n  ioapicwrite(REG_TABLE+2*irq+1, cpunum << 24);\n}\n"
  },
  {
    "path": "kalloc.c",
    "content": "// Physical memory allocator, intended to allocate\n// memory for user processes, kernel stacks, page table pages,\n// and pipe buffers. Allocates 4096-byte pages.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"spinlock.h\"\n\nvoid freerange(void *vstart, void *vend);\nextern char end[]; // first address after kernel loaded from ELF file\n                   // defined by the kernel linker script in kernel.ld\n\nstruct run {\n  struct run *next;\n};\n\nstruct {\n  struct spinlock lock;\n  int use_lock;\n  struct run *freelist;\n} kmem;\n\n// Initialization happens in two phases.\n// 1. main() calls kinit1() while still using entrypgdir to place just\n// the pages mapped by entrypgdir on free list.\n// 2. main() calls kinit2() with the rest of the physical pages\n// after installing a full page table that maps them on all cores.\nvoid\nkinit1(void *vstart, void *vend)\n{\n  initlock(&kmem.lock, \"kmem\");\n  kmem.use_lock = 0;\n  freerange(vstart, vend);\n}\n\nvoid\nkinit2(void *vstart, void *vend)\n{\n  freerange(vstart, vend);\n  kmem.use_lock = 1;\n}\n\nvoid\nfreerange(void *vstart, void *vend)\n{\n  char *p;\n  p = (char*)PGROUNDUP((uint)vstart);\n  for(; p + PGSIZE <= (char*)vend; p += PGSIZE)\n    kfree(p);\n}\n//PAGEBREAK: 21\n// Free the page of physical memory pointed at by v,\n// which normally should have been returned by a\n// call to kalloc().  (The exception is when\n// initializing the allocator; see kinit above.)\nvoid\nkfree(char *v)\n{\n  struct run *r;\n\n  if((uint)v % PGSIZE || v < end || V2P(v) >= PHYSTOP)\n    panic(\"kfree\");\n\n  // Fill with junk to catch dangling refs.\n  memset(v, 1, PGSIZE);\n\n  if(kmem.use_lock)\n    acquire(&kmem.lock);\n  r = (struct run*)v;\n  r->next = kmem.freelist;\n  kmem.freelist = r;\n  if(kmem.use_lock)\n    release(&kmem.lock);\n}\n\n// Allocate one 4096-byte page of physical memory.\n// Returns a pointer that the kernel can use.\n// Returns 0 if the memory cannot be allocated.\nchar*\nkalloc(void)\n{\n  struct run *r;\n\n  if(kmem.use_lock)\n    acquire(&kmem.lock);\n  r = kmem.freelist;\n  if(r)\n    kmem.freelist = r->next;\n  if(kmem.use_lock)\n    release(&kmem.lock);\n  return (char*)r;\n}\n\n"
  },
  {
    "path": "kbd.c",
    "content": "#include \"types.h\"\n#include \"x86.h\"\n#include \"defs.h\"\n#include \"kbd.h\"\n\nint\nkbdgetc(void)\n{\n  static uint shift;\n  static uchar *charcode[4] = {\n    normalmap, shiftmap, ctlmap, ctlmap\n  };\n  uint st, data, c;\n\n  st = inb(KBSTATP);\n  if((st & KBS_DIB) == 0)\n    return -1;\n  data = inb(KBDATAP);\n\n  if(data == 0xE0){\n    shift |= E0ESC;\n    return 0;\n  } else if(data & 0x80){\n    // Key released\n    data = (shift & E0ESC ? data : data & 0x7F);\n    shift &= ~(shiftcode[data] | E0ESC);\n    return 0;\n  } else if(shift & E0ESC){\n    // Last character was an E0 escape; or with 0x80\n    data |= 0x80;\n    shift &= ~E0ESC;\n  }\n\n  shift |= shiftcode[data];\n  shift ^= togglecode[data];\n  c = charcode[shift & (CTL | SHIFT)][data];\n  if(shift & CAPSLOCK){\n    if('a' <= c && c <= 'z')\n      c += 'A' - 'a';\n    else if('A' <= c && c <= 'Z')\n      c += 'a' - 'A';\n  }\n  return c;\n}\n\nvoid\nkbdintr(void)\n{\n  consoleintr(kbdgetc);\n}\n"
  },
  {
    "path": "kbd.h",
    "content": "// PC keyboard interface constants\n\n#define KBSTATP         0x64    // kbd controller status port(I)\n#define KBS_DIB         0x01    // kbd data in buffer\n#define KBDATAP         0x60    // kbd data port(I)\n\n#define NO              0\n\n#define SHIFT           (1<<0)\n#define CTL             (1<<1)\n#define ALT             (1<<2)\n\n#define CAPSLOCK        (1<<3)\n#define NUMLOCK         (1<<4)\n#define SCROLLLOCK      (1<<5)\n\n#define E0ESC           (1<<6)\n\n// Special keycodes\n#define KEY_HOME        0xE0\n#define KEY_END         0xE1\n#define KEY_UP          0xE2\n#define KEY_DN          0xE3\n#define KEY_LF          0xE4\n#define KEY_RT          0xE5\n#define KEY_PGUP        0xE6\n#define KEY_PGDN        0xE7\n#define KEY_INS         0xE8\n#define KEY_DEL         0xE9\n\n// C('A') == Control-A\n#define C(x) (x - '@')\n\nstatic uchar shiftcode[256] =\n{\n  [0x1D] CTL,\n  [0x2A] SHIFT,\n  [0x36] SHIFT,\n  [0x38] ALT,\n  [0x9D] CTL,\n  [0xB8] ALT\n};\n\nstatic uchar togglecode[256] =\n{\n  [0x3A] CAPSLOCK,\n  [0x45] NUMLOCK,\n  [0x46] SCROLLLOCK\n};\n\nstatic uchar normalmap[256] =\n{\n  NO,   0x1B, '1',  '2',  '3',  '4',  '5',  '6',  // 0x00\n  '7',  '8',  '9',  '0',  '-',  '=',  '\\b', '\\t',\n  'q',  'w',  'e',  'r',  't',  'y',  'u',  'i',  // 0x10\n  'o',  'p',  '[',  ']',  '\\n', NO,   'a',  's',\n  'd',  'f',  'g',  'h',  'j',  'k',  'l',  ';',  // 0x20\n  '\\'', '`',  NO,   '\\\\', 'z',  'x',  'c',  'v',\n  'b',  'n',  'm',  ',',  '.',  '/',  NO,   '*',  // 0x30\n  NO,   ' ',  NO,   NO,   NO,   NO,   NO,   NO,\n  NO,   NO,   NO,   NO,   NO,   NO,   NO,   '7',  // 0x40\n  '8',  '9',  '-',  '4',  '5',  '6',  '+',  '1',\n  '2',  '3',  '0',  '.',  NO,   NO,   NO,   NO,   // 0x50\n  [0x9C] '\\n',      // KP_Enter\n  [0xB5] '/',       // KP_Div\n  [0xC8] KEY_UP,    [0xD0] KEY_DN,\n  [0xC9] KEY_PGUP,  [0xD1] KEY_PGDN,\n  [0xCB] KEY_LF,    [0xCD] KEY_RT,\n  [0x97] KEY_HOME,  [0xCF] KEY_END,\n  [0xD2] KEY_INS,   [0xD3] KEY_DEL\n};\n\nstatic uchar shiftmap[256] =\n{\n  NO,   033,  '!',  '@',  '#',  '$',  '%',  '^',  // 0x00\n  '&',  '*',  '(',  ')',  '_',  '+',  '\\b', '\\t',\n  'Q',  'W',  'E',  'R',  'T',  'Y',  'U',  'I',  // 0x10\n  'O',  'P',  '{',  '}',  '\\n', NO,   'A',  'S',\n  'D',  'F',  'G',  'H',  'J',  'K',  'L',  ':',  // 0x20\n  '\"',  '~',  NO,   '|',  'Z',  'X',  'C',  'V',\n  'B',  'N',  'M',  '<',  '>',  '?',  NO,   '*',  // 0x30\n  NO,   ' ',  NO,   NO,   NO,   NO,   NO,   NO,\n  NO,   NO,   NO,   NO,   NO,   NO,   NO,   '7',  // 0x40\n  '8',  '9',  '-',  '4',  '5',  '6',  '+',  '1',\n  '2',  '3',  '0',  '.',  NO,   NO,   NO,   NO,   // 0x50\n  [0x9C] '\\n',      // KP_Enter\n  [0xB5] '/',       // KP_Div\n  [0xC8] KEY_UP,    [0xD0] KEY_DN,\n  [0xC9] KEY_PGUP,  [0xD1] KEY_PGDN,\n  [0xCB] KEY_LF,    [0xCD] KEY_RT,\n  [0x97] KEY_HOME,  [0xCF] KEY_END,\n  [0xD2] KEY_INS,   [0xD3] KEY_DEL\n};\n\nstatic uchar ctlmap[256] =\n{\n  NO,      NO,      NO,      NO,      NO,      NO,      NO,      NO,\n  NO,      NO,      NO,      NO,      NO,      NO,      NO,      NO,\n  C('Q'),  C('W'),  C('E'),  C('R'),  C('T'),  C('Y'),  C('U'),  C('I'),\n  C('O'),  C('P'),  NO,      NO,      '\\r',    NO,      C('A'),  C('S'),\n  C('D'),  C('F'),  C('G'),  C('H'),  C('J'),  C('K'),  C('L'),  NO,\n  NO,      NO,      NO,      C('\\\\'), C('Z'),  C('X'),  C('C'),  C('V'),\n  C('B'),  C('N'),  C('M'),  NO,      NO,      C('/'),  NO,      NO,\n  [0x9C] '\\r',      // KP_Enter\n  [0xB5] C('/'),    // KP_Div\n  [0xC8] KEY_UP,    [0xD0] KEY_DN,\n  [0xC9] KEY_PGUP,  [0xD1] KEY_PGDN,\n  [0xCB] KEY_LF,    [0xCD] KEY_RT,\n  [0x97] KEY_HOME,  [0xCF] KEY_END,\n  [0xD2] KEY_INS,   [0xD3] KEY_DEL\n};\n\n"
  },
  {
    "path": "kernel.ld",
    "content": "/* Simple linker script for the JOS kernel.\n   See the GNU ld 'info' manual (\"info ld\") to learn the syntax. */\n\nOUTPUT_FORMAT(\"elf32-i386\", \"elf32-i386\", \"elf32-i386\")\nOUTPUT_ARCH(i386)\nENTRY(_start)\n\nSECTIONS\n{\n\t/* Link the kernel at this address: \".\" means the current address */\n        /* Must be equal to KERNLINK */\n\t. = 0x80100000;\n\n\t.text : AT(0x100000) {\n\t\t*(.text .stub .text.* .gnu.linkonce.t.*)\n\t}\n\n\tPROVIDE(etext = .);\t/* Define the 'etext' symbol to this value */\n\n\t.rodata : {\n\t\t*(.rodata .rodata.* .gnu.linkonce.r.*)\n\t}\n\n\t/* Include debugging information in kernel memory */\n\t.stab : {\n\t\tPROVIDE(__STAB_BEGIN__ = .);\n\t\t*(.stab);\n\t\tPROVIDE(__STAB_END__ = .);\n\t}\n\n\t.stabstr : {\n\t\tPROVIDE(__STABSTR_BEGIN__ = .);\n\t\t*(.stabstr);\n\t\tPROVIDE(__STABSTR_END__ = .);\n\t}\n\n\t/* Adjust the address for the data segment to the next page */\n\t. = ALIGN(0x1000);\n\n\t/* Conventionally, Unix linkers provide pseudo-symbols\n\t * etext, edata, and end, at the end of the text, data, and bss.\n\t * For the kernel mapping, we need the address at the beginning\n\t * of the data section, but that's not one of the conventional\n\t * symbols, because the convention started before there was a\n\t * read-only rodata section between text and data. */\n\tPROVIDE(data = .);\n\n\t/* The data segment */\n\t.data : {\n\t\t*(.data)\n\t}\n\n\tPROVIDE(edata = .);\n\n\t.bss : {\n\t\t*(.bss)\n\t}\n\n\tPROVIDE(end = .);\n\n\t/DISCARD/ : {\n\t\t*(.eh_frame .note.GNU-stack)\n\t}\n}\n"
  },
  {
    "path": "kill.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(int argc, char **argv)\n{\n  int i;\n\n  if(argc < 2){\n    printf(2, \"usage: kill pid...\\n\");\n    exit();\n  }\n  for(i=1; i<argc; i++)\n    kill(atoi(argv[i]));\n  exit();\n}\n"
  },
  {
    "path": "lapic.c",
    "content": "// The local APIC manages internal (non-I/O) interrupts.\n// See Chapter 8 & Appendix C of Intel processor manual volume 3.\n\n#include \"param.h\"\n#include \"types.h\"\n#include \"defs.h\"\n#include \"date.h\"\n#include \"memlayout.h\"\n#include \"traps.h\"\n#include \"mmu.h\"\n#include \"x86.h\"\n\n// Local APIC registers, divided by 4 for use as uint[] indices.\n#define ID      (0x0020/4)   // ID\n#define VER     (0x0030/4)   // Version\n#define TPR     (0x0080/4)   // Task Priority\n#define EOI     (0x00B0/4)   // EOI\n#define SVR     (0x00F0/4)   // Spurious Interrupt Vector\n  #define ENABLE     0x00000100   // Unit Enable\n#define ESR     (0x0280/4)   // Error Status\n#define ICRLO   (0x0300/4)   // Interrupt Command\n  #define INIT       0x00000500   // INIT/RESET\n  #define STARTUP    0x00000600   // Startup IPI\n  #define DELIVS     0x00001000   // Delivery status\n  #define ASSERT     0x00004000   // Assert interrupt (vs deassert)\n  #define DEASSERT   0x00000000\n  #define LEVEL      0x00008000   // Level triggered\n  #define BCAST      0x00080000   // Send to all APICs, including self.\n  #define BUSY       0x00001000\n  #define FIXED      0x00000000\n#define ICRHI   (0x0310/4)   // Interrupt Command [63:32]\n#define TIMER   (0x0320/4)   // Local Vector Table 0 (TIMER)\n  #define X1         0x0000000B   // divide counts by 1\n  #define PERIODIC   0x00020000   // Periodic\n#define PCINT   (0x0340/4)   // Performance Counter LVT\n#define LINT0   (0x0350/4)   // Local Vector Table 1 (LINT0)\n#define LINT1   (0x0360/4)   // Local Vector Table 2 (LINT1)\n#define ERROR   (0x0370/4)   // Local Vector Table 3 (ERROR)\n  #define MASKED     0x00010000   // Interrupt masked\n#define TICR    (0x0380/4)   // Timer Initial Count\n#define TCCR    (0x0390/4)   // Timer Current Count\n#define TDCR    (0x03E0/4)   // Timer Divide Configuration\n\nvolatile uint *lapic;  // Initialized in mp.c\n\n//PAGEBREAK!\nstatic void\nlapicw(int index, int value)\n{\n  lapic[index] = value;\n  lapic[ID];  // wait for write to finish, by reading\n}\n\nvoid\nlapicinit(void)\n{\n  if(!lapic)\n    return;\n\n  // Enable local APIC; set spurious interrupt vector.\n  lapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS));\n\n  // The timer repeatedly counts down at bus frequency\n  // from lapic[TICR] and then issues an interrupt.\n  // If xv6 cared more about precise timekeeping,\n  // TICR would be calibrated using an external time source.\n  lapicw(TDCR, X1);\n  lapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));\n  lapicw(TICR, 10000000);\n\n  // Disable logical interrupt lines.\n  lapicw(LINT0, MASKED);\n  lapicw(LINT1, MASKED);\n\n  // Disable performance counter overflow interrupts\n  // on machines that provide that interrupt entry.\n  if(((lapic[VER]>>16) & 0xFF) >= 4)\n    lapicw(PCINT, MASKED);\n\n  // Map error interrupt to IRQ_ERROR.\n  lapicw(ERROR, T_IRQ0 + IRQ_ERROR);\n\n  // Clear error status register (requires back-to-back writes).\n  lapicw(ESR, 0);\n  lapicw(ESR, 0);\n\n  // Ack any outstanding interrupts.\n  lapicw(EOI, 0);\n\n  // Send an Init Level De-Assert to synchronise arbitration ID's.\n  lapicw(ICRHI, 0);\n  lapicw(ICRLO, BCAST | INIT | LEVEL);\n  while(lapic[ICRLO] & DELIVS)\n    ;\n\n  // Enable interrupts on the APIC (but not on the processor).\n  lapicw(TPR, 0);\n}\n\nint\nlapicid(void)\n{\n  if (!lapic)\n    return 0;\n  return lapic[ID] >> 24;\n}\n\n// Acknowledge interrupt.\nvoid\nlapiceoi(void)\n{\n  if(lapic)\n    lapicw(EOI, 0);\n}\n\n// Spin for a given number of microseconds.\n// On real hardware would want to tune this dynamically.\nvoid\nmicrodelay(int us)\n{\n}\n\n#define CMOS_PORT    0x70\n#define CMOS_RETURN  0x71\n\n// Start additional processor running entry code at addr.\n// See Appendix B of MultiProcessor Specification.\nvoid\nlapicstartap(uchar apicid, uint addr)\n{\n  int i;\n  ushort *wrv;\n\n  // \"The BSP must initialize CMOS shutdown code to 0AH\n  // and the warm reset vector (DWORD based at 40:67) to point at\n  // the AP startup code prior to the [universal startup algorithm].\"\n  outb(CMOS_PORT, 0xF);  // offset 0xF is shutdown code\n  outb(CMOS_PORT+1, 0x0A);\n  wrv = (ushort*)P2V((0x40<<4 | 0x67));  // Warm reset vector\n  wrv[0] = 0;\n  wrv[1] = addr >> 4;\n\n  // \"Universal startup algorithm.\"\n  // Send INIT (level-triggered) interrupt to reset other CPU.\n  lapicw(ICRHI, apicid<<24);\n  lapicw(ICRLO, INIT | LEVEL | ASSERT);\n  microdelay(200);\n  lapicw(ICRLO, INIT | LEVEL);\n  microdelay(100);    // should be 10ms, but too slow in Bochs!\n\n  // Send startup IPI (twice!) to enter code.\n  // Regular hardware is supposed to only accept a STARTUP\n  // when it is in the halted state due to an INIT.  So the second\n  // should be ignored, but it is part of the official Intel algorithm.\n  // Bochs complains about the second one.  Too bad for Bochs.\n  for(i = 0; i < 2; i++){\n    lapicw(ICRHI, apicid<<24);\n    lapicw(ICRLO, STARTUP | (addr>>12));\n    microdelay(200);\n  }\n}\n\n#define CMOS_STATA   0x0a\n#define CMOS_STATB   0x0b\n#define CMOS_UIP    (1 << 7)        // RTC update in progress\n\n#define SECS    0x00\n#define MINS    0x02\n#define HOURS   0x04\n#define DAY     0x07\n#define MONTH   0x08\n#define YEAR    0x09\n\nstatic uint\ncmos_read(uint reg)\n{\n  outb(CMOS_PORT,  reg);\n  microdelay(200);\n\n  return inb(CMOS_RETURN);\n}\n\nstatic void\nfill_rtcdate(struct rtcdate *r)\n{\n  r->second = cmos_read(SECS);\n  r->minute = cmos_read(MINS);\n  r->hour   = cmos_read(HOURS);\n  r->day    = cmos_read(DAY);\n  r->month  = cmos_read(MONTH);\n  r->year   = cmos_read(YEAR);\n}\n\n// qemu seems to use 24-hour GWT and the values are BCD encoded\nvoid\ncmostime(struct rtcdate *r)\n{\n  struct rtcdate t1, t2;\n  int sb, bcd;\n\n  sb = cmos_read(CMOS_STATB);\n\n  bcd = (sb & (1 << 2)) == 0;\n\n  // make sure CMOS doesn't modify time while we read it\n  for(;;) {\n    fill_rtcdate(&t1);\n    if(cmos_read(CMOS_STATA) & CMOS_UIP)\n        continue;\n    fill_rtcdate(&t2);\n    if(memcmp(&t1, &t2, sizeof(t1)) == 0)\n      break;\n  }\n\n  // convert\n  if(bcd) {\n#define    CONV(x)     (t1.x = ((t1.x >> 4) * 10) + (t1.x & 0xf))\n    CONV(second);\n    CONV(minute);\n    CONV(hour  );\n    CONV(day   );\n    CONV(month );\n    CONV(year  );\n#undef     CONV\n  }\n\n  *r = t1;\n  r->year += 2000;\n}\n"
  },
  {
    "path": "ln.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(int argc, char *argv[])\n{\n  if(argc != 3){\n    printf(2, \"Usage: ln old new\\n\");\n    exit();\n  }\n  if(link(argv[1], argv[2]) < 0)\n    printf(2, \"link %s %s: failed\\n\", argv[1], argv[2]);\n  exit();\n}\n"
  },
  {
    "path": "log.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"buf.h\"\n\n// Simple logging that allows concurrent FS system calls.\n//\n// A log transaction contains the updates of multiple FS system\n// calls. The logging system only commits when there are\n// no FS system calls active. Thus there is never\n// any reasoning required about whether a commit might\n// write an uncommitted system call's updates to disk.\n//\n// A system call should call begin_op()/end_op() to mark\n// its start and end. Usually begin_op() just increments\n// the count of in-progress FS system calls and returns.\n// But if it thinks the log is close to running out, it\n// sleeps until the last outstanding end_op() commits.\n//\n// The log is a physical re-do log containing disk blocks.\n// The on-disk log format:\n//   header block, containing block #s for block A, B, C, ...\n//   block A\n//   block B\n//   block C\n//   ...\n// Log appends are synchronous.\n\n// Contents of the header block, used for both the on-disk header block\n// and to keep track in memory of logged block# before commit.\nstruct logheader {\n  int n;\n  int block[LOGSIZE];\n};\n\nstruct log {\n  struct spinlock lock;\n  int start;\n  int size;\n  int outstanding; // how many FS sys calls are executing.\n  int committing;  // in commit(), please wait.\n  int dev;\n  struct logheader lh;\n};\nstruct log log;\n\nstatic void recover_from_log(void);\nstatic void commit();\n\nvoid\ninitlog(int dev)\n{\n  if (sizeof(struct logheader) >= BSIZE)\n    panic(\"initlog: too big logheader\");\n\n  struct superblock sb;\n  initlock(&log.lock, \"log\");\n  readsb(dev, &sb);\n  log.start = sb.logstart;\n  log.size = sb.nlog;\n  log.dev = dev;\n  recover_from_log();\n}\n\n// Copy committed blocks from log to their home location\nstatic void\ninstall_trans(void)\n{\n  int tail;\n\n  for (tail = 0; tail < log.lh.n; tail++) {\n    struct buf *lbuf = bread(log.dev, log.start+tail+1); // read log block\n    struct buf *dbuf = bread(log.dev, log.lh.block[tail]); // read dst\n    memmove(dbuf->data, lbuf->data, BSIZE);  // copy block to dst\n    bwrite(dbuf);  // write dst to disk\n    brelse(lbuf);\n    brelse(dbuf);\n  }\n}\n\n// Read the log header from disk into the in-memory log header\nstatic void\nread_head(void)\n{\n  struct buf *buf = bread(log.dev, log.start);\n  struct logheader *lh = (struct logheader *) (buf->data);\n  int i;\n  log.lh.n = lh->n;\n  for (i = 0; i < log.lh.n; i++) {\n    log.lh.block[i] = lh->block[i];\n  }\n  brelse(buf);\n}\n\n// Write in-memory log header to disk.\n// This is the true point at which the\n// current transaction commits.\nstatic void\nwrite_head(void)\n{\n  struct buf *buf = bread(log.dev, log.start);\n  struct logheader *hb = (struct logheader *) (buf->data);\n  int i;\n  hb->n = log.lh.n;\n  for (i = 0; i < log.lh.n; i++) {\n    hb->block[i] = log.lh.block[i];\n  }\n  bwrite(buf);\n  brelse(buf);\n}\n\nstatic void\nrecover_from_log(void)\n{\n  read_head();\n  install_trans(); // if committed, copy from log to disk\n  log.lh.n = 0;\n  write_head(); // clear the log\n}\n\n// called at the start of each FS system call.\nvoid\nbegin_op(void)\n{\n  acquire(&log.lock);\n  while(1){\n    if(log.committing){\n      sleep(&log, &log.lock);\n    } else if(log.lh.n + (log.outstanding+1)*MAXOPBLOCKS > LOGSIZE){\n      // this op might exhaust log space; wait for commit.\n      sleep(&log, &log.lock);\n    } else {\n      log.outstanding += 1;\n      release(&log.lock);\n      break;\n    }\n  }\n}\n\n// called at the end of each FS system call.\n// commits if this was the last outstanding operation.\nvoid\nend_op(void)\n{\n  int do_commit = 0;\n\n  acquire(&log.lock);\n  log.outstanding -= 1;\n  if(log.committing)\n    panic(\"log.committing\");\n  if(log.outstanding == 0){\n    do_commit = 1;\n    log.committing = 1;\n  } else {\n    // begin_op() may be waiting for log space,\n    // and decrementing log.outstanding has decreased\n    // the amount of reserved space.\n    wakeup(&log);\n  }\n  release(&log.lock);\n\n  if(do_commit){\n    // call commit w/o holding locks, since not allowed\n    // to sleep with locks.\n    commit();\n    acquire(&log.lock);\n    log.committing = 0;\n    wakeup(&log);\n    release(&log.lock);\n  }\n}\n\n// Copy modified blocks from cache to log.\nstatic void\nwrite_log(void)\n{\n  int tail;\n\n  for (tail = 0; tail < log.lh.n; tail++) {\n    struct buf *to = bread(log.dev, log.start+tail+1); // log block\n    struct buf *from = bread(log.dev, log.lh.block[tail]); // cache block\n    memmove(to->data, from->data, BSIZE);\n    bwrite(to);  // write the log\n    brelse(from);\n    brelse(to);\n  }\n}\n\nstatic void\ncommit()\n{\n  if (log.lh.n > 0) {\n    write_log();     // Write modified blocks from cache to log\n    write_head();    // Write header to disk -- the real commit\n    install_trans(); // Now install writes to home locations\n    log.lh.n = 0;\n    write_head();    // Erase the transaction from the log\n  }\n}\n\n// Caller has modified b->data and is done with the buffer.\n// Record the block number and pin in the cache with B_DIRTY.\n// commit()/write_log() will do the disk write.\n//\n// log_write() replaces bwrite(); a typical use is:\n//   bp = bread(...)\n//   modify bp->data[]\n//   log_write(bp)\n//   brelse(bp)\nvoid\nlog_write(struct buf *b)\n{\n  int i;\n\n  if (log.lh.n >= LOGSIZE || log.lh.n >= log.size - 1)\n    panic(\"too big a transaction\");\n  if (log.outstanding < 1)\n    panic(\"log_write outside of trans\");\n\n  acquire(&log.lock);\n  for (i = 0; i < log.lh.n; i++) {\n    if (log.lh.block[i] == b->blockno)   // log absorbtion\n      break;\n  }\n  log.lh.block[i] = b->blockno;\n  if (i == log.lh.n)\n    log.lh.n++;\n  b->flags |= B_DIRTY; // prevent eviction\n  release(&log.lock);\n}\n\n"
  },
  {
    "path": "ls.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"fs.h\"\n\nchar*\nfmtname(char *path)\n{\n  static char buf[DIRSIZ+1];\n  char *p;\n\n  // Find first character after last slash.\n  for(p=path+strlen(path); p >= path && *p != '/'; p--)\n    ;\n  p++;\n\n  // Return blank-padded name.\n  if(strlen(p) >= DIRSIZ)\n    return p;\n  memmove(buf, p, strlen(p));\n  memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));\n  return buf;\n}\n\nvoid\nls(char *path)\n{\n  char buf[512], *p;\n  int fd;\n  struct dirent de;\n  struct stat st;\n\n  if((fd = open(path, 0)) < 0){\n    printf(2, \"ls: cannot open %s\\n\", path);\n    return;\n  }\n\n  if(fstat(fd, &st) < 0){\n    printf(2, \"ls: cannot stat %s\\n\", path);\n    close(fd);\n    return;\n  }\n\n  switch(st.type){\n  case T_FILE:\n    printf(1, \"%s %d %d %d\\n\", fmtname(path), st.type, st.ino, st.size);\n    break;\n\n  case T_DIR:\n    if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){\n      printf(1, \"ls: path too long\\n\");\n      break;\n    }\n    strcpy(buf, path);\n    p = buf+strlen(buf);\n    *p++ = '/';\n    while(read(fd, &de, sizeof(de)) == sizeof(de)){\n      if(de.inum == 0)\n        continue;\n      memmove(p, de.name, DIRSIZ);\n      p[DIRSIZ] = 0;\n      if(stat(buf, &st) < 0){\n        printf(1, \"ls: cannot stat %s\\n\", buf);\n        continue;\n      }\n      printf(1, \"%s %d %d %d\\n\", fmtname(buf), st.type, st.ino, st.size);\n    }\n    break;\n  }\n  close(fd);\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int i;\n\n  if(argc < 2){\n    ls(\".\");\n    exit();\n  }\n  for(i=1; i<argc; i++)\n    ls(argv[i]);\n  exit();\n}\n"
  },
  {
    "path": "main.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n\nstatic void startothers(void);\nstatic void mpmain(void)  __attribute__((noreturn));\nextern pde_t *kpgdir;\nextern char end[]; // first address after kernel loaded from ELF file\n\n// Bootstrap processor starts running C code here.\n// Allocate a real stack and switch to it, first\n// doing some setup required for memory allocator to work.\nint\nmain(void)\n{\n  kinit1(end, P2V(4*1024*1024)); // phys page allocator\n  kvmalloc();      // kernel page table\n  mpinit();        // detect other processors\n  lapicinit();     // interrupt controller\n  seginit();       // segment descriptors\n  picinit();       // disable pic\n  ioapicinit();    // another interrupt controller\n  consoleinit();   // console hardware\n  uartinit();      // serial port\n  pinit();         // process table\n  tvinit();        // trap vectors\n  binit();         // buffer cache\n  fileinit();      // file table\n  ideinit();       // disk \n  startothers();   // start other processors\n  kinit2(P2V(4*1024*1024), P2V(PHYSTOP)); // must come after startothers()\n  userinit();      // first user process\n  mpmain();        // finish this processor's setup\n}\n\n// Other CPUs jump here from entryother.S.\nstatic void\nmpenter(void)\n{\n  switchkvm();\n  seginit();\n  lapicinit();\n  mpmain();\n}\n\n// Common CPU setup code.\nstatic void\nmpmain(void)\n{\n  cprintf(\"cpu%d: starting %d\\n\", cpuid(), cpuid());\n  idtinit();       // load idt register\n  xchg(&(mycpu()->started), 1); // tell startothers() we're up\n  scheduler();     // start running processes\n}\n\npde_t entrypgdir[];  // For entry.S\n\n// Start the non-boot (AP) processors.\nstatic void\nstartothers(void)\n{\n  extern uchar _binary_entryother_start[], _binary_entryother_size[];\n  uchar *code;\n  struct cpu *c;\n  char *stack;\n\n  // Write entry code to unused memory at 0x7000.\n  // The linker has placed the image of entryother.S in\n  // _binary_entryother_start.\n  code = P2V(0x7000);\n  memmove(code, _binary_entryother_start, (uint)_binary_entryother_size);\n\n  for(c = cpus; c < cpus+ncpu; c++){\n    if(c == mycpu())  // We've started already.\n      continue;\n\n    // Tell entryother.S what stack to use, where to enter, and what\n    // pgdir to use. We cannot use kpgdir yet, because the AP processor\n    // is running in low  memory, so we use entrypgdir for the APs too.\n    stack = kalloc();\n    *(void**)(code-4) = stack + KSTACKSIZE;\n    *(void(**)(void))(code-8) = mpenter;\n    *(int**)(code-12) = (void *) V2P(entrypgdir);\n\n    lapicstartap(c->apicid, V2P(code));\n\n    // wait for cpu to finish mpmain()\n    while(c->started == 0)\n      ;\n  }\n}\n\n// The boot page table used in entry.S and entryother.S.\n// Page directories (and page tables) must start on page boundaries,\n// hence the __aligned__ attribute.\n// PTE_PS in a page directory entry enables 4Mbyte pages.\n\n__attribute__((__aligned__(PGSIZE)))\npde_t entrypgdir[NPDENTRIES] = {\n  // Map VA's [0, 4MB) to PA's [0, 4MB)\n  [0] = (0) | PTE_P | PTE_W | PTE_PS,\n  // Map VA's [KERNBASE, KERNBASE+4MB) to PA's [0, 4MB)\n  [KERNBASE>>PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS,\n};\n\n//PAGEBREAK!\n// Blank page.\n//PAGEBREAK!\n// Blank page.\n//PAGEBREAK!\n// Blank page.\n\n"
  },
  {
    "path": "memide.c",
    "content": "// Fake IDE disk; stores blocks in memory.\n// Useful for running kernel without scratch disk.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n#include \"traps.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"buf.h\"\n\nextern uchar _binary_fs_img_start[], _binary_fs_img_size[];\n\nstatic int disksize;\nstatic uchar *memdisk;\n\nvoid\nideinit(void)\n{\n  memdisk = _binary_fs_img_start;\n  disksize = (uint)_binary_fs_img_size/BSIZE;\n}\n\n// Interrupt handler.\nvoid\nideintr(void)\n{\n  // no-op\n}\n\n// Sync buf with disk.\n// If B_DIRTY is set, write buf to disk, clear B_DIRTY, set B_VALID.\n// Else if B_VALID is not set, read buf from disk, set B_VALID.\nvoid\niderw(struct buf *b)\n{\n  uchar *p;\n\n  if(!holdingsleep(&b->lock))\n    panic(\"iderw: buf not locked\");\n  if((b->flags & (B_VALID|B_DIRTY)) == B_VALID)\n    panic(\"iderw: nothing to do\");\n  if(b->dev != 1)\n    panic(\"iderw: request not for disk 1\");\n  if(b->blockno >= disksize)\n    panic(\"iderw: block out of range\");\n\n  p = memdisk + b->blockno*BSIZE;\n\n  if(b->flags & B_DIRTY){\n    b->flags &= ~B_DIRTY;\n    memmove(p, b->data, BSIZE);\n  } else\n    memmove(b->data, p, BSIZE);\n  b->flags |= B_VALID;\n}\n"
  },
  {
    "path": "memlayout.h",
    "content": "// Memory layout\n\n#define EXTMEM  0x100000            // Start of extended memory\n#define PHYSTOP 0xE000000           // Top physical memory\n#define DEVSPACE 0xFE000000         // Other devices are at high addresses\n\n// Key addresses for address space layout (see kmap in vm.c for layout)\n#define KERNBASE 0x80000000         // First kernel virtual address\n#define KERNLINK (KERNBASE+EXTMEM)  // Address where kernel is linked\n\n#define V2P(a) (((uint) (a)) - KERNBASE)\n#define P2V(a) ((void *)(((char *) (a)) + KERNBASE))\n\n#define V2P_WO(x) ((x) - KERNBASE)    // same as V2P, but without casts\n#define P2V_WO(x) ((x) + KERNBASE)    // same as P2V, but without casts\n"
  },
  {
    "path": "mkdir.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(int argc, char *argv[])\n{\n  int i;\n\n  if(argc < 2){\n    printf(2, \"Usage: mkdir files...\\n\");\n    exit();\n  }\n\n  for(i = 1; i < argc; i++){\n    if(mkdir(argv[i]) < 0){\n      printf(2, \"mkdir: %s failed to create\\n\", argv[i]);\n      break;\n    }\n  }\n\n  exit();\n}\n"
  },
  {
    "path": "mkfs.c",
    "content": "#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <assert.h>\n\n#define stat xv6_stat  // avoid clash with host struct stat\n#include \"types.h\"\n#include \"fs.h\"\n#include \"stat.h\"\n#include \"param.h\"\n\n#ifndef static_assert\n#define static_assert(a, b) do { switch (0) case 0: case (a): ; } while (0)\n#endif\n\n#define NINODES 200\n\n// Disk layout:\n// [ boot block | sb block | log | inode blocks | free bit map | data blocks ]\n\nint nbitmap = FSSIZE/(BSIZE*8) + 1;\nint ninodeblocks = NINODES / IPB + 1;\nint nlog = LOGSIZE;\nint nmeta;    // Number of meta blocks (boot, sb, nlog, inode, bitmap)\nint nblocks;  // Number of data blocks\n\nint fsfd;\nstruct superblock sb;\nchar zeroes[BSIZE];\nuint freeinode = 1;\nuint freeblock;\n\n\nvoid balloc(int);\nvoid wsect(uint, void*);\nvoid winode(uint, struct dinode*);\nvoid rinode(uint inum, struct dinode *ip);\nvoid rsect(uint sec, void *buf);\nuint ialloc(ushort type);\nvoid iappend(uint inum, void *p, int n);\n\n// convert to intel byte order\nushort\nxshort(ushort x)\n{\n  ushort y;\n  uchar *a = (uchar*)&y;\n  a[0] = x;\n  a[1] = x >> 8;\n  return y;\n}\n\nuint\nxint(uint x)\n{\n  uint y;\n  uchar *a = (uchar*)&y;\n  a[0] = x;\n  a[1] = x >> 8;\n  a[2] = x >> 16;\n  a[3] = x >> 24;\n  return y;\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int i, cc, fd;\n  uint rootino, inum, off;\n  struct dirent de;\n  char buf[BSIZE];\n  struct dinode din;\n\n\n  static_assert(sizeof(int) == 4, \"Integers must be 4 bytes!\");\n\n  if(argc < 2){\n    fprintf(stderr, \"Usage: mkfs fs.img files...\\n\");\n    exit(1);\n  }\n\n  assert((BSIZE % sizeof(struct dinode)) == 0);\n  assert((BSIZE % sizeof(struct dirent)) == 0);\n\n  fsfd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666);\n  if(fsfd < 0){\n    perror(argv[1]);\n    exit(1);\n  }\n\n  // 1 fs block = 1 disk sector\n  nmeta = 2 + nlog + ninodeblocks + nbitmap;\n  nblocks = FSSIZE - nmeta;\n\n  sb.size = xint(FSSIZE);\n  sb.nblocks = xint(nblocks);\n  sb.ninodes = xint(NINODES);\n  sb.nlog = xint(nlog);\n  sb.logstart = xint(2);\n  sb.inodestart = xint(2+nlog);\n  sb.bmapstart = xint(2+nlog+ninodeblocks);\n\n  printf(\"nmeta %d (boot, super, log blocks %u inode blocks %u, bitmap blocks %u) blocks %d total %d\\n\",\n         nmeta, nlog, ninodeblocks, nbitmap, nblocks, FSSIZE);\n\n  freeblock = nmeta;     // the first free block that we can allocate\n\n  for(i = 0; i < FSSIZE; i++)\n    wsect(i, zeroes);\n\n  memset(buf, 0, sizeof(buf));\n  memmove(buf, &sb, sizeof(sb));\n  wsect(1, buf);\n\n  rootino = ialloc(T_DIR);\n  assert(rootino == ROOTINO);\n\n  bzero(&de, sizeof(de));\n  de.inum = xshort(rootino);\n  strcpy(de.name, \".\");\n  iappend(rootino, &de, sizeof(de));\n\n  bzero(&de, sizeof(de));\n  de.inum = xshort(rootino);\n  strcpy(de.name, \"..\");\n  iappend(rootino, &de, sizeof(de));\n\n  for(i = 2; i < argc; i++){\n    assert(index(argv[i], '/') == 0);\n\n    if((fd = open(argv[i], 0)) < 0){\n      perror(argv[i]);\n      exit(1);\n    }\n\n    // Skip leading _ in name when writing to file system.\n    // The binaries are named _rm, _cat, etc. to keep the\n    // build operating system from trying to execute them\n    // in place of system binaries like rm and cat.\n    if(argv[i][0] == '_')\n      ++argv[i];\n\n    inum = ialloc(T_FILE);\n\n    bzero(&de, sizeof(de));\n    de.inum = xshort(inum);\n    strncpy(de.name, argv[i], DIRSIZ);\n    iappend(rootino, &de, sizeof(de));\n\n    while((cc = read(fd, buf, sizeof(buf))) > 0)\n      iappend(inum, buf, cc);\n\n    close(fd);\n  }\n\n  // fix size of root inode dir\n  rinode(rootino, &din);\n  off = xint(din.size);\n  off = ((off/BSIZE) + 1) * BSIZE;\n  din.size = xint(off);\n  winode(rootino, &din);\n\n  balloc(freeblock);\n\n  exit(0);\n}\n\nvoid\nwsect(uint sec, void *buf)\n{\n  if(lseek(fsfd, sec * BSIZE, 0) != sec * BSIZE){\n    perror(\"lseek\");\n    exit(1);\n  }\n  if(write(fsfd, buf, BSIZE) != BSIZE){\n    perror(\"write\");\n    exit(1);\n  }\n}\n\nvoid\nwinode(uint inum, struct dinode *ip)\n{\n  char buf[BSIZE];\n  uint bn;\n  struct dinode *dip;\n\n  bn = IBLOCK(inum, sb);\n  rsect(bn, buf);\n  dip = ((struct dinode*)buf) + (inum % IPB);\n  *dip = *ip;\n  wsect(bn, buf);\n}\n\nvoid\nrinode(uint inum, struct dinode *ip)\n{\n  char buf[BSIZE];\n  uint bn;\n  struct dinode *dip;\n\n  bn = IBLOCK(inum, sb);\n  rsect(bn, buf);\n  dip = ((struct dinode*)buf) + (inum % IPB);\n  *ip = *dip;\n}\n\nvoid\nrsect(uint sec, void *buf)\n{\n  if(lseek(fsfd, sec * BSIZE, 0) != sec * BSIZE){\n    perror(\"lseek\");\n    exit(1);\n  }\n  if(read(fsfd, buf, BSIZE) != BSIZE){\n    perror(\"read\");\n    exit(1);\n  }\n}\n\nuint\nialloc(ushort type)\n{\n  uint inum = freeinode++;\n  struct dinode din;\n\n  bzero(&din, sizeof(din));\n  din.type = xshort(type);\n  din.nlink = xshort(1);\n  din.size = xint(0);\n  winode(inum, &din);\n  return inum;\n}\n\nvoid\nballoc(int used)\n{\n  uchar buf[BSIZE];\n  int i;\n\n  printf(\"balloc: first %d blocks have been allocated\\n\", used);\n  assert(used < BSIZE*8);\n  bzero(buf, BSIZE);\n  for(i = 0; i < used; i++){\n    buf[i/8] = buf[i/8] | (0x1 << (i%8));\n  }\n  printf(\"balloc: write bitmap block at sector %d\\n\", sb.bmapstart);\n  wsect(sb.bmapstart, buf);\n}\n\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\nvoid\niappend(uint inum, void *xp, int n)\n{\n  char *p = (char*)xp;\n  uint fbn, off, n1;\n  struct dinode din;\n  char buf[BSIZE];\n  uint indirect[NINDIRECT];\n  uint x;\n\n  rinode(inum, &din);\n  off = xint(din.size);\n  // printf(\"append inum %d at off %d sz %d\\n\", inum, off, n);\n  while(n > 0){\n    fbn = off / BSIZE;\n    assert(fbn < MAXFILE);\n    if(fbn < NDIRECT){\n      if(xint(din.addrs[fbn]) == 0){\n        din.addrs[fbn] = xint(freeblock++);\n      }\n      x = xint(din.addrs[fbn]);\n    } else {\n      if(xint(din.addrs[NDIRECT]) == 0){\n        din.addrs[NDIRECT] = xint(freeblock++);\n      }\n      rsect(xint(din.addrs[NDIRECT]), (char*)indirect);\n      if(indirect[fbn - NDIRECT] == 0){\n        indirect[fbn - NDIRECT] = xint(freeblock++);\n        wsect(xint(din.addrs[NDIRECT]), (char*)indirect);\n      }\n      x = xint(indirect[fbn-NDIRECT]);\n    }\n    n1 = min(n, (fbn + 1) * BSIZE - off);\n    rsect(x, buf);\n    bcopy(p, buf + off - (fbn * BSIZE), n1);\n    wsect(x, buf);\n    n -= n1;\n    off += n1;\n    p += n1;\n  }\n  din.size = xint(off);\n  winode(inum, &din);\n}\n"
  },
  {
    "path": "mmu.h",
    "content": "// This file contains definitions for the\n// x86 memory management unit (MMU).\n\n// Eflags register\n#define FL_IF           0x00000200      // Interrupt Enable\n\n// Control Register flags\n#define CR0_PE          0x00000001      // Protection Enable\n#define CR0_WP          0x00010000      // Write Protect\n#define CR0_PG          0x80000000      // Paging\n\n#define CR4_PSE         0x00000010      // Page size extension\n\n// various segment selectors.\n#define SEG_KCODE 1  // kernel code\n#define SEG_KDATA 2  // kernel data+stack\n#define SEG_UCODE 3  // user code\n#define SEG_UDATA 4  // user data+stack\n#define SEG_TSS   5  // this process's task state\n\n// cpu->gdt[NSEGS] holds the above segments.\n#define NSEGS     6\n\n#ifndef __ASSEMBLER__\n// Segment Descriptor\nstruct segdesc {\n  uint lim_15_0 : 16;  // Low bits of segment limit\n  uint base_15_0 : 16; // Low bits of segment base address\n  uint base_23_16 : 8; // Middle bits of segment base address\n  uint type : 4;       // Segment type (see STS_ constants)\n  uint s : 1;          // 0 = system, 1 = application\n  uint dpl : 2;        // Descriptor Privilege Level\n  uint p : 1;          // Present\n  uint lim_19_16 : 4;  // High bits of segment limit\n  uint avl : 1;        // Unused (available for software use)\n  uint rsv1 : 1;       // Reserved\n  uint db : 1;         // 0 = 16-bit segment, 1 = 32-bit segment\n  uint g : 1;          // Granularity: limit scaled by 4K when set\n  uint base_31_24 : 8; // High bits of segment base address\n};\n\n// Normal segment\n#define SEG(type, base, lim, dpl) (struct segdesc)    \\\n{ ((lim) >> 12) & 0xffff, (uint)(base) & 0xffff,      \\\n  ((uint)(base) >> 16) & 0xff, type, 1, dpl, 1,       \\\n  (uint)(lim) >> 28, 0, 0, 1, 1, (uint)(base) >> 24 }\n#define SEG16(type, base, lim, dpl) (struct segdesc)  \\\n{ (lim) & 0xffff, (uint)(base) & 0xffff,              \\\n  ((uint)(base) >> 16) & 0xff, type, 1, dpl, 1,       \\\n  (uint)(lim) >> 16, 0, 0, 1, 0, (uint)(base) >> 24 }\n#endif\n\n#define DPL_USER    0x3     // User DPL\n\n// Application segment type bits\n#define STA_X       0x8     // Executable segment\n#define STA_W       0x2     // Writeable (non-executable segments)\n#define STA_R       0x2     // Readable (executable segments)\n\n// System segment type bits\n#define STS_T32A    0x9     // Available 32-bit TSS\n#define STS_IG32    0xE     // 32-bit Interrupt Gate\n#define STS_TG32    0xF     // 32-bit Trap Gate\n\n// A virtual address 'la' has a three-part structure as follows:\n//\n// +--------10------+-------10-------+---------12----------+\n// | Page Directory |   Page Table   | Offset within Page  |\n// |      Index     |      Index     |                     |\n// +----------------+----------------+---------------------+\n//  \\--- PDX(va) --/ \\--- PTX(va) --/\n\n// page directory index\n#define PDX(va)         (((uint)(va) >> PDXSHIFT) & 0x3FF)\n\n// page table index\n#define PTX(va)         (((uint)(va) >> PTXSHIFT) & 0x3FF)\n\n// construct virtual address from indexes and offset\n#define PGADDR(d, t, o) ((uint)((d) << PDXSHIFT | (t) << PTXSHIFT | (o)))\n\n// Page directory and page table constants.\n#define NPDENTRIES      1024    // # directory entries per page directory\n#define NPTENTRIES      1024    // # PTEs per page table\n#define PGSIZE          4096    // bytes mapped by a page\n\n#define PTXSHIFT        12      // offset of PTX in a linear address\n#define PDXSHIFT        22      // offset of PDX in a linear address\n\n#define PGROUNDUP(sz)  (((sz)+PGSIZE-1) & ~(PGSIZE-1))\n#define PGROUNDDOWN(a) (((a)) & ~(PGSIZE-1))\n\n// Page table/directory entry flags.\n#define PTE_P           0x001   // Present\n#define PTE_W           0x002   // Writeable\n#define PTE_U           0x004   // User\n#define PTE_PS          0x080   // Page Size\n\n// Address in page table or page directory entry\n#define PTE_ADDR(pte)   ((uint)(pte) & ~0xFFF)\n#define PTE_FLAGS(pte)  ((uint)(pte) &  0xFFF)\n\n#ifndef __ASSEMBLER__\ntypedef uint pte_t;\n\n// Task state segment format\nstruct taskstate {\n  uint link;         // Old ts selector\n  uint esp0;         // Stack pointers and segment selectors\n  ushort ss0;        //   after an increase in privilege level\n  ushort padding1;\n  uint *esp1;\n  ushort ss1;\n  ushort padding2;\n  uint *esp2;\n  ushort ss2;\n  ushort padding3;\n  void *cr3;         // Page directory base\n  uint *eip;         // Saved state from last task switch\n  uint eflags;\n  uint eax;          // More saved state (registers)\n  uint ecx;\n  uint edx;\n  uint ebx;\n  uint *esp;\n  uint *ebp;\n  uint esi;\n  uint edi;\n  ushort es;         // Even more saved state (segment selectors)\n  ushort padding4;\n  ushort cs;\n  ushort padding5;\n  ushort ss;\n  ushort padding6;\n  ushort ds;\n  ushort padding7;\n  ushort fs;\n  ushort padding8;\n  ushort gs;\n  ushort padding9;\n  ushort ldt;\n  ushort padding10;\n  ushort t;          // Trap on task switch\n  ushort iomb;       // I/O map base address\n};\n\n// Gate descriptors for interrupts and traps\nstruct gatedesc {\n  uint off_15_0 : 16;   // low 16 bits of offset in segment\n  uint cs : 16;         // code segment selector\n  uint args : 5;        // # args, 0 for interrupt/trap gates\n  uint rsv1 : 3;        // reserved(should be zero I guess)\n  uint type : 4;        // type(STS_{IG32,TG32})\n  uint s : 1;           // must be 0 (system)\n  uint dpl : 2;         // descriptor(meaning new) privilege level\n  uint p : 1;           // Present\n  uint off_31_16 : 16;  // high bits of offset in segment\n};\n\n// Set up a normal interrupt/trap gate descriptor.\n// - istrap: 1 for a trap (= exception) gate, 0 for an interrupt gate.\n//   interrupt gate clears FL_IF, trap gate leaves FL_IF alone\n// - sel: Code segment selector for interrupt/trap handler\n// - off: Offset in code segment for interrupt/trap handler\n// - dpl: Descriptor Privilege Level -\n//        the privilege level required for software to invoke\n//        this interrupt/trap gate explicitly using an int instruction.\n#define SETGATE(gate, istrap, sel, off, d)                \\\n{                                                         \\\n  (gate).off_15_0 = (uint)(off) & 0xffff;                \\\n  (gate).cs = (sel);                                      \\\n  (gate).args = 0;                                        \\\n  (gate).rsv1 = 0;                                        \\\n  (gate).type = (istrap) ? STS_TG32 : STS_IG32;           \\\n  (gate).s = 0;                                           \\\n  (gate).dpl = (d);                                       \\\n  (gate).p = 1;                                           \\\n  (gate).off_31_16 = (uint)(off) >> 16;                  \\\n}\n\n#endif\n"
  },
  {
    "path": "mp.c",
    "content": "// Multiprocessor support\n// Search memory for MP description structures.\n// http://developer.intel.com/design/pentium/datashts/24201606.pdf\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mp.h\"\n#include \"x86.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n\nstruct cpu cpus[NCPU];\nint ncpu;\nuchar ioapicid;\n\nstatic uchar\nsum(uchar *addr, int len)\n{\n  int i, sum;\n\n  sum = 0;\n  for(i=0; i<len; i++)\n    sum += addr[i];\n  return sum;\n}\n\n// Look for an MP structure in the len bytes at addr.\nstatic struct mp*\nmpsearch1(uint a, int len)\n{\n  uchar *e, *p, *addr;\n\n  addr = P2V(a);\n  e = addr+len;\n  for(p = addr; p < e; p += sizeof(struct mp))\n    if(memcmp(p, \"_MP_\", 4) == 0 && sum(p, sizeof(struct mp)) == 0)\n      return (struct mp*)p;\n  return 0;\n}\n\n// Search for the MP Floating Pointer Structure, which according to the\n// spec is in one of the following three locations:\n// 1) in the first KB of the EBDA;\n// 2) in the last KB of system base memory;\n// 3) in the BIOS ROM between 0xE0000 and 0xFFFFF.\nstatic struct mp*\nmpsearch(void)\n{\n  uchar *bda;\n  uint p;\n  struct mp *mp;\n\n  bda = (uchar *) P2V(0x400);\n  if((p = ((bda[0x0F]<<8)| bda[0x0E]) << 4)){\n    if((mp = mpsearch1(p, 1024)))\n      return mp;\n  } else {\n    p = ((bda[0x14]<<8)|bda[0x13])*1024;\n    if((mp = mpsearch1(p-1024, 1024)))\n      return mp;\n  }\n  return mpsearch1(0xF0000, 0x10000);\n}\n\n// Search for an MP configuration table.  For now,\n// don't accept the default configurations (physaddr == 0).\n// Check for correct signature, calculate the checksum and,\n// if correct, check the version.\n// To do: check extended table checksum.\nstatic struct mpconf*\nmpconfig(struct mp **pmp)\n{\n  struct mpconf *conf;\n  struct mp *mp;\n\n  if((mp = mpsearch()) == 0 || mp->physaddr == 0)\n    return 0;\n  conf = (struct mpconf*) P2V((uint) mp->physaddr);\n  if(memcmp(conf, \"PCMP\", 4) != 0)\n    return 0;\n  if(conf->version != 1 && conf->version != 4)\n    return 0;\n  if(sum((uchar*)conf, conf->length) != 0)\n    return 0;\n  *pmp = mp;\n  return conf;\n}\n\nvoid\nmpinit(void)\n{\n  uchar *p, *e;\n  int ismp;\n  struct mp *mp;\n  struct mpconf *conf;\n  struct mpproc *proc;\n  struct mpioapic *ioapic;\n\n  if((conf = mpconfig(&mp)) == 0)\n    panic(\"Expect to run on an SMP\");\n  ismp = 1;\n  lapic = (uint*)conf->lapicaddr;\n  for(p=(uchar*)(conf+1), e=(uchar*)conf+conf->length; p<e; ){\n    switch(*p){\n    case MPPROC:\n      proc = (struct mpproc*)p;\n      if(ncpu < NCPU) {\n        cpus[ncpu].apicid = proc->apicid;  // apicid may differ from ncpu\n        ncpu++;\n      }\n      p += sizeof(struct mpproc);\n      continue;\n    case MPIOAPIC:\n      ioapic = (struct mpioapic*)p;\n      ioapicid = ioapic->apicno;\n      p += sizeof(struct mpioapic);\n      continue;\n    case MPBUS:\n    case MPIOINTR:\n    case MPLINTR:\n      p += 8;\n      continue;\n    default:\n      ismp = 0;\n      break;\n    }\n  }\n  if(!ismp)\n    panic(\"Didn't find a suitable machine\");\n\n  if(mp->imcrp){\n    // Bochs doesn't support IMCR, so this doesn't run on Bochs.\n    // But it would on real hardware.\n    outb(0x22, 0x70);   // Select IMCR\n    outb(0x23, inb(0x23) | 1);  // Mask external interrupts.\n  }\n}\n"
  },
  {
    "path": "mp.h",
    "content": "// See MultiProcessor Specification Version 1.[14]\n\nstruct mp {             // floating pointer\n  uchar signature[4];           // \"_MP_\"\n  void *physaddr;               // phys addr of MP config table\n  uchar length;                 // 1\n  uchar specrev;                // [14]\n  uchar checksum;               // all bytes must add up to 0\n  uchar type;                   // MP system config type\n  uchar imcrp;\n  uchar reserved[3];\n};\n\nstruct mpconf {         // configuration table header\n  uchar signature[4];           // \"PCMP\"\n  ushort length;                // total table length\n  uchar version;                // [14]\n  uchar checksum;               // all bytes must add up to 0\n  uchar product[20];            // product id\n  uint *oemtable;               // OEM table pointer\n  ushort oemlength;             // OEM table length\n  ushort entry;                 // entry count\n  uint *lapicaddr;              // address of local APIC\n  ushort xlength;               // extended table length\n  uchar xchecksum;              // extended table checksum\n  uchar reserved;\n};\n\nstruct mpproc {         // processor table entry\n  uchar type;                   // entry type (0)\n  uchar apicid;                 // local APIC id\n  uchar version;                // local APIC verison\n  uchar flags;                  // CPU flags\n    #define MPBOOT 0x02           // This proc is the bootstrap processor.\n  uchar signature[4];           // CPU signature\n  uint feature;                 // feature flags from CPUID instruction\n  uchar reserved[8];\n};\n\nstruct mpioapic {       // I/O APIC table entry\n  uchar type;                   // entry type (2)\n  uchar apicno;                 // I/O APIC id\n  uchar version;                // I/O APIC version\n  uchar flags;                  // I/O APIC flags\n  uint *addr;                  // I/O APIC address\n};\n\n// Table entry types\n#define MPPROC    0x00  // One per processor\n#define MPBUS     0x01  // One per bus\n#define MPIOAPIC  0x02  // One per I/O APIC\n#define MPIOINTR  0x03  // One per bus interrupt source\n#define MPLINTR   0x04  // One per system interrupt source\n\n//PAGEBREAK!\n// Blank page.\n"
  },
  {
    "path": "param.h",
    "content": "#define NPROC        64  // maximum number of processes\n#define KSTACKSIZE 4096  // size of per-process kernel stack\n#define NCPU          8  // maximum number of CPUs\n#define NOFILE       16  // open files per process\n#define NFILE       100  // open files per system\n#define NINODE       50  // maximum number of active i-nodes\n#define NDEV         10  // maximum major device number\n#define ROOTDEV       1  // device number of file system root disk\n#define MAXARG       32  // max exec arguments\n#define MAXOPBLOCKS  10  // max # of blocks any FS op writes\n#define LOGSIZE      (MAXOPBLOCKS*3)  // max data blocks in on-disk log\n#define NBUF         (MAXOPBLOCKS*3)  // size of disk block cache\n#define FSSIZE       1000  // size of file system in blocks\n\n"
  },
  {
    "path": "picirq.c",
    "content": "#include \"types.h\"\n#include \"x86.h\"\n#include \"traps.h\"\n\n// I/O Addresses of the two programmable interrupt controllers\n#define IO_PIC1         0x20    // Master (IRQs 0-7)\n#define IO_PIC2         0xA0    // Slave (IRQs 8-15)\n\n// Don't use the 8259A interrupt controllers.  Xv6 assumes SMP hardware.\nvoid\npicinit(void)\n{\n  // mask all interrupts\n  outb(IO_PIC1+1, 0xFF);\n  outb(IO_PIC2+1, 0xFF);\n}\n\n//PAGEBREAK!\n// Blank page.\n"
  },
  {
    "path": "pipe.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"fs.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"file.h\"\n\n#define PIPESIZE 512\n\nstruct pipe {\n  struct spinlock lock;\n  char data[PIPESIZE];\n  uint nread;     // number of bytes read\n  uint nwrite;    // number of bytes written\n  int readopen;   // read fd is still open\n  int writeopen;  // write fd is still open\n};\n\nint\npipealloc(struct file **f0, struct file **f1)\n{\n  struct pipe *p;\n\n  p = 0;\n  *f0 = *f1 = 0;\n  if((*f0 = filealloc()) == 0 || (*f1 = filealloc()) == 0)\n    goto bad;\n  if((p = (struct pipe*)kalloc()) == 0)\n    goto bad;\n  p->readopen = 1;\n  p->writeopen = 1;\n  p->nwrite = 0;\n  p->nread = 0;\n  initlock(&p->lock, \"pipe\");\n  (*f0)->type = FD_PIPE;\n  (*f0)->readable = 1;\n  (*f0)->writable = 0;\n  (*f0)->pipe = p;\n  (*f1)->type = FD_PIPE;\n  (*f1)->readable = 0;\n  (*f1)->writable = 1;\n  (*f1)->pipe = p;\n  return 0;\n\n//PAGEBREAK: 20\n bad:\n  if(p)\n    kfree((char*)p);\n  if(*f0)\n    fileclose(*f0);\n  if(*f1)\n    fileclose(*f1);\n  return -1;\n}\n\nvoid\npipeclose(struct pipe *p, int writable)\n{\n  acquire(&p->lock);\n  if(writable){\n    p->writeopen = 0;\n    wakeup(&p->nread);\n  } else {\n    p->readopen = 0;\n    wakeup(&p->nwrite);\n  }\n  if(p->readopen == 0 && p->writeopen == 0){\n    release(&p->lock);\n    kfree((char*)p);\n  } else\n    release(&p->lock);\n}\n\n//PAGEBREAK: 40\nint\npipewrite(struct pipe *p, char *addr, int n)\n{\n  int i;\n\n  acquire(&p->lock);\n  for(i = 0; i < n; i++){\n    while(p->nwrite == p->nread + PIPESIZE){  //DOC: pipewrite-full\n      if(p->readopen == 0 || myproc()->killed){\n        release(&p->lock);\n        return -1;\n      }\n      wakeup(&p->nread);\n      sleep(&p->nwrite, &p->lock);  //DOC: pipewrite-sleep\n    }\n    p->data[p->nwrite++ % PIPESIZE] = addr[i];\n  }\n  wakeup(&p->nread);  //DOC: pipewrite-wakeup1\n  release(&p->lock);\n  return n;\n}\n\nint\npiperead(struct pipe *p, char *addr, int n)\n{\n  int i;\n\n  acquire(&p->lock);\n  while(p->nread == p->nwrite && p->writeopen){  //DOC: pipe-empty\n    if(myproc()->killed){\n      release(&p->lock);\n      return -1;\n    }\n    sleep(&p->nread, &p->lock); //DOC: piperead-sleep\n  }\n  for(i = 0; i < n; i++){  //DOC: piperead-copy\n    if(p->nread == p->nwrite)\n      break;\n    addr[i] = p->data[p->nread++ % PIPESIZE];\n  }\n  wakeup(&p->nwrite);  //DOC: piperead-wakeup\n  release(&p->lock);\n  return i;\n}\n"
  },
  {
    "path": "pr.pl",
    "content": "#!/usr/bin/perl\n\nuse POSIX qw(strftime);\n\nif($ARGV[0] eq \"-h\"){\n\tshift @ARGV;\n\t$h = $ARGV[0];\n\tshift @ARGV;\n}else{\n\t$h = $ARGV[0];\n}\n\n$page = 0;\n$now = strftime \"%b %e %H:%M %Y\", localtime;\n\n@lines = <>;\nfor($i=0; $i<@lines; $i+=50){\n\tprint \"\\n\\n\";\n\t++$page;\n\tprint \"$now  $h  Page $page\\n\";\n\tprint \"\\n\\n\";\n\tfor($j=$i; $j<@lines && $j<$i +50; $j++){\n\t\t$lines[$j] =~ s!//DOC.*!!;\n\t\tprint $lines[$j];\n\t}\n\tfor(; $j<$i+50; $j++){\n\t\tprint \"\\n\";\n\t}\n\t$sheet = \"\";\n\tif($lines[$i] =~ /^([0-9][0-9])[0-9][0-9] /){\n\t\t$sheet = \"Sheet $1\";\n\t}\n\tprint \"\\n\\n\";\n\tprint \"$sheet\\n\";\n\tprint \"\\n\\n\";\n}\n"
  },
  {
    "path": "printf.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nstatic void\nputc(int fd, char c)\n{\n  write(fd, &c, 1);\n}\n\nstatic void\nprintint(int fd, int xx, int base, int sgn)\n{\n  static char digits[] = \"0123456789ABCDEF\";\n  char buf[16];\n  int i, neg;\n  uint x;\n\n  neg = 0;\n  if(sgn && xx < 0){\n    neg = 1;\n    x = -xx;\n  } else {\n    x = xx;\n  }\n\n  i = 0;\n  do{\n    buf[i++] = digits[x % base];\n  }while((x /= base) != 0);\n  if(neg)\n    buf[i++] = '-';\n\n  while(--i >= 0)\n    putc(fd, buf[i]);\n}\n\n// Print to the given fd. Only understands %d, %x, %p, %s.\nvoid\nprintf(int fd, const char *fmt, ...)\n{\n  char *s;\n  int c, i, state;\n  uint *ap;\n\n  state = 0;\n  ap = (uint*)(void*)&fmt + 1;\n  for(i = 0; fmt[i]; i++){\n    c = fmt[i] & 0xff;\n    if(state == 0){\n      if(c == '%'){\n        state = '%';\n      } else {\n        putc(fd, c);\n      }\n    } else if(state == '%'){\n      if(c == 'd'){\n        printint(fd, *ap, 10, 1);\n        ap++;\n      } else if(c == 'x' || c == 'p'){\n        printint(fd, *ap, 16, 0);\n        ap++;\n      } else if(c == 's'){\n        s = (char*)*ap;\n        ap++;\n        if(s == 0)\n          s = \"(null)\";\n        while(*s != 0){\n          putc(fd, *s);\n          s++;\n        }\n      } else if(c == 'c'){\n        putc(fd, *ap);\n        ap++;\n      } else if(c == '%'){\n        putc(fd, c);\n      } else {\n        // Unknown % sequence.  Print it to draw attention.\n        putc(fd, '%');\n        putc(fd, c);\n      }\n      state = 0;\n    }\n  }\n}\n"
  },
  {
    "path": "printpcs",
    "content": "#!/bin/sh\n\n# Decode the symbols from a panic EIP list\n\n# Find a working addr2line\nfor p in i386-jos-elf-addr2line addr2line; do\n    if which $p 2>&1 >/dev/null && \\\n       $p -h 2>&1 | grep -q '\\belf32-i386\\b'; then\n        break\n    fi\ndone\n\n# Enable as much pretty-printing as this addr2line can do\n$p $($p -h | grep ' -[aipsf] ' | awk '{print $1}') -e kernel \"$@\"\n"
  },
  {
    "path": "proc.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"x86.h\"\n#include \"proc.h\"\n#include \"spinlock.h\"\n\nstruct {\n  struct spinlock lock;\n  struct proc proc[NPROC];\n} ptable;\n\nstatic struct proc *initproc;\n\nint nextpid = 1;\nextern void forkret(void);\nextern void trapret(void);\n\nstatic void wakeup1(void *chan);\n\nvoid\npinit(void)\n{\n  initlock(&ptable.lock, \"ptable\");\n}\n\n// Must be called with interrupts disabled\nint\ncpuid() {\n  return mycpu()-cpus;\n}\n\n// Must be called with interrupts disabled to avoid the caller being\n// rescheduled between reading lapicid and running through the loop.\nstruct cpu*\nmycpu(void)\n{\n  int apicid, i;\n  \n  if(readeflags()&FL_IF)\n    panic(\"mycpu called with interrupts enabled\\n\");\n  \n  apicid = lapicid();\n  // APIC IDs are not guaranteed to be contiguous. Maybe we should have\n  // a reverse map, or reserve a register to store &cpus[i].\n  for (i = 0; i < ncpu; ++i) {\n    if (cpus[i].apicid == apicid)\n      return &cpus[i];\n  }\n  panic(\"unknown apicid\\n\");\n}\n\n// Disable interrupts so that we are not rescheduled\n// while reading proc from the cpu structure\nstruct proc*\nmyproc(void) {\n  struct cpu *c;\n  struct proc *p;\n  pushcli();\n  c = mycpu();\n  p = c->proc;\n  popcli();\n  return p;\n}\n\n//PAGEBREAK: 32\n// Look in the process table for an UNUSED proc.\n// If found, change state to EMBRYO and initialize\n// state required to run in the kernel.\n// Otherwise return 0.\nstatic struct proc*\nallocproc(void)\n{\n  struct proc *p;\n  char *sp;\n\n  acquire(&ptable.lock);\n\n  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)\n    if(p->state == UNUSED)\n      goto found;\n\n  release(&ptable.lock);\n  return 0;\n\nfound:\n  p->state = EMBRYO;\n  p->pid = nextpid++;\n\n  release(&ptable.lock);\n\n  // Allocate kernel stack.\n  if((p->kstack = kalloc()) == 0){\n    p->state = UNUSED;\n    return 0;\n  }\n  sp = p->kstack + KSTACKSIZE;\n\n  // Leave room for trap frame.\n  sp -= sizeof *p->tf;\n  p->tf = (struct trapframe*)sp;\n\n  // Set up new context to start executing at forkret,\n  // which returns to trapret.\n  sp -= 4;\n  *(uint*)sp = (uint)trapret;\n\n  sp -= sizeof *p->context;\n  p->context = (struct context*)sp;\n  memset(p->context, 0, sizeof *p->context);\n  p->context->eip = (uint)forkret;\n\n  return p;\n}\n\n//PAGEBREAK: 32\n// Set up first user process.\nvoid\nuserinit(void)\n{\n  struct proc *p;\n  extern char _binary_initcode_start[], _binary_initcode_size[];\n\n  p = allocproc();\n  \n  initproc = p;\n  if((p->pgdir = setupkvm()) == 0)\n    panic(\"userinit: out of memory?\");\n  inituvm(p->pgdir, _binary_initcode_start, (int)_binary_initcode_size);\n  p->sz = PGSIZE;\n  memset(p->tf, 0, sizeof(*p->tf));\n  p->tf->cs = (SEG_UCODE << 3) | DPL_USER;\n  p->tf->ds = (SEG_UDATA << 3) | DPL_USER;\n  p->tf->es = p->tf->ds;\n  p->tf->ss = p->tf->ds;\n  p->tf->eflags = FL_IF;\n  p->tf->esp = PGSIZE;\n  p->tf->eip = 0;  // beginning of initcode.S\n\n  safestrcpy(p->name, \"initcode\", sizeof(p->name));\n  p->cwd = namei(\"/\");\n\n  // this assignment to p->state lets other cores\n  // run this process. the acquire forces the above\n  // writes to be visible, and the lock is also needed\n  // because the assignment might not be atomic.\n  acquire(&ptable.lock);\n\n  p->state = RUNNABLE;\n\n  release(&ptable.lock);\n}\n\n// Grow current process's memory by n bytes.\n// Return 0 on success, -1 on failure.\nint\ngrowproc(int n)\n{\n  uint sz;\n  struct proc *curproc = myproc();\n\n  sz = curproc->sz;\n  if(n > 0){\n    if((sz = allocuvm(curproc->pgdir, sz, sz + n)) == 0)\n      return -1;\n  } else if(n < 0){\n    if((sz = deallocuvm(curproc->pgdir, sz, sz + n)) == 0)\n      return -1;\n  }\n  curproc->sz = sz;\n  switchuvm(curproc);\n  return 0;\n}\n\n// Create a new process copying p as the parent.\n// Sets up stack to return as if from system call.\n// Caller must set state of returned proc to RUNNABLE.\nint\nfork(void)\n{\n  int i, pid;\n  struct proc *np;\n  struct proc *curproc = myproc();\n\n  // Allocate process.\n  if((np = allocproc()) == 0){\n    return -1;\n  }\n\n  // Copy process state from proc.\n  if((np->pgdir = copyuvm(curproc->pgdir, curproc->sz)) == 0){\n    kfree(np->kstack);\n    np->kstack = 0;\n    np->state = UNUSED;\n    return -1;\n  }\n  np->sz = curproc->sz;\n  np->parent = curproc;\n  *np->tf = *curproc->tf;\n\n  // Clear %eax so that fork returns 0 in the child.\n  np->tf->eax = 0;\n\n  for(i = 0; i < NOFILE; i++)\n    if(curproc->ofile[i])\n      np->ofile[i] = filedup(curproc->ofile[i]);\n  np->cwd = idup(curproc->cwd);\n\n  safestrcpy(np->name, curproc->name, sizeof(curproc->name));\n\n  pid = np->pid;\n\n  acquire(&ptable.lock);\n\n  np->state = RUNNABLE;\n\n  release(&ptable.lock);\n\n  return pid;\n}\n\n// Exit the current process.  Does not return.\n// An exited process remains in the zombie state\n// until its parent calls wait() to find out it exited.\nvoid\nexit(void)\n{\n  struct proc *curproc = myproc();\n  struct proc *p;\n  int fd;\n\n  if(curproc == initproc)\n    panic(\"init exiting\");\n\n  // Close all open files.\n  for(fd = 0; fd < NOFILE; fd++){\n    if(curproc->ofile[fd]){\n      fileclose(curproc->ofile[fd]);\n      curproc->ofile[fd] = 0;\n    }\n  }\n\n  begin_op();\n  iput(curproc->cwd);\n  end_op();\n  curproc->cwd = 0;\n\n  acquire(&ptable.lock);\n\n  // Parent might be sleeping in wait().\n  wakeup1(curproc->parent);\n\n  // Pass abandoned children to init.\n  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){\n    if(p->parent == curproc){\n      p->parent = initproc;\n      if(p->state == ZOMBIE)\n        wakeup1(initproc);\n    }\n  }\n\n  // Jump into the scheduler, never to return.\n  curproc->state = ZOMBIE;\n  sched();\n  panic(\"zombie exit\");\n}\n\n// Wait for a child process to exit and return its pid.\n// Return -1 if this process has no children.\nint\nwait(void)\n{\n  struct proc *p;\n  int havekids, pid;\n  struct proc *curproc = myproc();\n  \n  acquire(&ptable.lock);\n  for(;;){\n    // Scan through table looking for exited children.\n    havekids = 0;\n    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){\n      if(p->parent != curproc)\n        continue;\n      havekids = 1;\n      if(p->state == ZOMBIE){\n        // Found one.\n        pid = p->pid;\n        kfree(p->kstack);\n        p->kstack = 0;\n        freevm(p->pgdir);\n        p->pid = 0;\n        p->parent = 0;\n        p->name[0] = 0;\n        p->killed = 0;\n        p->state = UNUSED;\n        release(&ptable.lock);\n        return pid;\n      }\n    }\n\n    // No point waiting if we don't have any children.\n    if(!havekids || curproc->killed){\n      release(&ptable.lock);\n      return -1;\n    }\n\n    // Wait for children to exit.  (See wakeup1 call in proc_exit.)\n    sleep(curproc, &ptable.lock);  //DOC: wait-sleep\n  }\n}\n\n//PAGEBREAK: 42\n// Per-CPU process scheduler.\n// Each CPU calls scheduler() after setting itself up.\n// Scheduler never returns.  It loops, doing:\n//  - choose a process to run\n//  - swtch to start running that process\n//  - eventually that process transfers control\n//      via swtch back to the scheduler.\nvoid\nscheduler(void)\n{\n  struct proc *p;\n  struct cpu *c = mycpu();\n  c->proc = 0;\n  \n  for(;;){\n    // Enable interrupts on this processor.\n    sti();\n\n    // Loop over process table looking for process to run.\n    acquire(&ptable.lock);\n    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){\n      if(p->state != RUNNABLE)\n        continue;\n\n      // Switch to chosen process.  It is the process's job\n      // to release ptable.lock and then reacquire it\n      // before jumping back to us.\n      c->proc = p;\n      switchuvm(p);\n      p->state = RUNNING;\n\n      swtch(&(c->scheduler), p->context);\n      switchkvm();\n\n      // Process is done running for now.\n      // It should have changed its p->state before coming back.\n      c->proc = 0;\n    }\n    release(&ptable.lock);\n\n  }\n}\n\n// Enter scheduler.  Must hold only ptable.lock\n// and have changed proc->state. Saves and restores\n// intena because intena is a property of this\n// kernel thread, not this CPU. It should\n// be proc->intena and proc->ncli, but that would\n// break in the few places where a lock is held but\n// there's no process.\nvoid\nsched(void)\n{\n  int intena;\n  struct proc *p = myproc();\n\n  if(!holding(&ptable.lock))\n    panic(\"sched ptable.lock\");\n  if(mycpu()->ncli != 1)\n    panic(\"sched locks\");\n  if(p->state == RUNNING)\n    panic(\"sched running\");\n  if(readeflags()&FL_IF)\n    panic(\"sched interruptible\");\n  intena = mycpu()->intena;\n  swtch(&p->context, mycpu()->scheduler);\n  mycpu()->intena = intena;\n}\n\n// Give up the CPU for one scheduling round.\nvoid\nyield(void)\n{\n  acquire(&ptable.lock);  //DOC: yieldlock\n  myproc()->state = RUNNABLE;\n  sched();\n  release(&ptable.lock);\n}\n\n// A fork child's very first scheduling by scheduler()\n// will swtch here.  \"Return\" to user space.\nvoid\nforkret(void)\n{\n  static int first = 1;\n  // Still holding ptable.lock from scheduler.\n  release(&ptable.lock);\n\n  if (first) {\n    // Some initialization functions must be run in the context\n    // of a regular process (e.g., they call sleep), and thus cannot\n    // be run from main().\n    first = 0;\n    iinit(ROOTDEV);\n    initlog(ROOTDEV);\n  }\n\n  // Return to \"caller\", actually trapret (see allocproc).\n}\n\n// Atomically release lock and sleep on chan.\n// Reacquires lock when awakened.\nvoid\nsleep(void *chan, struct spinlock *lk)\n{\n  struct proc *p = myproc();\n  \n  if(p == 0)\n    panic(\"sleep\");\n\n  if(lk == 0)\n    panic(\"sleep without lk\");\n\n  // Must acquire ptable.lock in order to\n  // change p->state and then call sched.\n  // Once we hold ptable.lock, we can be\n  // guaranteed that we won't miss any wakeup\n  // (wakeup runs with ptable.lock locked),\n  // so it's okay to release lk.\n  if(lk != &ptable.lock){  //DOC: sleeplock0\n    acquire(&ptable.lock);  //DOC: sleeplock1\n    release(lk);\n  }\n  // Go to sleep.\n  p->chan = chan;\n  p->state = SLEEPING;\n\n  sched();\n\n  // Tidy up.\n  p->chan = 0;\n\n  // Reacquire original lock.\n  if(lk != &ptable.lock){  //DOC: sleeplock2\n    release(&ptable.lock);\n    acquire(lk);\n  }\n}\n\n//PAGEBREAK!\n// Wake up all processes sleeping on chan.\n// The ptable lock must be held.\nstatic void\nwakeup1(void *chan)\n{\n  struct proc *p;\n\n  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++)\n    if(p->state == SLEEPING && p->chan == chan)\n      p->state = RUNNABLE;\n}\n\n// Wake up all processes sleeping on chan.\nvoid\nwakeup(void *chan)\n{\n  acquire(&ptable.lock);\n  wakeup1(chan);\n  release(&ptable.lock);\n}\n\n// Kill the process with the given pid.\n// Process won't exit until it returns\n// to user space (see trap in trap.c).\nint\nkill(int pid)\n{\n  struct proc *p;\n\n  acquire(&ptable.lock);\n  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){\n    if(p->pid == pid){\n      p->killed = 1;\n      // Wake process from sleep if necessary.\n      if(p->state == SLEEPING)\n        p->state = RUNNABLE;\n      release(&ptable.lock);\n      return 0;\n    }\n  }\n  release(&ptable.lock);\n  return -1;\n}\n\n//PAGEBREAK: 36\n// Print a process listing to console.  For debugging.\n// Runs when user types ^P on console.\n// No lock to avoid wedging a stuck machine further.\nvoid\nprocdump(void)\n{\n  static char *states[] = {\n  [UNUSED]    \"unused\",\n  [EMBRYO]    \"embryo\",\n  [SLEEPING]  \"sleep \",\n  [RUNNABLE]  \"runble\",\n  [RUNNING]   \"run   \",\n  [ZOMBIE]    \"zombie\"\n  };\n  int i;\n  struct proc *p;\n  char *state;\n  uint pc[10];\n\n  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){\n    if(p->state == UNUSED)\n      continue;\n    if(p->state >= 0 && p->state < NELEM(states) && states[p->state])\n      state = states[p->state];\n    else\n      state = \"???\";\n    cprintf(\"%d %s %s\", p->pid, state, p->name);\n    if(p->state == SLEEPING){\n      getcallerpcs((uint*)p->context->ebp+2, pc);\n      for(i=0; i<10 && pc[i] != 0; i++)\n        cprintf(\" %p\", pc[i]);\n    }\n    cprintf(\"\\n\");\n  }\n}\n"
  },
  {
    "path": "proc.h",
    "content": "// Per-CPU state\nstruct cpu {\n  uchar apicid;                // Local APIC ID\n  struct context *scheduler;   // swtch() here to enter scheduler\n  struct taskstate ts;         // Used by x86 to find stack for interrupt\n  struct segdesc gdt[NSEGS];   // x86 global descriptor table\n  volatile uint started;       // Has the CPU started?\n  int ncli;                    // Depth of pushcli nesting.\n  int intena;                  // Were interrupts enabled before pushcli?\n  struct proc *proc;           // The process running on this cpu or null\n};\n\nextern struct cpu cpus[NCPU];\nextern int ncpu;\n\n//PAGEBREAK: 17\n// Saved registers for kernel context switches.\n// Don't need to save all the segment registers (%cs, etc),\n// because they are constant across kernel contexts.\n// Don't need to save %eax, %ecx, %edx, because the\n// x86 convention is that the caller has saved them.\n// Contexts are stored at the bottom of the stack they\n// describe; the stack pointer is the address of the context.\n// The layout of the context matches the layout of the stack in swtch.S\n// at the \"Switch stacks\" comment. Switch doesn't save eip explicitly,\n// but it is on the stack and allocproc() manipulates it.\nstruct context {\n  uint edi;\n  uint esi;\n  uint ebx;\n  uint ebp;\n  uint eip;\n};\n\nenum procstate { UNUSED, EMBRYO, SLEEPING, RUNNABLE, RUNNING, ZOMBIE };\n\n// Per-process state\nstruct proc {\n  uint sz;                     // Size of process memory (bytes)\n  pde_t* pgdir;                // Page table\n  char *kstack;                // Bottom of kernel stack for this process\n  enum procstate state;        // Process state\n  int pid;                     // Process ID\n  struct proc *parent;         // Parent process\n  struct trapframe *tf;        // Trap frame for current syscall\n  struct context *context;     // swtch() here to run process\n  void *chan;                  // If non-zero, sleeping on chan\n  int killed;                  // If non-zero, have been killed\n  struct file *ofile[NOFILE];  // Open files\n  struct inode *cwd;           // Current directory\n  char name[16];               // Process name (debugging)\n};\n\n// Process memory is laid out contiguously, low addresses first:\n//   text\n//   original data and bss\n//   fixed-size stack\n//   expandable heap\n"
  },
  {
    "path": "rm.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(int argc, char *argv[])\n{\n  int i;\n\n  if(argc < 2){\n    printf(2, \"Usage: rm files...\\n\");\n    exit();\n  }\n\n  for(i = 1; i < argc; i++){\n    if(unlink(argv[i]) < 0){\n      printf(2, \"rm: %s failed to delete\\n\", argv[i]);\n      break;\n    }\n  }\n\n  exit();\n}\n"
  },
  {
    "path": "runoff",
    "content": "#!/bin/sh\n\necho This script takes a minute to run.  Be patient. 1>&2\n\nLC_CTYPE=C export LC_CTYPE\n\n# pad stdin to multiple of 120 lines\npad()\n{\n\tawk '{print} END{for(; NR%120!=0; NR++) print \"\"}'\n}\n\n# create formatted (numbered) files\nmkdir -p fmt\nrm -f fmt/*\ncp README fmt\necho > fmt/blank\nfiles=`grep -v '^#' runoff.list | awk '{print $1}'`\nn=99\nfor i in $files\ndo\n\t./runoff1 -n $n $i >fmt/$i\n\tnn=`tail -1 fmt/$i | sed 's/ .*//; s/^0*//'`\n\tif [ \"x$nn\" != x ]; then\n\t\tn=$nn\n\tfi\ndone\n\n# create table of contents\ncat toc.hdr >fmt/toc\npr -e8 -t runoff.list | awk '\n/^[a-z0-9]/ {\n\ts=$0\n\tf=\"fmt/\"$1\n\tgetline<f\n\tclose(f)\n\tn=$1\n\tprintf(\"%02d %s\\n\", n/100, s);\n\tprintf(\"TOC: %04d %s\\n\", n, s) >\"fmt/tocdata\"\n\tnext\n}\n{\n\tprint\n}' | pr -3 -t >>fmt/toc\ncat toc.ftr >>fmt/toc\n\n# check for bad alignments\nperl -e '\n\t$leftwarn = 0;\n\twhile(<>){\n\t\tchomp;\n\t\ts!#.*!!;\n\t\ts!\\s+! !g;\n\t\ts! +$!!;\n\t\tnext if /^$/;\n\t\t\n\t\tif(/TOC: (\\d+) (.*)/){\n\t\t\t$toc{$2} = $1;\n\t\t\tnext;\n\t\t}\n\t\t\n\t\tif(/sheet1: (left|right)$/){\n\t\t\tprint STDERR \"assuming that sheet 1 is a $1 page.  double-check!\\n\";\n\t\t\t$left = $1 eq \"left\" ? \"13579\" : \"02468\";\n\t\t\t$right = $1 eq \"left\" ? \"02468\" : \"13579\";\n\t\t\tnext;\n\t\t}\n\t\t\n\t\tif(/even: (.*)/){\n\t\t\t$file = $1;\n\t\t\tif(!defined($toc{$file})){\n\t\t\t\tprint STDERR \"Have no toc for $file\\n\";\n\t\t\t\tnext;\n\t\t\t}\n\t\t\tif($toc{$file} =~ /^\\d\\d[^0]/){\n\t\t\t\tprint STDERR \"$file does not start on a fresh page.\\n\";\n\t\t\t}\n\t\t\tnext;\n\t\t}\n\t\t\n\t\tif(/odd: (.*)/){\n\t\t\t$file = $1;\n\t\t\tif(!defined($toc{$file})){\n\t\t\t\tprint STDERR \"Have no toc for $file\\n\";\n\t\t\t\tnext;\n\t\t\t}\n\t\t\tif($toc{$file} !~ /^\\d\\d5/){\n\t\t\t\tprint STDERR \"$file does not start on a second half page.\\n\";\n\t\t\t}\n\t\t\tnext;\n\t\t}\n\t\t\n\t\tif(/(left|right): (.*)/){\n\t\t\t$what = $1;\n\t\t\t$file = $2;\n\t\t\tif(!defined($toc{$file})){\n\t\t\t\tprint STDERR \"Have no toc for $file\\n\";\n\t\t\t\tnext;\n\t\t\t}\n\t\t\tif($what eq \"left\" && !($toc{$file} =~ /^\\d[$left][05]/)){\n\t\t\t\tprint STDERR \"$file does not start on a left page [$toc{$file}]\\n\";\n\t\t\t}\n\t\t\t# why does this not work if I inline $x in the if?\n\t\t\t$x = ($toc{$file} =~ /^\\d[$right][05]/);\n\t\t\tif($what eq \"right\" && !$x){\n\t\t\t\tprint STDERR \"$file does not start on a right page [$toc{$file}] [$x]\\n\";\n\t\t\t}\n\t\t\tnext;\n\t\t}\n\t\t\n\t\tprint STDERR \"Unknown spec: $_\\n\";\n\t}\n' fmt/tocdata runoff.spec\n\n# make definition list\ncd fmt\nperl -e '\n\twhile(<>) {\n\t\tchomp;\n\n\t\ts!//.*!!;\n\t\ts!/\\*([^*]|[*][^/])*\\*/!!g;\n\t\ts!\\s! !g;\n\t\ts! +$!!;\n\n\t\t# look for declarations like char* x;\n\t\tif (/^[0-9]+ typedef .* u(int|short|long|char);/) {\n\t\t\tnext;\n\t\t}\n\t\tif (/^[0-9]+ extern/) {\n\t\t\tnext;\n\t\t}\n\t\tif (/^[0-9]+ struct [a-zA-Z0-9_]+;/) {\n\t\t\tnext;\n\t\t}\n\t\tif (/^([0-9]+) #define +([A-za-z0-9_]+) +?\\(.*/) {\n\t\t\tprint \"$1 $2\\n\"\n\t\t}\n\t\telsif (/^([0-9]+) #define +([A-Za-z0-9_]+) +([^ ]+)/) {\n\t\t\tprint \"$1 $2 $3\\n\";\n\t\t}\n\t\telsif (/^([0-9]+) #define +([A-Za-z0-9_]+)/) {\n\t\t\tprint \"$1 $2\\n\";\n\t\t}\n\t\t\n\t\tif(/^^([0-9]+) \\.globl ([a-zA-Z0-9_]+)/){\n\t\t\t$isglobl{$2} = 1;\n\t\t}\n\t\tif(/^^([0-9]+) ([a-zA-Z0-9_]+):$/ && $isglobl{$2}){\n\t\t\tprint \"$1 $2\\n\";\n\t\t}\n\t\t\n\t\tif (/\\(/) {\n\t\t\tnext;\n\t\t}\n\n\t\tif (/^([0-9]+) (((static|struct|extern|union|enum) +)*([A-Za-z0-9_]+))( .*)? +([A-Za-z_][A-Za-z0-9_]*)(,|;|=| =)/) {\n\t\t\tprint \"$1 $7\\n\";\n\t\t}\n\t\t\n\t\telsif(/^([0-9]+) (enum|struct|union) +([A-Za-z0-9_]+) +{/){ \n\t\t\tprint \"$1 $3\\n\";\n\t\t}\n\t\t# TODO: enum members\n\t}\n' $files >defs\n\n(for i in $files\ndo\n\tcase \"$i\" in\n\t*.S)\n\t\tcat $i | sed 's;#.*;;; s;//.*;;;'\n\t\t;;\n\t*)\n\t\tcat $i | sed 's;//.*;;; s;\"([^\"\\\\]|\\\\.)*\";;;'\n\tesac\ndone\n) >alltext\n\nperl -n -e 'print if s/^([0-9]+ [a-zA-Z0-9_]+)\\(.*$/\\1/;' alltext |\n\tegrep -v ' (STUB|usage|main|if|for)$' >>defs\n#perl -n -e 'print if s/^([0-9]+) STUB\\(([a-zA-Z0-9_]+)\\)$/\\1 \\2/;' alltext \\\n#\t>>defs\n(\n>s.defs\n\n# make reference list\nfor i in `awk '{print $2}' defs | sort -f | uniq`\ndo\n\tdefs=`egrep '^[0-9]+ '$i'( |$)' defs | awk '{print $1}'`\n\techo $i $defs >>s.defs\n\tuses=`egrep -h '([^a-zA-Z_0-9])'$i'($|[^a-zA-Z_0-9])' alltext | awk '{print $1}'`\n\tif [ \"x$defs\" != \"x$uses\" ]; then\n\t\techo $i $defs\n\t\techo $uses |fmt -29 | sed 's/^/    /'\n#\telse\n#\t\techo $i defined but not used >&2\n\tfi\ndone\n) >refs\n\n# build defs list\nawk '\n{\n\tprintf(\"%04d %s\\n\", $2, $1);\n\tfor(i=3; i<=NF; i++)\n\t\tprintf(\"%04d    \\\" \\n\", $i);\n}\n' s.defs > t.defs\n\n# format the whole thing\n(\n\t../pr.pl README\n\t../pr.pl -h \"table of contents\" toc\n\t# pr -t -2 t.defs | ../pr.pl -h \"definitions\" | pad\n\tpr -t -l50 -2 refs | ../pr.pl -h \"cross-references\" | pad\n\t# pr.pl -h \"definitions\" -2 t.defs | pad\n\t# pr.pl -h \"cross-references\" -2 refs | pad\n\t../pr.pl blank  # make sheet 1 start on left page\n\t../pr.pl blank\n\tfor i in $files\n\tdo\n\t\t../pr.pl -h \"xv6/$i\" $i\n\tdone\n) | mpage -m50t50b -o -bLetter -T -t -2 -FCourier -L60 >all.ps\ngrep Pages: all.ps\n\n# if we have the nice font, use it\nnicefont=LucidaSans-Typewriter83\nif [ ! -f ../$nicefont ]\nthen\n\tif git cat-file blob font:$nicefont > ../$nicefont~; then\n\t\tmv ../$nicefont~ ../$nicefont\n\tfi\nfi\nif [ -f ../$nicefont ]\nthen\n\techo nicefont\n\t(sed 1q all.ps; cat ../$nicefont; sed \"1d; s/Courier/$nicefont/\" all.ps) >allf.ps\nelse\n\techo ugly font!\n\tcp all.ps allf.ps\nfi\nps2pdf allf.ps ../xv6.pdf\n# cd ..\n# pdftops xv6.pdf xv6.ps\n"
  },
  {
    "path": "runoff.list",
    "content": "# basic headers\ntypes.h\nparam.h\nmemlayout.h\ndefs.h\nx86.h\nasm.h\nmmu.h\nelf.h\ndate.h\n\n# entering xv6\nentry.S\nentryother.S\nmain.c\n\n# locks\nspinlock.h\nspinlock.c\n\n# processes\nvm.c\nproc.h\nproc.c\nswtch.S\nkalloc.c\n\n# system calls\ntraps.h\nvectors.pl\ntrapasm.S\ntrap.c\nsyscall.h\nsyscall.c\nsysproc.c\n\n# file system\nbuf.h\nsleeplock.h\nfcntl.h\nstat.h\nfs.h\nfile.h\nide.c\nbio.c\nsleeplock.c\nlog.c\nfs.c\nfile.c\nsysfile.c\nexec.c\n\n# pipes\npipe.c\n\n# string operations\nstring.c\n\n# low-level hardware\nmp.h\nmp.c\nlapic.c\nioapic.c\nkbd.h\nkbd.c\nconsole.c\nuart.c\n\n# user-level\ninitcode.S\nusys.S\ninit.c\nsh.c\n\n# bootloader\nbootasm.S\nbootmain.c\n\n# link\nkernel.ld\n"
  },
  {
    "path": "runoff.spec",
    "content": "# Is sheet 01 (after the TOC) a left sheet or a right sheet?\nsheet1: left\n\n# \"left\" and \"right\" specify which page of a two-page spread a file\n# must start on.  \"left\" means that a file must start on the first of\n# the two pages.  \"right\" means it must start on the second of the two\n# pages.  The file may start in either column.\n#\n# \"even\" and \"odd\" specify which column a file must start on.  \"even\"\n# means it must start in the left of the two columns (00).  \"odd\" means it\n# must start in the right of the two columns (50).\n#\n# You'd think these would be the other way around.\n\n# types.h either\n# param.h either\n# defs.h either\n# x86.h either\n# asm.h either\n# mmu.h either\n# elf.h either\n# mp.h either\n\neven: entry.S  # mild preference\neven: entryother.S  # mild preference\neven: main.c\n# mp.c don't care at all\n# even: initcode.S\n# odd: init.c\n\nleft: spinlock.h\neven: spinlock.h\n\n# This gets struct proc and allocproc on the same spread\nleft: proc.h\neven: proc.h\n\n# goal is to have two action-packed 2-page spreads,\n# one with\n#     userinit growproc fork exit wait\n# and another with\n#     scheduler sched yield forkret sleep wakeup1 wakeup\nright: proc.c   # VERY important\neven: proc.c   # VERY important\n\n# A few more action packed spreads\n# page table creation and process loading\n#     walkpgdir mappages setupkvm switch[ku]vm inituvm (loaduvm)\n# process memory management\n#     allocuvm deallocuvm freevm\nleft: vm.c\n\neven: kalloc.c  # mild preference\n\n# syscall.h either\n# trapasm.S either\n# traps.h either\n# even: trap.c\n# vectors.pl either\n# syscall.c either\n# sysproc.c either\n\n# buf.h either\n# dev.h either\n# fcntl.h either\n# stat.h either\n# file.h either\n# fs.h either\n# fsvar.h either\n# left: ide.c # mild preference\neven: ide.c\n# odd: bio.c\n\n# log.c fits nicely in a spread\neven: log.c\nleft: log.c\n\n# with fs.c starting on 2nd column of a left page, we get these 2-page spreads:\n#\tialloc iupdate iget idup ilock iunlock iput iunlockput\n#\tbmap itrunc stati readi writei\n#\tnamecmp dirlookup dirlink skipelem namex namei\n#\tfileinit filealloc filedup fileclose filestat fileread filewrite\n# starting on 2nd column of a right page is not terrible either\nodd: fs.c   # VERY important\nleft: fs.c  # mild preference\n# file.c either\n# exec.c either\n# sysfile.c either\n\n# Mild preference, but makes spreads of mp.c, lapic.c, and ioapic.c+picirq.c\neven: mp.c\nleft: mp.c\n\n# even: pipe.c  # mild preference\n# string.c either\n# left: kbd.h  # mild preference\neven: kbd.h\neven: console.c\nodd: sh.c\n\neven: bootasm.S   # mild preference\neven: bootmain.c  # mild preference\n"
  },
  {
    "path": "runoff1",
    "content": "#!/usr/bin/perl\n\n$n = 0;\n$v = 0;\nif($ARGV[0] eq \"-v\") {\n\t$v = 1;\n\tshift @ARGV;\n}\nif($ARGV[0] eq \"-n\") {\n\t$n = $ARGV[1];\n\tshift @ARGV;\n\tshift @ARGV;\n}\n$n = int(($n+49)/50)*50 - 1;\n\n$file = $ARGV[0];\n@lines = <>;\n$linenum = 0;\nforeach (@lines) {\n\t$linenum++;\n\tchomp;\n\ts/\\s+$//;\n\tif(length() >= 75){\n\t\tprint STDERR \"$file:$linenum: line too long\\n\";\n\t}\n}\n@outlines = ();\n$nextout = 0;\n\nfor($i=0; $i<@lines; ){\n\t# Skip leading blank lines.\n\t$i++ while $i<@lines && $lines[$i] =~ /^$/;\n\tlast if $i>=@lines;\n\n\t# If the rest of the file fits, use the whole thing.\n\tif(@lines <= $i+50 && !grep { /PAGEBREAK/ } @lines){\n\t\t$breakbefore = @lines;\n\t}else{\n\t\t# Find a good next page break;\n\t\t# Hope for end of function.\n\t\t# but settle for a blank line (but not first blank line\n\t\t# in function, which comes after variable declarations).\n\t\t$breakbefore = $i;\n\t\t$lastblank = $i;\n\t\t$sawbrace = 0;\n\t\t$breaksize = 15;  # 15 lines to get to function\n\t\tfor($j=$i; $j<$i+50 && $j < @lines; $j++){\n\t\t\tif($lines[$j] =~ /PAGEBREAK!/){\n\t\t\t\t$lines[$j] = \"\";\n\t\t\t\t$breakbefore = $j;\n\t\t\t\t$breaksize = 100;\n\t\t\t\tlast;\n\t\t\t}\n\t\t\tif($lines[$j] =~ /PAGEBREAK:\\s*([0-9]+)/){\n\t\t\t\t$breaksize = $1;\n\t\t\t\t$breakbefore = $j;\n\t\t\t\t$lines[$j] = \"\";\n\t\t\t}\n\t\t\tif($lines[$j] =~ /^};?$/){\n\t\t\t\t$breakbefore = $j+1;\n\t\t\t\t$breaksize = 15;\n\t\t\t}\n\t\t\tif($lines[$j] =~ /^{$/){\n\t\t\t\t$sawbrace = 1;\n\t\t\t}\n\t\t\tif($lines[$j] =~ /^$/){\n\t\t\t\tif($sawbrace){\n\t\t\t\t\t$sawbrace = 0;\n\t\t\t\t}else{\n\t\t\t\t\t$lastblank = $j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif($j<@lines && $lines[$j] =~ /^$/){\n\t\t\t$lastblank = $j;\n\t\t}\n\n\t\t# If we are not putting enough on a page, try a blank line.\n\t\tif($breakbefore - $i < 50 - $breaksize && $lastblank > $breakbefore && $lastblank >= $i+50 - 5){\n\t\t\tif($v){\n\t\t\t\tprint STDERR \"breakbefore $breakbefore i $i breaksize $breaksize\\n\";\n\t\t\t}\n\t\t\t$breakbefore = $lastblank;\n\t\t\t$breaksize = 5;  # only 5 lines to get to blank line\n\t\t}\n\n\t\t# If we are not putting enough on a page, force a full page.\n\t\tif($breakbefore - $i < 50 - $breaksize && $breakbefore != @lines){\n\t\t\t$breakbefore = $i + 50;\n\t\t\t$breakbefore = @lines if @lines < $breakbefore;\n\t\t}\n\n\t\tif($breakbefore < $i+2){\n\t\t\t$breakbefore = $i+2;\n\t\t}\n\t}\n\n\t# Emit the page.\n\t$i50 = $i + 50;\n\tfor(; $i<$breakbefore; $i++){\n\t\tprintf \"%04d %s\\n\", ++$n, $lines[$i];\n\t}\n\n\t# Finish page\n\tfor($j=$i; $j<$i50; $j++){\n\t\tprintf \"%04d \\n\", ++$n;\n\t}\n}\n"
  },
  {
    "path": "sh.c",
    "content": "// Shell.\n\n#include \"types.h\"\n#include \"user.h\"\n#include \"fcntl.h\"\n\n// Parsed command representation\n#define EXEC  1\n#define REDIR 2\n#define PIPE  3\n#define LIST  4\n#define BACK  5\n\n#define MAXARGS 10\n\nstruct cmd {\n  int type;\n};\n\nstruct execcmd {\n  int type;\n  char *argv[MAXARGS];\n  char *eargv[MAXARGS];\n};\n\nstruct redircmd {\n  int type;\n  struct cmd *cmd;\n  char *file;\n  char *efile;\n  int mode;\n  int fd;\n};\n\nstruct pipecmd {\n  int type;\n  struct cmd *left;\n  struct cmd *right;\n};\n\nstruct listcmd {\n  int type;\n  struct cmd *left;\n  struct cmd *right;\n};\n\nstruct backcmd {\n  int type;\n  struct cmd *cmd;\n};\n\nint fork1(void);  // Fork but panics on failure.\nvoid panic(char*);\nstruct cmd *parsecmd(char*);\n\n// Execute cmd.  Never returns.\nvoid\nruncmd(struct cmd *cmd)\n{\n  int p[2];\n  struct backcmd *bcmd;\n  struct execcmd *ecmd;\n  struct listcmd *lcmd;\n  struct pipecmd *pcmd;\n  struct redircmd *rcmd;\n\n  if(cmd == 0)\n    exit();\n\n  switch(cmd->type){\n  default:\n    panic(\"runcmd\");\n\n  case EXEC:\n    ecmd = (struct execcmd*)cmd;\n    if(ecmd->argv[0] == 0)\n      exit();\n    exec(ecmd->argv[0], ecmd->argv);\n    printf(2, \"exec %s failed\\n\", ecmd->argv[0]);\n    break;\n\n  case REDIR:\n    rcmd = (struct redircmd*)cmd;\n    close(rcmd->fd);\n    if(open(rcmd->file, rcmd->mode) < 0){\n      printf(2, \"open %s failed\\n\", rcmd->file);\n      exit();\n    }\n    runcmd(rcmd->cmd);\n    break;\n\n  case LIST:\n    lcmd = (struct listcmd*)cmd;\n    if(fork1() == 0)\n      runcmd(lcmd->left);\n    wait();\n    runcmd(lcmd->right);\n    break;\n\n  case PIPE:\n    pcmd = (struct pipecmd*)cmd;\n    if(pipe(p) < 0)\n      panic(\"pipe\");\n    if(fork1() == 0){\n      close(1);\n      dup(p[1]);\n      close(p[0]);\n      close(p[1]);\n      runcmd(pcmd->left);\n    }\n    if(fork1() == 0){\n      close(0);\n      dup(p[0]);\n      close(p[0]);\n      close(p[1]);\n      runcmd(pcmd->right);\n    }\n    close(p[0]);\n    close(p[1]);\n    wait();\n    wait();\n    break;\n\n  case BACK:\n    bcmd = (struct backcmd*)cmd;\n    if(fork1() == 0)\n      runcmd(bcmd->cmd);\n    break;\n  }\n  exit();\n}\n\nint\ngetcmd(char *buf, int nbuf)\n{\n  printf(2, \"$ \");\n  memset(buf, 0, nbuf);\n  gets(buf, nbuf);\n  if(buf[0] == 0) // EOF\n    return -1;\n  return 0;\n}\n\nint\nmain(void)\n{\n  static char buf[100];\n  int fd;\n\n  // Ensure that three file descriptors are open.\n  while((fd = open(\"console\", O_RDWR)) >= 0){\n    if(fd >= 3){\n      close(fd);\n      break;\n    }\n  }\n\n  // Read and run input commands.\n  while(getcmd(buf, sizeof(buf)) >= 0){\n    if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){\n      // Chdir must be called by the parent, not the child.\n      buf[strlen(buf)-1] = 0;  // chop \\n\n      if(chdir(buf+3) < 0)\n        printf(2, \"cannot cd %s\\n\", buf+3);\n      continue;\n    }\n    if(fork1() == 0)\n      runcmd(parsecmd(buf));\n    wait();\n  }\n  exit();\n}\n\nvoid\npanic(char *s)\n{\n  printf(2, \"%s\\n\", s);\n  exit();\n}\n\nint\nfork1(void)\n{\n  int pid;\n\n  pid = fork();\n  if(pid == -1)\n    panic(\"fork\");\n  return pid;\n}\n\n//PAGEBREAK!\n// Constructors\n\nstruct cmd*\nexeccmd(void)\n{\n  struct execcmd *cmd;\n\n  cmd = malloc(sizeof(*cmd));\n  memset(cmd, 0, sizeof(*cmd));\n  cmd->type = EXEC;\n  return (struct cmd*)cmd;\n}\n\nstruct cmd*\nredircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)\n{\n  struct redircmd *cmd;\n\n  cmd = malloc(sizeof(*cmd));\n  memset(cmd, 0, sizeof(*cmd));\n  cmd->type = REDIR;\n  cmd->cmd = subcmd;\n  cmd->file = file;\n  cmd->efile = efile;\n  cmd->mode = mode;\n  cmd->fd = fd;\n  return (struct cmd*)cmd;\n}\n\nstruct cmd*\npipecmd(struct cmd *left, struct cmd *right)\n{\n  struct pipecmd *cmd;\n\n  cmd = malloc(sizeof(*cmd));\n  memset(cmd, 0, sizeof(*cmd));\n  cmd->type = PIPE;\n  cmd->left = left;\n  cmd->right = right;\n  return (struct cmd*)cmd;\n}\n\nstruct cmd*\nlistcmd(struct cmd *left, struct cmd *right)\n{\n  struct listcmd *cmd;\n\n  cmd = malloc(sizeof(*cmd));\n  memset(cmd, 0, sizeof(*cmd));\n  cmd->type = LIST;\n  cmd->left = left;\n  cmd->right = right;\n  return (struct cmd*)cmd;\n}\n\nstruct cmd*\nbackcmd(struct cmd *subcmd)\n{\n  struct backcmd *cmd;\n\n  cmd = malloc(sizeof(*cmd));\n  memset(cmd, 0, sizeof(*cmd));\n  cmd->type = BACK;\n  cmd->cmd = subcmd;\n  return (struct cmd*)cmd;\n}\n//PAGEBREAK!\n// Parsing\n\nchar whitespace[] = \" \\t\\r\\n\\v\";\nchar symbols[] = \"<|>&;()\";\n\nint\ngettoken(char **ps, char *es, char **q, char **eq)\n{\n  char *s;\n  int ret;\n\n  s = *ps;\n  while(s < es && strchr(whitespace, *s))\n    s++;\n  if(q)\n    *q = s;\n  ret = *s;\n  switch(*s){\n  case 0:\n    break;\n  case '|':\n  case '(':\n  case ')':\n  case ';':\n  case '&':\n  case '<':\n    s++;\n    break;\n  case '>':\n    s++;\n    if(*s == '>'){\n      ret = '+';\n      s++;\n    }\n    break;\n  default:\n    ret = 'a';\n    while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))\n      s++;\n    break;\n  }\n  if(eq)\n    *eq = s;\n\n  while(s < es && strchr(whitespace, *s))\n    s++;\n  *ps = s;\n  return ret;\n}\n\nint\npeek(char **ps, char *es, char *toks)\n{\n  char *s;\n\n  s = *ps;\n  while(s < es && strchr(whitespace, *s))\n    s++;\n  *ps = s;\n  return *s && strchr(toks, *s);\n}\n\nstruct cmd *parseline(char**, char*);\nstruct cmd *parsepipe(char**, char*);\nstruct cmd *parseexec(char**, char*);\nstruct cmd *nulterminate(struct cmd*);\n\nstruct cmd*\nparsecmd(char *s)\n{\n  char *es;\n  struct cmd *cmd;\n\n  es = s + strlen(s);\n  cmd = parseline(&s, es);\n  peek(&s, es, \"\");\n  if(s != es){\n    printf(2, \"leftovers: %s\\n\", s);\n    panic(\"syntax\");\n  }\n  nulterminate(cmd);\n  return cmd;\n}\n\nstruct cmd*\nparseline(char **ps, char *es)\n{\n  struct cmd *cmd;\n\n  cmd = parsepipe(ps, es);\n  while(peek(ps, es, \"&\")){\n    gettoken(ps, es, 0, 0);\n    cmd = backcmd(cmd);\n  }\n  if(peek(ps, es, \";\")){\n    gettoken(ps, es, 0, 0);\n    cmd = listcmd(cmd, parseline(ps, es));\n  }\n  return cmd;\n}\n\nstruct cmd*\nparsepipe(char **ps, char *es)\n{\n  struct cmd *cmd;\n\n  cmd = parseexec(ps, es);\n  if(peek(ps, es, \"|\")){\n    gettoken(ps, es, 0, 0);\n    cmd = pipecmd(cmd, parsepipe(ps, es));\n  }\n  return cmd;\n}\n\nstruct cmd*\nparseredirs(struct cmd *cmd, char **ps, char *es)\n{\n  int tok;\n  char *q, *eq;\n\n  while(peek(ps, es, \"<>\")){\n    tok = gettoken(ps, es, 0, 0);\n    if(gettoken(ps, es, &q, &eq) != 'a')\n      panic(\"missing file for redirection\");\n    switch(tok){\n    case '<':\n      cmd = redircmd(cmd, q, eq, O_RDONLY, 0);\n      break;\n    case '>':\n      cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);\n      break;\n    case '+':  // >>\n      cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1);\n      break;\n    }\n  }\n  return cmd;\n}\n\nstruct cmd*\nparseblock(char **ps, char *es)\n{\n  struct cmd *cmd;\n\n  if(!peek(ps, es, \"(\"))\n    panic(\"parseblock\");\n  gettoken(ps, es, 0, 0);\n  cmd = parseline(ps, es);\n  if(!peek(ps, es, \")\"))\n    panic(\"syntax - missing )\");\n  gettoken(ps, es, 0, 0);\n  cmd = parseredirs(cmd, ps, es);\n  return cmd;\n}\n\nstruct cmd*\nparseexec(char **ps, char *es)\n{\n  char *q, *eq;\n  int tok, argc;\n  struct execcmd *cmd;\n  struct cmd *ret;\n\n  if(peek(ps, es, \"(\"))\n    return parseblock(ps, es);\n\n  ret = execcmd();\n  cmd = (struct execcmd*)ret;\n\n  argc = 0;\n  ret = parseredirs(ret, ps, es);\n  while(!peek(ps, es, \"|)&;\")){\n    if((tok=gettoken(ps, es, &q, &eq)) == 0)\n      break;\n    if(tok != 'a')\n      panic(\"syntax\");\n    cmd->argv[argc] = q;\n    cmd->eargv[argc] = eq;\n    argc++;\n    if(argc >= MAXARGS)\n      panic(\"too many args\");\n    ret = parseredirs(ret, ps, es);\n  }\n  cmd->argv[argc] = 0;\n  cmd->eargv[argc] = 0;\n  return ret;\n}\n\n// NUL-terminate all the counted strings.\nstruct cmd*\nnulterminate(struct cmd *cmd)\n{\n  int i;\n  struct backcmd *bcmd;\n  struct execcmd *ecmd;\n  struct listcmd *lcmd;\n  struct pipecmd *pcmd;\n  struct redircmd *rcmd;\n\n  if(cmd == 0)\n    return 0;\n\n  switch(cmd->type){\n  case EXEC:\n    ecmd = (struct execcmd*)cmd;\n    for(i=0; ecmd->argv[i]; i++)\n      *ecmd->eargv[i] = 0;\n    break;\n\n  case REDIR:\n    rcmd = (struct redircmd*)cmd;\n    nulterminate(rcmd->cmd);\n    *rcmd->efile = 0;\n    break;\n\n  case PIPE:\n    pcmd = (struct pipecmd*)cmd;\n    nulterminate(pcmd->left);\n    nulterminate(pcmd->right);\n    break;\n\n  case LIST:\n    lcmd = (struct listcmd*)cmd;\n    nulterminate(lcmd->left);\n    nulterminate(lcmd->right);\n    break;\n\n  case BACK:\n    bcmd = (struct backcmd*)cmd;\n    nulterminate(bcmd->cmd);\n    break;\n  }\n  return cmd;\n}\n"
  },
  {
    "path": "show1",
    "content": "#!/bin/sh\n\nrunoff1 \"$@\" | pr.pl -h \"xv6/$@\" | mpage -m50t50b -o -bLetter -T -t -2 -FLucidaSans-Typewriter83 -L60 >x.ps; gv --swap x.ps\n"
  },
  {
    "path": "sign.pl",
    "content": "#!/usr/bin/perl\n\nopen(SIG, $ARGV[0]) || die \"open $ARGV[0]: $!\";\n\n$n = sysread(SIG, $buf, 1000);\n\nif($n > 510){\n  print STDERR \"boot block too large: $n bytes (max 510)\\n\";\n  exit 1;\n}\n\nprint STDERR \"boot block is $n bytes (max 510)\\n\";\n\n$buf .= \"\\0\" x (510-$n);\n$buf .= \"\\x55\\xAA\";\n\nopen(SIG, \">$ARGV[0]\") || die \"open >$ARGV[0]: $!\";\nprint SIG $buf;\nclose SIG;\n"
  },
  {
    "path": "sleep1.p",
    "content": "/*\nThis file defines a Promela model for xv6's\nacquire, release, sleep, and wakeup, along with\na model of a simple producer/consumer queue.\n\nTo run:\n\tspinp sleep1.p\n\n(You may need to install Spin, available at http://spinroot.com/.)\n\nAfter a successful run spin prints something like:\n\n\tunreached in proctype consumer\n\t\t(0 of 37 states)\n\tunreached in proctype producer\n\t\t(0 of 23 states)\n\nAfter an unsuccessful run, the spinp script prints\nan execution trace that causes a deadlock.\n\nThe safe body of producer reads:\n\n\t\tacquire(lk);\n\t\tx = value; value = x + 1; x = 0;\n\t\twakeup(0);\n\t\trelease(lk);\n\t\ti = i + 1;\n\nIf this is changed to:\n\n\t\tx = value; value = x + 1; x = 0;\n\t\tacquire(lk);\n\t\twakeup(0);\n\t\trelease(lk);\n\t\ti = i + 1;\n\nthen a deadlock can happen, because the non-atomic\nincrement of value conflicts with the non-atomic \ndecrement in consumer, causing value to have a bad value.\nTry this.\n\nIf it is changed to:\n\n\t\tacquire(lk);\n\t\tx = value; value = x + 1; x = 0;\n\t\trelease(lk);\n\t\twakeup(0);\n\t\ti = i + 1;\n\nthen nothing bad happens: it is okay to wakeup after release\ninstead of before, although it seems morally wrong.\n*/\n\n#define ITER 4\n#define N 2\n\nbit lk;\nbyte value;\nbit sleeping[N];\n\ninline acquire(x)\n{\n\tatomic { x == 0; x = 1 }\n}\n\ninline release(x)\n{\n\tassert x==1;\n\tx = 0\n}\n\ninline sleep(cond, lk)\n{\n\tassert !sleeping[_pid];\n\tif\n\t:: cond ->\n\t\tskip\n\t:: else ->\n\t\tatomic { release(lk); sleeping[_pid] = 1 };\n\t\tsleeping[_pid] == 0;\n\t\tacquire(lk)\n\tfi\n}\n\ninline wakeup()\n{\n\tw = 0;\n\tdo\n\t:: w < N ->\n\t\tsleeping[w] = 0;\n\t\tw = w + 1\n\t:: else ->\n\t\tbreak\n\tod\n}\n\nactive[N] proctype consumer()\n{\n\tbyte i, x;\n\t\n\ti = 0;\n\tdo\n\t:: i < ITER ->\n\t\tacquire(lk);\n\t\tsleep(value > 0, lk);\n\t\tx = value; value = x - 1; x = 0;\n\t\trelease(lk);\n\t\ti = i + 1;\n\t:: else ->\n\t\tbreak\n\tod;\n\ti = 0;\n\tskip\n}\n\nactive[N] proctype producer()\n{\n\tbyte i, x, w;\n\t\n\ti = 0;\n\tdo\n\t:: i < ITER ->\n\t\tacquire(lk);\n\t\tx = value; value = x + 1; x = 0;\n\t\trelease(lk);\n\t\twakeup();\n\t\ti = i + 1;\n\t:: else ->\n\t\tbreak\n\tod;\n\ti = 0;\n\tskip\t\n}\n\n"
  },
  {
    "path": "sleeplock.c",
    "content": "// Sleeping locks\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"x86.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n\nvoid\ninitsleeplock(struct sleeplock *lk, char *name)\n{\n  initlock(&lk->lk, \"sleep lock\");\n  lk->name = name;\n  lk->locked = 0;\n  lk->pid = 0;\n}\n\nvoid\nacquiresleep(struct sleeplock *lk)\n{\n  acquire(&lk->lk);\n  while (lk->locked) {\n    sleep(lk, &lk->lk);\n  }\n  lk->locked = 1;\n  lk->pid = myproc()->pid;\n  release(&lk->lk);\n}\n\nvoid\nreleasesleep(struct sleeplock *lk)\n{\n  acquire(&lk->lk);\n  lk->locked = 0;\n  lk->pid = 0;\n  wakeup(lk);\n  release(&lk->lk);\n}\n\nint\nholdingsleep(struct sleeplock *lk)\n{\n  int r;\n  \n  acquire(&lk->lk);\n  r = lk->locked && (lk->pid == myproc()->pid);\n  release(&lk->lk);\n  return r;\n}\n\n\n\n"
  },
  {
    "path": "sleeplock.h",
    "content": "// Long-term locks for processes\nstruct sleeplock {\n  uint locked;       // Is the lock held?\n  struct spinlock lk; // spinlock protecting this sleep lock\n  \n  // For debugging:\n  char *name;        // Name of lock.\n  int pid;           // Process holding lock\n};\n\n"
  },
  {
    "path": "spinlock.c",
    "content": "// Mutual exclusion spin locks.\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"x86.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"spinlock.h\"\n\nvoid\ninitlock(struct spinlock *lk, char *name)\n{\n  lk->name = name;\n  lk->locked = 0;\n  lk->cpu = 0;\n}\n\n// Acquire the lock.\n// Loops (spins) until the lock is acquired.\n// Holding a lock for a long time may cause\n// other CPUs to waste time spinning to acquire it.\nvoid\nacquire(struct spinlock *lk)\n{\n  pushcli(); // disable interrupts to avoid deadlock.\n  if(holding(lk))\n    panic(\"acquire\");\n\n  // The xchg is atomic.\n  while(xchg(&lk->locked, 1) != 0)\n    ;\n\n  // Tell the C compiler and the processor to not move loads or stores\n  // past this point, to ensure that the critical section's memory\n  // references happen after the lock is acquired.\n  __sync_synchronize();\n\n  // Record info about lock acquisition for debugging.\n  lk->cpu = mycpu();\n  getcallerpcs(&lk, lk->pcs);\n}\n\n// Release the lock.\nvoid\nrelease(struct spinlock *lk)\n{\n  if(!holding(lk))\n    panic(\"release\");\n\n  lk->pcs[0] = 0;\n  lk->cpu = 0;\n\n  // Tell the C compiler and the processor to not move loads or stores\n  // past this point, to ensure that all the stores in the critical\n  // section are visible to other cores before the lock is released.\n  // Both the C compiler and the hardware may re-order loads and\n  // stores; __sync_synchronize() tells them both not to.\n  __sync_synchronize();\n\n  // Release the lock, equivalent to lk->locked = 0.\n  // This code can't use a C assignment, since it might\n  // not be atomic. A real OS would use C atomics here.\n  asm volatile(\"movl $0, %0\" : \"+m\" (lk->locked) : );\n\n  popcli();\n}\n\n// Record the current call stack in pcs[] by following the %ebp chain.\nvoid\ngetcallerpcs(void *v, uint pcs[])\n{\n  uint *ebp;\n  int i;\n\n  ebp = (uint*)v - 2;\n  for(i = 0; i < 10; i++){\n    if(ebp == 0 || ebp < (uint*)KERNBASE || ebp == (uint*)0xffffffff)\n      break;\n    pcs[i] = ebp[1];     // saved %eip\n    ebp = (uint*)ebp[0]; // saved %ebp\n  }\n  for(; i < 10; i++)\n    pcs[i] = 0;\n}\n\n// Check whether this cpu is holding the lock.\nint\nholding(struct spinlock *lock)\n{\n  int r;\n  pushcli();\n  r = lock->locked && lock->cpu == mycpu();\n  popcli();\n  return r;\n}\n\n\n// Pushcli/popcli are like cli/sti except that they are matched:\n// it takes two popcli to undo two pushcli.  Also, if interrupts\n// are off, then pushcli, popcli leaves them off.\n\nvoid\npushcli(void)\n{\n  int eflags;\n\n  eflags = readeflags();\n  cli();\n  if(mycpu()->ncli == 0)\n    mycpu()->intena = eflags & FL_IF;\n  mycpu()->ncli += 1;\n}\n\nvoid\npopcli(void)\n{\n  if(readeflags()&FL_IF)\n    panic(\"popcli - interruptible\");\n  if(--mycpu()->ncli < 0)\n    panic(\"popcli\");\n  if(mycpu()->ncli == 0 && mycpu()->intena)\n    sti();\n}\n\n"
  },
  {
    "path": "spinlock.h",
    "content": "// Mutual exclusion lock.\nstruct spinlock {\n  uint locked;       // Is the lock held?\n\n  // For debugging:\n  char *name;        // Name of lock.\n  struct cpu *cpu;   // The cpu holding the lock.\n  uint pcs[10];      // The call stack (an array of program counters)\n                     // that locked the lock.\n};\n\n"
  },
  {
    "path": "spinp",
    "content": "#!/bin/sh\n\nif [ $# != 1 ] || [ ! -f \"$1\" ]; then\n\techo 'usage: spinp file.p' 1>&2\n\texit 1\nfi\n\nrm -f $1.trail\nspin -a $1 || exit 1\ncc -DSAFETY -DREACH -DMEMLIM=500 -o pan pan.c\npan -i\nrm pan.* pan\nif [ -f $1.trail ]; then\n\tspin -t -p $1\nfi\n\n"
  },
  {
    "path": "stat.h",
    "content": "#define T_DIR  1   // Directory\n#define T_FILE 2   // File\n#define T_DEV  3   // Device\n\nstruct stat {\n  short type;  // Type of file\n  int dev;     // File system's disk device\n  uint ino;    // Inode number\n  short nlink; // Number of links to file\n  uint size;   // Size of file in bytes\n};\n"
  },
  {
    "path": "stressfs.c",
    "content": "// Demonstrate that moving the \"acquire\" in iderw after the loop that\n// appends to the idequeue results in a race.\n\n// For this to work, you should also add a spin within iderw's\n// idequeue traversal loop.  Adding the following demonstrated a panic\n// after about 5 runs of stressfs in QEMU on a 2.1GHz CPU:\n//    for (i = 0; i < 40000; i++)\n//      asm volatile(\"\");\n\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"fs.h\"\n#include \"fcntl.h\"\n\nint\nmain(int argc, char *argv[])\n{\n  int fd, i;\n  char path[] = \"stressfs0\";\n  char data[512];\n\n  printf(1, \"stressfs starting\\n\");\n  memset(data, 'a', sizeof(data));\n\n  for(i = 0; i < 4; i++)\n    if(fork() > 0)\n      break;\n\n  printf(1, \"write %d\\n\", i);\n\n  path[8] += i;\n  fd = open(path, O_CREATE | O_RDWR);\n  for(i = 0; i < 20; i++)\n//    printf(fd, \"%d\\n\", i);\n    write(fd, data, sizeof(data));\n  close(fd);\n\n  printf(1, \"read\\n\");\n\n  fd = open(path, O_RDONLY);\n  for (i = 0; i < 20; i++)\n    read(fd, data, sizeof(data));\n  close(fd);\n\n  wait();\n\n  exit();\n}\n"
  },
  {
    "path": "string.c",
    "content": "#include \"types.h\"\n#include \"x86.h\"\n\nvoid*\nmemset(void *dst, int c, uint n)\n{\n  if ((int)dst%4 == 0 && n%4 == 0){\n    c &= 0xFF;\n    stosl(dst, (c<<24)|(c<<16)|(c<<8)|c, n/4);\n  } else\n    stosb(dst, c, n);\n  return dst;\n}\n\nint\nmemcmp(const void *v1, const void *v2, uint n)\n{\n  const uchar *s1, *s2;\n\n  s1 = v1;\n  s2 = v2;\n  while(n-- > 0){\n    if(*s1 != *s2)\n      return *s1 - *s2;\n    s1++, s2++;\n  }\n\n  return 0;\n}\n\nvoid*\nmemmove(void *dst, const void *src, uint n)\n{\n  const char *s;\n  char *d;\n\n  s = src;\n  d = dst;\n  if(s < d && s + n > d){\n    s += n;\n    d += n;\n    while(n-- > 0)\n      *--d = *--s;\n  } else\n    while(n-- > 0)\n      *d++ = *s++;\n\n  return dst;\n}\n\n// memcpy exists to placate GCC.  Use memmove.\nvoid*\nmemcpy(void *dst, const void *src, uint n)\n{\n  return memmove(dst, src, n);\n}\n\nint\nstrncmp(const char *p, const char *q, uint n)\n{\n  while(n > 0 && *p && *p == *q)\n    n--, p++, q++;\n  if(n == 0)\n    return 0;\n  return (uchar)*p - (uchar)*q;\n}\n\nchar*\nstrncpy(char *s, const char *t, int n)\n{\n  char *os;\n\n  os = s;\n  while(n-- > 0 && (*s++ = *t++) != 0)\n    ;\n  while(n-- > 0)\n    *s++ = 0;\n  return os;\n}\n\n// Like strncpy but guaranteed to NUL-terminate.\nchar*\nsafestrcpy(char *s, const char *t, int n)\n{\n  char *os;\n\n  os = s;\n  if(n <= 0)\n    return os;\n  while(--n > 0 && (*s++ = *t++) != 0)\n    ;\n  *s = 0;\n  return os;\n}\n\nint\nstrlen(const char *s)\n{\n  int n;\n\n  for(n = 0; s[n]; n++)\n    ;\n  return n;\n}\n\n"
  },
  {
    "path": "swtch.S",
    "content": "# Context switch\n#\n#   void swtch(struct context **old, struct context *new);\n# \n# Save the current registers on the stack, creating\n# a struct context, and save its address in *old.\n# Switch stacks to new and pop previously-saved registers.\n\n.globl swtch\nswtch:\n  movl 4(%esp), %eax\n  movl 8(%esp), %edx\n\n  # Save old callee-saved registers\n  pushl %ebp\n  pushl %ebx\n  pushl %esi\n  pushl %edi\n\n  # Switch stacks\n  movl %esp, (%eax)\n  movl %edx, %esp\n\n  # Load new callee-saved registers\n  popl %edi\n  popl %esi\n  popl %ebx\n  popl %ebp\n  ret\n"
  },
  {
    "path": "syscall.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n#include \"syscall.h\"\n\n// User code makes a system call with INT T_SYSCALL.\n// System call number in %eax.\n// Arguments on the stack, from the user call to the C\n// library system call function. The saved user %esp points\n// to a saved program counter, and then the first argument.\n\n// Fetch the int at addr from the current process.\nint\nfetchint(uint addr, int *ip)\n{\n  struct proc *curproc = myproc();\n\n  if(addr >= curproc->sz || addr+4 > curproc->sz)\n    return -1;\n  *ip = *(int*)(addr);\n  return 0;\n}\n\n// Fetch the nul-terminated string at addr from the current process.\n// Doesn't actually copy the string - just sets *pp to point at it.\n// Returns length of string, not including nul.\nint\nfetchstr(uint addr, char **pp)\n{\n  char *s, *ep;\n  struct proc *curproc = myproc();\n\n  if(addr >= curproc->sz)\n    return -1;\n  *pp = (char*)addr;\n  ep = (char*)curproc->sz;\n  for(s = *pp; s < ep; s++){\n    if(*s == 0)\n      return s - *pp;\n  }\n  return -1;\n}\n\n// Fetch the nth 32-bit system call argument.\nint\nargint(int n, int *ip)\n{\n  return fetchint((myproc()->tf->esp) + 4 + 4*n, ip);\n}\n\n// Fetch the nth word-sized system call argument as a pointer\n// to a block of memory of size bytes.  Check that the pointer\n// lies within the process address space.\nint\nargptr(int n, char **pp, int size)\n{\n  int i;\n  struct proc *curproc = myproc();\n \n  if(argint(n, &i) < 0)\n    return -1;\n  if(size < 0 || (uint)i >= curproc->sz || (uint)i+size > curproc->sz)\n    return -1;\n  *pp = (char*)i;\n  return 0;\n}\n\n// Fetch the nth word-sized system call argument as a string pointer.\n// Check that the pointer is valid and the string is nul-terminated.\n// (There is no shared writable memory, so the string can't change\n// between this check and being used by the kernel.)\nint\nargstr(int n, char **pp)\n{\n  int addr;\n  if(argint(n, &addr) < 0)\n    return -1;\n  return fetchstr(addr, pp);\n}\n\nextern int sys_chdir(void);\nextern int sys_close(void);\nextern int sys_dup(void);\nextern int sys_exec(void);\nextern int sys_exit(void);\nextern int sys_fork(void);\nextern int sys_fstat(void);\nextern int sys_getpid(void);\nextern int sys_kill(void);\nextern int sys_link(void);\nextern int sys_mkdir(void);\nextern int sys_mknod(void);\nextern int sys_open(void);\nextern int sys_pipe(void);\nextern int sys_read(void);\nextern int sys_sbrk(void);\nextern int sys_sleep(void);\nextern int sys_unlink(void);\nextern int sys_wait(void);\nextern int sys_write(void);\nextern int sys_uptime(void);\n\nstatic int (*syscalls[])(void) = {\n[SYS_fork]    sys_fork,\n[SYS_exit]    sys_exit,\n[SYS_wait]    sys_wait,\n[SYS_pipe]    sys_pipe,\n[SYS_read]    sys_read,\n[SYS_kill]    sys_kill,\n[SYS_exec]    sys_exec,\n[SYS_fstat]   sys_fstat,\n[SYS_chdir]   sys_chdir,\n[SYS_dup]     sys_dup,\n[SYS_getpid]  sys_getpid,\n[SYS_sbrk]    sys_sbrk,\n[SYS_sleep]   sys_sleep,\n[SYS_uptime]  sys_uptime,\n[SYS_open]    sys_open,\n[SYS_write]   sys_write,\n[SYS_mknod]   sys_mknod,\n[SYS_unlink]  sys_unlink,\n[SYS_link]    sys_link,\n[SYS_mkdir]   sys_mkdir,\n[SYS_close]   sys_close,\n};\n\nvoid\nsyscall(void)\n{\n  int num;\n  struct proc *curproc = myproc();\n\n  num = curproc->tf->eax;\n  if(num > 0 && num < NELEM(syscalls) && syscalls[num]) {\n    curproc->tf->eax = syscalls[num]();\n  } else {\n    cprintf(\"%d %s: unknown sys call %d\\n\",\n            curproc->pid, curproc->name, num);\n    curproc->tf->eax = -1;\n  }\n}\n"
  },
  {
    "path": "syscall.h",
    "content": "// System call numbers\n#define SYS_fork    1\n#define SYS_exit    2\n#define SYS_wait    3\n#define SYS_pipe    4\n#define SYS_read    5\n#define SYS_kill    6\n#define SYS_exec    7\n#define SYS_fstat   8\n#define SYS_chdir   9\n#define SYS_dup    10\n#define SYS_getpid 11\n#define SYS_sbrk   12\n#define SYS_sleep  13\n#define SYS_uptime 14\n#define SYS_open   15\n#define SYS_write  16\n#define SYS_mknod  17\n#define SYS_unlink 18\n#define SYS_link   19\n#define SYS_mkdir  20\n#define SYS_close  21\n"
  },
  {
    "path": "sysfile.c",
    "content": "//\n// File-system system calls.\n// Mostly argument checking, since we don't trust\n// user code, and calls into file.c and fs.c.\n//\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"stat.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"fs.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"file.h\"\n#include \"fcntl.h\"\n\n// Fetch the nth word-sized system call argument as a file descriptor\n// and return both the descriptor and the corresponding struct file.\nstatic int\nargfd(int n, int *pfd, struct file **pf)\n{\n  int fd;\n  struct file *f;\n\n  if(argint(n, &fd) < 0)\n    return -1;\n  if(fd < 0 || fd >= NOFILE || (f=myproc()->ofile[fd]) == 0)\n    return -1;\n  if(pfd)\n    *pfd = fd;\n  if(pf)\n    *pf = f;\n  return 0;\n}\n\n// Allocate a file descriptor for the given file.\n// Takes over file reference from caller on success.\nstatic int\nfdalloc(struct file *f)\n{\n  int fd;\n  struct proc *curproc = myproc();\n\n  for(fd = 0; fd < NOFILE; fd++){\n    if(curproc->ofile[fd] == 0){\n      curproc->ofile[fd] = f;\n      return fd;\n    }\n  }\n  return -1;\n}\n\nint\nsys_dup(void)\n{\n  struct file *f;\n  int fd;\n\n  if(argfd(0, 0, &f) < 0)\n    return -1;\n  if((fd=fdalloc(f)) < 0)\n    return -1;\n  filedup(f);\n  return fd;\n}\n\nint\nsys_read(void)\n{\n  struct file *f;\n  int n;\n  char *p;\n\n  if(argfd(0, 0, &f) < 0 || argint(2, &n) < 0 || argptr(1, &p, n) < 0)\n    return -1;\n  return fileread(f, p, n);\n}\n\nint\nsys_write(void)\n{\n  struct file *f;\n  int n;\n  char *p;\n\n  if(argfd(0, 0, &f) < 0 || argint(2, &n) < 0 || argptr(1, &p, n) < 0)\n    return -1;\n  return filewrite(f, p, n);\n}\n\nint\nsys_close(void)\n{\n  int fd;\n  struct file *f;\n\n  if(argfd(0, &fd, &f) < 0)\n    return -1;\n  myproc()->ofile[fd] = 0;\n  fileclose(f);\n  return 0;\n}\n\nint\nsys_fstat(void)\n{\n  struct file *f;\n  struct stat *st;\n\n  if(argfd(0, 0, &f) < 0 || argptr(1, (void*)&st, sizeof(*st)) < 0)\n    return -1;\n  return filestat(f, st);\n}\n\n// Create the path new as a link to the same inode as old.\nint\nsys_link(void)\n{\n  char name[DIRSIZ], *new, *old;\n  struct inode *dp, *ip;\n\n  if(argstr(0, &old) < 0 || argstr(1, &new) < 0)\n    return -1;\n\n  begin_op();\n  if((ip = namei(old)) == 0){\n    end_op();\n    return -1;\n  }\n\n  ilock(ip);\n  if(ip->type == T_DIR){\n    iunlockput(ip);\n    end_op();\n    return -1;\n  }\n\n  ip->nlink++;\n  iupdate(ip);\n  iunlock(ip);\n\n  if((dp = nameiparent(new, name)) == 0)\n    goto bad;\n  ilock(dp);\n  if(dp->dev != ip->dev || dirlink(dp, name, ip->inum) < 0){\n    iunlockput(dp);\n    goto bad;\n  }\n  iunlockput(dp);\n  iput(ip);\n\n  end_op();\n\n  return 0;\n\nbad:\n  ilock(ip);\n  ip->nlink--;\n  iupdate(ip);\n  iunlockput(ip);\n  end_op();\n  return -1;\n}\n\n// Is the directory dp empty except for \".\" and \"..\" ?\nstatic int\nisdirempty(struct inode *dp)\n{\n  int off;\n  struct dirent de;\n\n  for(off=2*sizeof(de); off<dp->size; off+=sizeof(de)){\n    if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))\n      panic(\"isdirempty: readi\");\n    if(de.inum != 0)\n      return 0;\n  }\n  return 1;\n}\n\n//PAGEBREAK!\nint\nsys_unlink(void)\n{\n  struct inode *ip, *dp;\n  struct dirent de;\n  char name[DIRSIZ], *path;\n  uint off;\n\n  if(argstr(0, &path) < 0)\n    return -1;\n\n  begin_op();\n  if((dp = nameiparent(path, name)) == 0){\n    end_op();\n    return -1;\n  }\n\n  ilock(dp);\n\n  // Cannot unlink \".\" or \"..\".\n  if(namecmp(name, \".\") == 0 || namecmp(name, \"..\") == 0)\n    goto bad;\n\n  if((ip = dirlookup(dp, name, &off)) == 0)\n    goto bad;\n  ilock(ip);\n\n  if(ip->nlink < 1)\n    panic(\"unlink: nlink < 1\");\n  if(ip->type == T_DIR && !isdirempty(ip)){\n    iunlockput(ip);\n    goto bad;\n  }\n\n  memset(&de, 0, sizeof(de));\n  if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))\n    panic(\"unlink: writei\");\n  if(ip->type == T_DIR){\n    dp->nlink--;\n    iupdate(dp);\n  }\n  iunlockput(dp);\n\n  ip->nlink--;\n  iupdate(ip);\n  iunlockput(ip);\n\n  end_op();\n\n  return 0;\n\nbad:\n  iunlockput(dp);\n  end_op();\n  return -1;\n}\n\nstatic struct inode*\ncreate(char *path, short type, short major, short minor)\n{\n  struct inode *ip, *dp;\n  char name[DIRSIZ];\n\n  if((dp = nameiparent(path, name)) == 0)\n    return 0;\n  ilock(dp);\n\n  if((ip = dirlookup(dp, name, 0)) != 0){\n    iunlockput(dp);\n    ilock(ip);\n    if(type == T_FILE && ip->type == T_FILE)\n      return ip;\n    iunlockput(ip);\n    return 0;\n  }\n\n  if((ip = ialloc(dp->dev, type)) == 0)\n    panic(\"create: ialloc\");\n\n  ilock(ip);\n  ip->major = major;\n  ip->minor = minor;\n  ip->nlink = 1;\n  iupdate(ip);\n\n  if(type == T_DIR){  // Create . and .. entries.\n    dp->nlink++;  // for \"..\"\n    iupdate(dp);\n    // No ip->nlink++ for \".\": avoid cyclic ref count.\n    if(dirlink(ip, \".\", ip->inum) < 0 || dirlink(ip, \"..\", dp->inum) < 0)\n      panic(\"create dots\");\n  }\n\n  if(dirlink(dp, name, ip->inum) < 0)\n    panic(\"create: dirlink\");\n\n  iunlockput(dp);\n\n  return ip;\n}\n\nint\nsys_open(void)\n{\n  char *path;\n  int fd, omode;\n  struct file *f;\n  struct inode *ip;\n\n  if(argstr(0, &path) < 0 || argint(1, &omode) < 0)\n    return -1;\n\n  begin_op();\n\n  if(omode & O_CREATE){\n    ip = create(path, T_FILE, 0, 0);\n    if(ip == 0){\n      end_op();\n      return -1;\n    }\n  } else {\n    if((ip = namei(path)) == 0){\n      end_op();\n      return -1;\n    }\n    ilock(ip);\n    if(ip->type == T_DIR && omode != O_RDONLY){\n      iunlockput(ip);\n      end_op();\n      return -1;\n    }\n  }\n\n  if((f = filealloc()) == 0 || (fd = fdalloc(f)) < 0){\n    if(f)\n      fileclose(f);\n    iunlockput(ip);\n    end_op();\n    return -1;\n  }\n  iunlock(ip);\n  end_op();\n\n  f->type = FD_INODE;\n  f->ip = ip;\n  f->off = 0;\n  f->readable = !(omode & O_WRONLY);\n  f->writable = (omode & O_WRONLY) || (omode & O_RDWR);\n  return fd;\n}\n\nint\nsys_mkdir(void)\n{\n  char *path;\n  struct inode *ip;\n\n  begin_op();\n  if(argstr(0, &path) < 0 || (ip = create(path, T_DIR, 0, 0)) == 0){\n    end_op();\n    return -1;\n  }\n  iunlockput(ip);\n  end_op();\n  return 0;\n}\n\nint\nsys_mknod(void)\n{\n  struct inode *ip;\n  char *path;\n  int major, minor;\n\n  begin_op();\n  if((argstr(0, &path)) < 0 ||\n     argint(1, &major) < 0 ||\n     argint(2, &minor) < 0 ||\n     (ip = create(path, T_DEV, major, minor)) == 0){\n    end_op();\n    return -1;\n  }\n  iunlockput(ip);\n  end_op();\n  return 0;\n}\n\nint\nsys_chdir(void)\n{\n  char *path;\n  struct inode *ip;\n  struct proc *curproc = myproc();\n  \n  begin_op();\n  if(argstr(0, &path) < 0 || (ip = namei(path)) == 0){\n    end_op();\n    return -1;\n  }\n  ilock(ip);\n  if(ip->type != T_DIR){\n    iunlockput(ip);\n    end_op();\n    return -1;\n  }\n  iunlock(ip);\n  iput(curproc->cwd);\n  end_op();\n  curproc->cwd = ip;\n  return 0;\n}\n\nint\nsys_exec(void)\n{\n  char *path, *argv[MAXARG];\n  int i;\n  uint uargv, uarg;\n\n  if(argstr(0, &path) < 0 || argint(1, (int*)&uargv) < 0){\n    return -1;\n  }\n  memset(argv, 0, sizeof(argv));\n  for(i=0;; i++){\n    if(i >= NELEM(argv))\n      return -1;\n    if(fetchint(uargv+4*i, (int*)&uarg) < 0)\n      return -1;\n    if(uarg == 0){\n      argv[i] = 0;\n      break;\n    }\n    if(fetchstr(uarg, &argv[i]) < 0)\n      return -1;\n  }\n  return exec(path, argv);\n}\n\nint\nsys_pipe(void)\n{\n  int *fd;\n  struct file *rf, *wf;\n  int fd0, fd1;\n\n  if(argptr(0, (void*)&fd, 2*sizeof(fd[0])) < 0)\n    return -1;\n  if(pipealloc(&rf, &wf) < 0)\n    return -1;\n  fd0 = -1;\n  if((fd0 = fdalloc(rf)) < 0 || (fd1 = fdalloc(wf)) < 0){\n    if(fd0 >= 0)\n      myproc()->ofile[fd0] = 0;\n    fileclose(rf);\n    fileclose(wf);\n    return -1;\n  }\n  fd[0] = fd0;\n  fd[1] = fd1;\n  return 0;\n}\n"
  },
  {
    "path": "sysproc.c",
    "content": "#include \"types.h\"\n#include \"x86.h\"\n#include \"defs.h\"\n#include \"date.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n\nint\nsys_fork(void)\n{\n  return fork();\n}\n\nint\nsys_exit(void)\n{\n  exit();\n  return 0;  // not reached\n}\n\nint\nsys_wait(void)\n{\n  return wait();\n}\n\nint\nsys_kill(void)\n{\n  int pid;\n\n  if(argint(0, &pid) < 0)\n    return -1;\n  return kill(pid);\n}\n\nint\nsys_getpid(void)\n{\n  return myproc()->pid;\n}\n\nint\nsys_sbrk(void)\n{\n  int addr;\n  int n;\n\n  if(argint(0, &n) < 0)\n    return -1;\n  addr = myproc()->sz;\n  if(growproc(n) < 0)\n    return -1;\n  return addr;\n}\n\nint\nsys_sleep(void)\n{\n  int n;\n  uint ticks0;\n\n  if(argint(0, &n) < 0)\n    return -1;\n  acquire(&tickslock);\n  ticks0 = ticks;\n  while(ticks - ticks0 < n){\n    if(myproc()->killed){\n      release(&tickslock);\n      return -1;\n    }\n    sleep(&ticks, &tickslock);\n  }\n  release(&tickslock);\n  return 0;\n}\n\n// return how many clock tick interrupts have occurred\n// since start.\nint\nsys_uptime(void)\n{\n  uint xticks;\n\n  acquire(&tickslock);\n  xticks = ticks;\n  release(&tickslock);\n  return xticks;\n}\n"
  },
  {
    "path": "toc.ftr",
    "content": "\n\nThe source listing is preceded by a cross-reference that lists every defined \nconstant, struct, global variable, and function in xv6.  Each entry gives,\non the same line as the name, the line number (or, in a few cases, numbers)\nwhere the name is defined.  Successive lines in an entry list the line\nnumbers where the name is used.  For example, this entry:\n\n    swtch 2658\n        0374 2428 2466 2657 2658\n\nindicates that swtch is defined on line 2658 and is mentioned on five lines\non sheets 03, 24, and 26.\n"
  },
  {
    "path": "toc.hdr",
    "content": "The numbers to the left of the file names in the table are sheet numbers.\nThe source code has been printed in a double column format with fifty\nlines per column, giving one hundred lines per sheet (or page).\nThus there is a convenient relationship between line numbers and sheet numbers.\n\n\n"
  },
  {
    "path": "trap.c",
    "content": "#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n#include \"traps.h\"\n#include \"spinlock.h\"\n\n// Interrupt descriptor table (shared by all CPUs).\nstruct gatedesc idt[256];\nextern uint vectors[];  // in vectors.S: array of 256 entry pointers\nstruct spinlock tickslock;\nuint ticks;\n\nvoid\ntvinit(void)\n{\n  int i;\n\n  for(i = 0; i < 256; i++)\n    SETGATE(idt[i], 0, SEG_KCODE<<3, vectors[i], 0);\n  SETGATE(idt[T_SYSCALL], 1, SEG_KCODE<<3, vectors[T_SYSCALL], DPL_USER);\n\n  initlock(&tickslock, \"time\");\n}\n\nvoid\nidtinit(void)\n{\n  lidt(idt, sizeof(idt));\n}\n\n//PAGEBREAK: 41\nvoid\ntrap(struct trapframe *tf)\n{\n  if(tf->trapno == T_SYSCALL){\n    if(myproc()->killed)\n      exit();\n    myproc()->tf = tf;\n    syscall();\n    if(myproc()->killed)\n      exit();\n    return;\n  }\n\n  switch(tf->trapno){\n  case T_IRQ0 + IRQ_TIMER:\n    if(cpuid() == 0){\n      acquire(&tickslock);\n      ticks++;\n      wakeup(&ticks);\n      release(&tickslock);\n    }\n    lapiceoi();\n    break;\n  case T_IRQ0 + IRQ_IDE:\n    ideintr();\n    lapiceoi();\n    break;\n  case T_IRQ0 + IRQ_IDE+1:\n    // Bochs generates spurious IDE1 interrupts.\n    break;\n  case T_IRQ0 + IRQ_KBD:\n    kbdintr();\n    lapiceoi();\n    break;\n  case T_IRQ0 + IRQ_COM1:\n    uartintr();\n    lapiceoi();\n    break;\n  case T_IRQ0 + 7:\n  case T_IRQ0 + IRQ_SPURIOUS:\n    cprintf(\"cpu%d: spurious interrupt at %x:%x\\n\",\n            cpuid(), tf->cs, tf->eip);\n    lapiceoi();\n    break;\n\n  //PAGEBREAK: 13\n  default:\n    if(myproc() == 0 || (tf->cs&3) == 0){\n      // In kernel, it must be our mistake.\n      cprintf(\"unexpected trap %d from cpu %d eip %x (cr2=0x%x)\\n\",\n              tf->trapno, cpuid(), tf->eip, rcr2());\n      panic(\"trap\");\n    }\n    // In user space, assume process misbehaved.\n    cprintf(\"pid %d %s: trap %d err %d on cpu %d \"\n            \"eip 0x%x addr 0x%x--kill proc\\n\",\n            myproc()->pid, myproc()->name, tf->trapno,\n            tf->err, cpuid(), tf->eip, rcr2());\n    myproc()->killed = 1;\n  }\n\n  // Force process exit if it has been killed and is in user space.\n  // (If it is still executing in the kernel, let it keep running\n  // until it gets to the regular system call return.)\n  if(myproc() && myproc()->killed && (tf->cs&3) == DPL_USER)\n    exit();\n\n  // Force process to give up CPU on clock tick.\n  // If interrupts were on while locks held, would need to check nlock.\n  if(myproc() && myproc()->state == RUNNING &&\n     tf->trapno == T_IRQ0+IRQ_TIMER)\n    yield();\n\n  // Check if the process has been killed since we yielded\n  if(myproc() && myproc()->killed && (tf->cs&3) == DPL_USER)\n    exit();\n}\n"
  },
  {
    "path": "trapasm.S",
    "content": "#include \"mmu.h\"\n\n  # vectors.S sends all traps here.\n.globl alltraps\nalltraps:\n  # Build trap frame.\n  pushl %ds\n  pushl %es\n  pushl %fs\n  pushl %gs\n  pushal\n  \n  # Set up data segments.\n  movw $(SEG_KDATA<<3), %ax\n  movw %ax, %ds\n  movw %ax, %es\n\n  # Call trap(tf), where tf=%esp\n  pushl %esp\n  call trap\n  addl $4, %esp\n\n  # Return falls through to trapret...\n.globl trapret\ntrapret:\n  popal\n  popl %gs\n  popl %fs\n  popl %es\n  popl %ds\n  addl $0x8, %esp  # trapno and errcode\n  iret\n"
  },
  {
    "path": "traps.h",
    "content": "// x86 trap and interrupt constants.\n\n// Processor-defined:\n#define T_DIVIDE         0      // divide error\n#define T_DEBUG          1      // debug exception\n#define T_NMI            2      // non-maskable interrupt\n#define T_BRKPT          3      // breakpoint\n#define T_OFLOW          4      // overflow\n#define T_BOUND          5      // bounds check\n#define T_ILLOP          6      // illegal opcode\n#define T_DEVICE         7      // device not available\n#define T_DBLFLT         8      // double fault\n// #define T_COPROC      9      // reserved (not used since 486)\n#define T_TSS           10      // invalid task switch segment\n#define T_SEGNP         11      // segment not present\n#define T_STACK         12      // stack exception\n#define T_GPFLT         13      // general protection fault\n#define T_PGFLT         14      // page fault\n// #define T_RES        15      // reserved\n#define T_FPERR         16      // floating point error\n#define T_ALIGN         17      // aligment check\n#define T_MCHK          18      // machine check\n#define T_SIMDERR       19      // SIMD floating point error\n\n// These are arbitrarily chosen, but with care not to overlap\n// processor defined exceptions or interrupt vectors.\n#define T_SYSCALL       64      // system call\n#define T_DEFAULT      500      // catchall\n\n#define T_IRQ0          32      // IRQ 0 corresponds to int T_IRQ\n\n#define IRQ_TIMER        0\n#define IRQ_KBD          1\n#define IRQ_COM1         4\n#define IRQ_IDE         14\n#define IRQ_ERROR       19\n#define IRQ_SPURIOUS    31\n\n"
  },
  {
    "path": "types.h",
    "content": "typedef unsigned int   uint;\ntypedef unsigned short ushort;\ntypedef unsigned char  uchar;\ntypedef uint pde_t;\n"
  },
  {
    "path": "uart.c",
    "content": "// Intel 8250 serial port (UART).\n\n#include \"types.h\"\n#include \"defs.h\"\n#include \"param.h\"\n#include \"traps.h\"\n#include \"spinlock.h\"\n#include \"sleeplock.h\"\n#include \"fs.h\"\n#include \"file.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"x86.h\"\n\n#define COM1    0x3f8\n\nstatic int uart;    // is there a uart?\n\nvoid\nuartinit(void)\n{\n  char *p;\n\n  // Turn off the FIFO\n  outb(COM1+2, 0);\n\n  // 9600 baud, 8 data bits, 1 stop bit, parity off.\n  outb(COM1+3, 0x80);    // Unlock divisor\n  outb(COM1+0, 115200/9600);\n  outb(COM1+1, 0);\n  outb(COM1+3, 0x03);    // Lock divisor, 8 data bits.\n  outb(COM1+4, 0);\n  outb(COM1+1, 0x01);    // Enable receive interrupts.\n\n  // If status is 0xFF, no serial port.\n  if(inb(COM1+5) == 0xFF)\n    return;\n  uart = 1;\n\n  // Acknowledge pre-existing interrupt conditions;\n  // enable interrupts.\n  inb(COM1+2);\n  inb(COM1+0);\n  ioapicenable(IRQ_COM1, 0);\n\n  // Announce that we're here.\n  for(p=\"xv6...\\n\"; *p; p++)\n    uartputc(*p);\n}\n\nvoid\nuartputc(int c)\n{\n  int i;\n\n  if(!uart)\n    return;\n  for(i = 0; i < 128 && !(inb(COM1+5) & 0x20); i++)\n    microdelay(10);\n  outb(COM1+0, c);\n}\n\nstatic int\nuartgetc(void)\n{\n  if(!uart)\n    return -1;\n  if(!(inb(COM1+5) & 0x01))\n    return -1;\n  return inb(COM1+0);\n}\n\nvoid\nuartintr(void)\n{\n  consoleintr(uartgetc);\n}\n"
  },
  {
    "path": "ulib.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"fcntl.h\"\n#include \"user.h\"\n#include \"x86.h\"\n\nchar*\nstrcpy(char *s, const char *t)\n{\n  char *os;\n\n  os = s;\n  while((*s++ = *t++) != 0)\n    ;\n  return os;\n}\n\nint\nstrcmp(const char *p, const char *q)\n{\n  while(*p && *p == *q)\n    p++, q++;\n  return (uchar)*p - (uchar)*q;\n}\n\nuint\nstrlen(const char *s)\n{\n  int n;\n\n  for(n = 0; s[n]; n++)\n    ;\n  return n;\n}\n\nvoid*\nmemset(void *dst, int c, uint n)\n{\n  stosb(dst, c, n);\n  return dst;\n}\n\nchar*\nstrchr(const char *s, char c)\n{\n  for(; *s; s++)\n    if(*s == c)\n      return (char*)s;\n  return 0;\n}\n\nchar*\ngets(char *buf, int max)\n{\n  int i, cc;\n  char c;\n\n  for(i=0; i+1 < max; ){\n    cc = read(0, &c, 1);\n    if(cc < 1)\n      break;\n    buf[i++] = c;\n    if(c == '\\n' || c == '\\r')\n      break;\n  }\n  buf[i] = '\\0';\n  return buf;\n}\n\nint\nstat(const char *n, struct stat *st)\n{\n  int fd;\n  int r;\n\n  fd = open(n, O_RDONLY);\n  if(fd < 0)\n    return -1;\n  r = fstat(fd, st);\n  close(fd);\n  return r;\n}\n\nint\natoi(const char *s)\n{\n  int n;\n\n  n = 0;\n  while('0' <= *s && *s <= '9')\n    n = n*10 + *s++ - '0';\n  return n;\n}\n\nvoid*\nmemmove(void *vdst, const void *vsrc, int n)\n{\n  char *dst;\n  const char *src;\n\n  dst = vdst;\n  src = vsrc;\n  while(n-- > 0)\n    *dst++ = *src++;\n  return vdst;\n}\n"
  },
  {
    "path": "umalloc.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"param.h\"\n\n// Memory allocator by Kernighan and Ritchie,\n// The C programming Language, 2nd ed.  Section 8.7.\n\ntypedef long Align;\n\nunion header {\n  struct {\n    union header *ptr;\n    uint size;\n  } s;\n  Align x;\n};\n\ntypedef union header Header;\n\nstatic Header base;\nstatic Header *freep;\n\nvoid\nfree(void *ap)\n{\n  Header *bp, *p;\n\n  bp = (Header*)ap - 1;\n  for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)\n    if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))\n      break;\n  if(bp + bp->s.size == p->s.ptr){\n    bp->s.size += p->s.ptr->s.size;\n    bp->s.ptr = p->s.ptr->s.ptr;\n  } else\n    bp->s.ptr = p->s.ptr;\n  if(p + p->s.size == bp){\n    p->s.size += bp->s.size;\n    p->s.ptr = bp->s.ptr;\n  } else\n    p->s.ptr = bp;\n  freep = p;\n}\n\nstatic Header*\nmorecore(uint nu)\n{\n  char *p;\n  Header *hp;\n\n  if(nu < 4096)\n    nu = 4096;\n  p = sbrk(nu * sizeof(Header));\n  if(p == (char*)-1)\n    return 0;\n  hp = (Header*)p;\n  hp->s.size = nu;\n  free((void*)(hp + 1));\n  return freep;\n}\n\nvoid*\nmalloc(uint nbytes)\n{\n  Header *p, *prevp;\n  uint nunits;\n\n  nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;\n  if((prevp = freep) == 0){\n    base.s.ptr = freep = prevp = &base;\n    base.s.size = 0;\n  }\n  for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){\n    if(p->s.size >= nunits){\n      if(p->s.size == nunits)\n        prevp->s.ptr = p->s.ptr;\n      else {\n        p->s.size -= nunits;\n        p += p->s.size;\n        p->s.size = nunits;\n      }\n      freep = prevp;\n      return (void*)(p + 1);\n    }\n    if(p == freep)\n      if((p = morecore(nunits)) == 0)\n        return 0;\n  }\n}\n"
  },
  {
    "path": "user.h",
    "content": "struct stat;\nstruct rtcdate;\n\n// system calls\nint fork(void);\nint exit(void) __attribute__((noreturn));\nint wait(void);\nint pipe(int*);\nint write(int, const void*, int);\nint read(int, void*, int);\nint close(int);\nint kill(int);\nint exec(char*, char**);\nint open(const char*, int);\nint mknod(const char*, short, short);\nint unlink(const char*);\nint fstat(int fd, struct stat*);\nint link(const char*, const char*);\nint mkdir(const char*);\nint chdir(const char*);\nint dup(int);\nint getpid(void);\nchar* sbrk(int);\nint sleep(int);\nint uptime(void);\n\n// ulib.c\nint stat(const char*, struct stat*);\nchar* strcpy(char*, const char*);\nvoid *memmove(void*, const void*, int);\nchar* strchr(const char*, char c);\nint strcmp(const char*, const char*);\nvoid printf(int, const char*, ...);\nchar* gets(char*, int max);\nuint strlen(const char*);\nvoid* memset(void*, int, uint);\nvoid* malloc(uint);\nvoid free(void*);\nint atoi(const char*);\n"
  },
  {
    "path": "usertests.c",
    "content": "#include \"param.h\"\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n#include \"fs.h\"\n#include \"fcntl.h\"\n#include \"syscall.h\"\n#include \"traps.h\"\n#include \"memlayout.h\"\n\nchar buf[8192];\nchar name[3];\nchar *echoargv[] = { \"echo\", \"ALL\", \"TESTS\", \"PASSED\", 0 };\nint stdout = 1;\n\n// does chdir() call iput(p->cwd) in a transaction?\nvoid\niputtest(void)\n{\n  printf(stdout, \"iput test\\n\");\n\n  if(mkdir(\"iputdir\") < 0){\n    printf(stdout, \"mkdir failed\\n\");\n    exit();\n  }\n  if(chdir(\"iputdir\") < 0){\n    printf(stdout, \"chdir iputdir failed\\n\");\n    exit();\n  }\n  if(unlink(\"../iputdir\") < 0){\n    printf(stdout, \"unlink ../iputdir failed\\n\");\n    exit();\n  }\n  if(chdir(\"/\") < 0){\n    printf(stdout, \"chdir / failed\\n\");\n    exit();\n  }\n  printf(stdout, \"iput test ok\\n\");\n}\n\n// does exit() call iput(p->cwd) in a transaction?\nvoid\nexitiputtest(void)\n{\n  int pid;\n\n  printf(stdout, \"exitiput test\\n\");\n\n  pid = fork();\n  if(pid < 0){\n    printf(stdout, \"fork failed\\n\");\n    exit();\n  }\n  if(pid == 0){\n    if(mkdir(\"iputdir\") < 0){\n      printf(stdout, \"mkdir failed\\n\");\n      exit();\n    }\n    if(chdir(\"iputdir\") < 0){\n      printf(stdout, \"child chdir failed\\n\");\n      exit();\n    }\n    if(unlink(\"../iputdir\") < 0){\n      printf(stdout, \"unlink ../iputdir failed\\n\");\n      exit();\n    }\n    exit();\n  }\n  wait();\n  printf(stdout, \"exitiput test ok\\n\");\n}\n\n// does the error path in open() for attempt to write a\n// directory call iput() in a transaction?\n// needs a hacked kernel that pauses just after the namei()\n// call in sys_open():\n//    if((ip = namei(path)) == 0)\n//      return -1;\n//    {\n//      int i;\n//      for(i = 0; i < 10000; i++)\n//        yield();\n//    }\nvoid\nopeniputtest(void)\n{\n  int pid;\n\n  printf(stdout, \"openiput test\\n\");\n  if(mkdir(\"oidir\") < 0){\n    printf(stdout, \"mkdir oidir failed\\n\");\n    exit();\n  }\n  pid = fork();\n  if(pid < 0){\n    printf(stdout, \"fork failed\\n\");\n    exit();\n  }\n  if(pid == 0){\n    int fd = open(\"oidir\", O_RDWR);\n    if(fd >= 0){\n      printf(stdout, \"open directory for write succeeded\\n\");\n      exit();\n    }\n    exit();\n  }\n  sleep(1);\n  if(unlink(\"oidir\") != 0){\n    printf(stdout, \"unlink failed\\n\");\n    exit();\n  }\n  wait();\n  printf(stdout, \"openiput test ok\\n\");\n}\n\n// simple file system tests\n\nvoid\nopentest(void)\n{\n  int fd;\n\n  printf(stdout, \"open test\\n\");\n  fd = open(\"echo\", 0);\n  if(fd < 0){\n    printf(stdout, \"open echo failed!\\n\");\n    exit();\n  }\n  close(fd);\n  fd = open(\"doesnotexist\", 0);\n  if(fd >= 0){\n    printf(stdout, \"open doesnotexist succeeded!\\n\");\n    exit();\n  }\n  printf(stdout, \"open test ok\\n\");\n}\n\nvoid\nwritetest(void)\n{\n  int fd;\n  int i;\n\n  printf(stdout, \"small file test\\n\");\n  fd = open(\"small\", O_CREATE|O_RDWR);\n  if(fd >= 0){\n    printf(stdout, \"creat small succeeded; ok\\n\");\n  } else {\n    printf(stdout, \"error: creat small failed!\\n\");\n    exit();\n  }\n  for(i = 0; i < 100; i++){\n    if(write(fd, \"aaaaaaaaaa\", 10) != 10){\n      printf(stdout, \"error: write aa %d new file failed\\n\", i);\n      exit();\n    }\n    if(write(fd, \"bbbbbbbbbb\", 10) != 10){\n      printf(stdout, \"error: write bb %d new file failed\\n\", i);\n      exit();\n    }\n  }\n  printf(stdout, \"writes ok\\n\");\n  close(fd);\n  fd = open(\"small\", O_RDONLY);\n  if(fd >= 0){\n    printf(stdout, \"open small succeeded ok\\n\");\n  } else {\n    printf(stdout, \"error: open small failed!\\n\");\n    exit();\n  }\n  i = read(fd, buf, 2000);\n  if(i == 2000){\n    printf(stdout, \"read succeeded ok\\n\");\n  } else {\n    printf(stdout, \"read failed\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(unlink(\"small\") < 0){\n    printf(stdout, \"unlink small failed\\n\");\n    exit();\n  }\n  printf(stdout, \"small file test ok\\n\");\n}\n\nvoid\nwritetest1(void)\n{\n  int i, fd, n;\n\n  printf(stdout, \"big files test\\n\");\n\n  fd = open(\"big\", O_CREATE|O_RDWR);\n  if(fd < 0){\n    printf(stdout, \"error: creat big failed!\\n\");\n    exit();\n  }\n\n  for(i = 0; i < MAXFILE; i++){\n    ((int*)buf)[0] = i;\n    if(write(fd, buf, 512) != 512){\n      printf(stdout, \"error: write big file failed\\n\", i);\n      exit();\n    }\n  }\n\n  close(fd);\n\n  fd = open(\"big\", O_RDONLY);\n  if(fd < 0){\n    printf(stdout, \"error: open big failed!\\n\");\n    exit();\n  }\n\n  n = 0;\n  for(;;){\n    i = read(fd, buf, 512);\n    if(i == 0){\n      if(n == MAXFILE - 1){\n        printf(stdout, \"read only %d blocks from big\", n);\n        exit();\n      }\n      break;\n    } else if(i != 512){\n      printf(stdout, \"read failed %d\\n\", i);\n      exit();\n    }\n    if(((int*)buf)[0] != n){\n      printf(stdout, \"read content of block %d is %d\\n\",\n             n, ((int*)buf)[0]);\n      exit();\n    }\n    n++;\n  }\n  close(fd);\n  if(unlink(\"big\") < 0){\n    printf(stdout, \"unlink big failed\\n\");\n    exit();\n  }\n  printf(stdout, \"big files ok\\n\");\n}\n\nvoid\ncreatetest(void)\n{\n  int i, fd;\n\n  printf(stdout, \"many creates, followed by unlink test\\n\");\n\n  name[0] = 'a';\n  name[2] = '\\0';\n  for(i = 0; i < 52; i++){\n    name[1] = '0' + i;\n    fd = open(name, O_CREATE|O_RDWR);\n    close(fd);\n  }\n  name[0] = 'a';\n  name[2] = '\\0';\n  for(i = 0; i < 52; i++){\n    name[1] = '0' + i;\n    unlink(name);\n  }\n  printf(stdout, \"many creates, followed by unlink; ok\\n\");\n}\n\nvoid dirtest(void)\n{\n  printf(stdout, \"mkdir test\\n\");\n\n  if(mkdir(\"dir0\") < 0){\n    printf(stdout, \"mkdir failed\\n\");\n    exit();\n  }\n\n  if(chdir(\"dir0\") < 0){\n    printf(stdout, \"chdir dir0 failed\\n\");\n    exit();\n  }\n\n  if(chdir(\"..\") < 0){\n    printf(stdout, \"chdir .. failed\\n\");\n    exit();\n  }\n\n  if(unlink(\"dir0\") < 0){\n    printf(stdout, \"unlink dir0 failed\\n\");\n    exit();\n  }\n  printf(stdout, \"mkdir test ok\\n\");\n}\n\nvoid\nexectest(void)\n{\n  printf(stdout, \"exec test\\n\");\n  if(exec(\"echo\", echoargv) < 0){\n    printf(stdout, \"exec echo failed\\n\");\n    exit();\n  }\n}\n\n// simple fork and pipe read/write\n\nvoid\npipe1(void)\n{\n  int fds[2], pid;\n  int seq, i, n, cc, total;\n\n  if(pipe(fds) != 0){\n    printf(1, \"pipe() failed\\n\");\n    exit();\n  }\n  pid = fork();\n  seq = 0;\n  if(pid == 0){\n    close(fds[0]);\n    for(n = 0; n < 5; n++){\n      for(i = 0; i < 1033; i++)\n        buf[i] = seq++;\n      if(write(fds[1], buf, 1033) != 1033){\n        printf(1, \"pipe1 oops 1\\n\");\n        exit();\n      }\n    }\n    exit();\n  } else if(pid > 0){\n    close(fds[1]);\n    total = 0;\n    cc = 1;\n    while((n = read(fds[0], buf, cc)) > 0){\n      for(i = 0; i < n; i++){\n        if((buf[i] & 0xff) != (seq++ & 0xff)){\n          printf(1, \"pipe1 oops 2\\n\");\n          return;\n        }\n      }\n      total += n;\n      cc = cc * 2;\n      if(cc > sizeof(buf))\n        cc = sizeof(buf);\n    }\n    if(total != 5 * 1033){\n      printf(1, \"pipe1 oops 3 total %d\\n\", total);\n      exit();\n    }\n    close(fds[0]);\n    wait();\n  } else {\n    printf(1, \"fork() failed\\n\");\n    exit();\n  }\n  printf(1, \"pipe1 ok\\n\");\n}\n\n// meant to be run w/ at most two CPUs\nvoid\npreempt(void)\n{\n  int pid1, pid2, pid3;\n  int pfds[2];\n\n  printf(1, \"preempt: \");\n  pid1 = fork();\n  if(pid1 == 0)\n    for(;;)\n      ;\n\n  pid2 = fork();\n  if(pid2 == 0)\n    for(;;)\n      ;\n\n  pipe(pfds);\n  pid3 = fork();\n  if(pid3 == 0){\n    close(pfds[0]);\n    if(write(pfds[1], \"x\", 1) != 1)\n      printf(1, \"preempt write error\");\n    close(pfds[1]);\n    for(;;)\n      ;\n  }\n\n  close(pfds[1]);\n  if(read(pfds[0], buf, sizeof(buf)) != 1){\n    printf(1, \"preempt read error\");\n    return;\n  }\n  close(pfds[0]);\n  printf(1, \"kill... \");\n  kill(pid1);\n  kill(pid2);\n  kill(pid3);\n  printf(1, \"wait... \");\n  wait();\n  wait();\n  wait();\n  printf(1, \"preempt ok\\n\");\n}\n\n// try to find any races between exit and wait\nvoid\nexitwait(void)\n{\n  int i, pid;\n\n  for(i = 0; i < 100; i++){\n    pid = fork();\n    if(pid < 0){\n      printf(1, \"fork failed\\n\");\n      return;\n    }\n    if(pid){\n      if(wait() != pid){\n        printf(1, \"wait wrong pid\\n\");\n        return;\n      }\n    } else {\n      exit();\n    }\n  }\n  printf(1, \"exitwait ok\\n\");\n}\n\nvoid\nmem(void)\n{\n  void *m1, *m2;\n  int pid, ppid;\n\n  printf(1, \"mem test\\n\");\n  ppid = getpid();\n  if((pid = fork()) == 0){\n    m1 = 0;\n    while((m2 = malloc(10001)) != 0){\n      *(char**)m2 = m1;\n      m1 = m2;\n    }\n    while(m1){\n      m2 = *(char**)m1;\n      free(m1);\n      m1 = m2;\n    }\n    m1 = malloc(1024*20);\n    if(m1 == 0){\n      printf(1, \"couldn't allocate mem?!!\\n\");\n      kill(ppid);\n      exit();\n    }\n    free(m1);\n    printf(1, \"mem ok\\n\");\n    exit();\n  } else {\n    wait();\n  }\n}\n\n// More file system tests\n\n// two processes write to the same file descriptor\n// is the offset shared? does inode locking work?\nvoid\nsharedfd(void)\n{\n  int fd, pid, i, n, nc, np;\n  char buf[10];\n\n  printf(1, \"sharedfd test\\n\");\n\n  unlink(\"sharedfd\");\n  fd = open(\"sharedfd\", O_CREATE|O_RDWR);\n  if(fd < 0){\n    printf(1, \"fstests: cannot open sharedfd for writing\");\n    return;\n  }\n  pid = fork();\n  memset(buf, pid==0?'c':'p', sizeof(buf));\n  for(i = 0; i < 1000; i++){\n    if(write(fd, buf, sizeof(buf)) != sizeof(buf)){\n      printf(1, \"fstests: write sharedfd failed\\n\");\n      break;\n    }\n  }\n  if(pid == 0)\n    exit();\n  else\n    wait();\n  close(fd);\n  fd = open(\"sharedfd\", 0);\n  if(fd < 0){\n    printf(1, \"fstests: cannot open sharedfd for reading\\n\");\n    return;\n  }\n  nc = np = 0;\n  while((n = read(fd, buf, sizeof(buf))) > 0){\n    for(i = 0; i < sizeof(buf); i++){\n      if(buf[i] == 'c')\n        nc++;\n      if(buf[i] == 'p')\n        np++;\n    }\n  }\n  close(fd);\n  unlink(\"sharedfd\");\n  if(nc == 10000 && np == 10000){\n    printf(1, \"sharedfd ok\\n\");\n  } else {\n    printf(1, \"sharedfd oops %d %d\\n\", nc, np);\n    exit();\n  }\n}\n\n// four processes write different files at the same\n// time, to test block allocation.\nvoid\nfourfiles(void)\n{\n  int fd, pid, i, j, n, total, pi;\n  char *names[] = { \"f0\", \"f1\", \"f2\", \"f3\" };\n  char *fname;\n\n  printf(1, \"fourfiles test\\n\");\n\n  for(pi = 0; pi < 4; pi++){\n    fname = names[pi];\n    unlink(fname);\n\n    pid = fork();\n    if(pid < 0){\n      printf(1, \"fork failed\\n\");\n      exit();\n    }\n\n    if(pid == 0){\n      fd = open(fname, O_CREATE | O_RDWR);\n      if(fd < 0){\n        printf(1, \"create failed\\n\");\n        exit();\n      }\n\n      memset(buf, '0'+pi, 512);\n      for(i = 0; i < 12; i++){\n        if((n = write(fd, buf, 500)) != 500){\n          printf(1, \"write failed %d\\n\", n);\n          exit();\n        }\n      }\n      exit();\n    }\n  }\n\n  for(pi = 0; pi < 4; pi++){\n    wait();\n  }\n\n  for(i = 0; i < 2; i++){\n    fname = names[i];\n    fd = open(fname, 0);\n    total = 0;\n    while((n = read(fd, buf, sizeof(buf))) > 0){\n      for(j = 0; j < n; j++){\n        if(buf[j] != '0'+i){\n          printf(1, \"wrong char\\n\");\n          exit();\n        }\n      }\n      total += n;\n    }\n    close(fd);\n    if(total != 12*500){\n      printf(1, \"wrong length %d\\n\", total);\n      exit();\n    }\n    unlink(fname);\n  }\n\n  printf(1, \"fourfiles ok\\n\");\n}\n\n// four processes create and delete different files in same directory\nvoid\ncreatedelete(void)\n{\n  enum { N = 20 };\n  int pid, i, fd, pi;\n  char name[32];\n\n  printf(1, \"createdelete test\\n\");\n\n  for(pi = 0; pi < 4; pi++){\n    pid = fork();\n    if(pid < 0){\n      printf(1, \"fork failed\\n\");\n      exit();\n    }\n\n    if(pid == 0){\n      name[0] = 'p' + pi;\n      name[2] = '\\0';\n      for(i = 0; i < N; i++){\n        name[1] = '0' + i;\n        fd = open(name, O_CREATE | O_RDWR);\n        if(fd < 0){\n          printf(1, \"create failed\\n\");\n          exit();\n        }\n        close(fd);\n        if(i > 0 && (i % 2 ) == 0){\n          name[1] = '0' + (i / 2);\n          if(unlink(name) < 0){\n            printf(1, \"unlink failed\\n\");\n            exit();\n          }\n        }\n      }\n      exit();\n    }\n  }\n\n  for(pi = 0; pi < 4; pi++){\n    wait();\n  }\n\n  name[0] = name[1] = name[2] = 0;\n  for(i = 0; i < N; i++){\n    for(pi = 0; pi < 4; pi++){\n      name[0] = 'p' + pi;\n      name[1] = '0' + i;\n      fd = open(name, 0);\n      if((i == 0 || i >= N/2) && fd < 0){\n        printf(1, \"oops createdelete %s didn't exist\\n\", name);\n        exit();\n      } else if((i >= 1 && i < N/2) && fd >= 0){\n        printf(1, \"oops createdelete %s did exist\\n\", name);\n        exit();\n      }\n      if(fd >= 0)\n        close(fd);\n    }\n  }\n\n  for(i = 0; i < N; i++){\n    for(pi = 0; pi < 4; pi++){\n      name[0] = 'p' + i;\n      name[1] = '0' + i;\n      unlink(name);\n    }\n  }\n\n  printf(1, \"createdelete ok\\n\");\n}\n\n// can I unlink a file and still read it?\nvoid\nunlinkread(void)\n{\n  int fd, fd1;\n\n  printf(1, \"unlinkread test\\n\");\n  fd = open(\"unlinkread\", O_CREATE | O_RDWR);\n  if(fd < 0){\n    printf(1, \"create unlinkread failed\\n\");\n    exit();\n  }\n  write(fd, \"hello\", 5);\n  close(fd);\n\n  fd = open(\"unlinkread\", O_RDWR);\n  if(fd < 0){\n    printf(1, \"open unlinkread failed\\n\");\n    exit();\n  }\n  if(unlink(\"unlinkread\") != 0){\n    printf(1, \"unlink unlinkread failed\\n\");\n    exit();\n  }\n\n  fd1 = open(\"unlinkread\", O_CREATE | O_RDWR);\n  write(fd1, \"yyy\", 3);\n  close(fd1);\n\n  if(read(fd, buf, sizeof(buf)) != 5){\n    printf(1, \"unlinkread read failed\");\n    exit();\n  }\n  if(buf[0] != 'h'){\n    printf(1, \"unlinkread wrong data\\n\");\n    exit();\n  }\n  if(write(fd, buf, 10) != 10){\n    printf(1, \"unlinkread write failed\\n\");\n    exit();\n  }\n  close(fd);\n  unlink(\"unlinkread\");\n  printf(1, \"unlinkread ok\\n\");\n}\n\nvoid\nlinktest(void)\n{\n  int fd;\n\n  printf(1, \"linktest\\n\");\n\n  unlink(\"lf1\");\n  unlink(\"lf2\");\n\n  fd = open(\"lf1\", O_CREATE|O_RDWR);\n  if(fd < 0){\n    printf(1, \"create lf1 failed\\n\");\n    exit();\n  }\n  if(write(fd, \"hello\", 5) != 5){\n    printf(1, \"write lf1 failed\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(link(\"lf1\", \"lf2\") < 0){\n    printf(1, \"link lf1 lf2 failed\\n\");\n    exit();\n  }\n  unlink(\"lf1\");\n\n  if(open(\"lf1\", 0) >= 0){\n    printf(1, \"unlinked lf1 but it is still there!\\n\");\n    exit();\n  }\n\n  fd = open(\"lf2\", 0);\n  if(fd < 0){\n    printf(1, \"open lf2 failed\\n\");\n    exit();\n  }\n  if(read(fd, buf, sizeof(buf)) != 5){\n    printf(1, \"read lf2 failed\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(link(\"lf2\", \"lf2\") >= 0){\n    printf(1, \"link lf2 lf2 succeeded! oops\\n\");\n    exit();\n  }\n\n  unlink(\"lf2\");\n  if(link(\"lf2\", \"lf1\") >= 0){\n    printf(1, \"link non-existant succeeded! oops\\n\");\n    exit();\n  }\n\n  if(link(\".\", \"lf1\") >= 0){\n    printf(1, \"link . lf1 succeeded! oops\\n\");\n    exit();\n  }\n\n  printf(1, \"linktest ok\\n\");\n}\n\n// test concurrent create/link/unlink of the same file\nvoid\nconcreate(void)\n{\n  char file[3];\n  int i, pid, n, fd;\n  char fa[40];\n  struct {\n    ushort inum;\n    char name[14];\n  } de;\n\n  printf(1, \"concreate test\\n\");\n  file[0] = 'C';\n  file[2] = '\\0';\n  for(i = 0; i < 40; i++){\n    file[1] = '0' + i;\n    unlink(file);\n    pid = fork();\n    if(pid && (i % 3) == 1){\n      link(\"C0\", file);\n    } else if(pid == 0 && (i % 5) == 1){\n      link(\"C0\", file);\n    } else {\n      fd = open(file, O_CREATE | O_RDWR);\n      if(fd < 0){\n        printf(1, \"concreate create %s failed\\n\", file);\n        exit();\n      }\n      close(fd);\n    }\n    if(pid == 0)\n      exit();\n    else\n      wait();\n  }\n\n  memset(fa, 0, sizeof(fa));\n  fd = open(\".\", 0);\n  n = 0;\n  while(read(fd, &de, sizeof(de)) > 0){\n    if(de.inum == 0)\n      continue;\n    if(de.name[0] == 'C' && de.name[2] == '\\0'){\n      i = de.name[1] - '0';\n      if(i < 0 || i >= sizeof(fa)){\n        printf(1, \"concreate weird file %s\\n\", de.name);\n        exit();\n      }\n      if(fa[i]){\n        printf(1, \"concreate duplicate file %s\\n\", de.name);\n        exit();\n      }\n      fa[i] = 1;\n      n++;\n    }\n  }\n  close(fd);\n\n  if(n != 40){\n    printf(1, \"concreate not enough files in directory listing\\n\");\n    exit();\n  }\n\n  for(i = 0; i < 40; i++){\n    file[1] = '0' + i;\n    pid = fork();\n    if(pid < 0){\n      printf(1, \"fork failed\\n\");\n      exit();\n    }\n    if(((i % 3) == 0 && pid == 0) ||\n       ((i % 3) == 1 && pid != 0)){\n      close(open(file, 0));\n      close(open(file, 0));\n      close(open(file, 0));\n      close(open(file, 0));\n    } else {\n      unlink(file);\n      unlink(file);\n      unlink(file);\n      unlink(file);\n    }\n    if(pid == 0)\n      exit();\n    else\n      wait();\n  }\n\n  printf(1, \"concreate ok\\n\");\n}\n\n// another concurrent link/unlink/create test,\n// to look for deadlocks.\nvoid\nlinkunlink()\n{\n  int pid, i;\n\n  printf(1, \"linkunlink test\\n\");\n\n  unlink(\"x\");\n  pid = fork();\n  if(pid < 0){\n    printf(1, \"fork failed\\n\");\n    exit();\n  }\n\n  unsigned int x = (pid ? 1 : 97);\n  for(i = 0; i < 100; i++){\n    x = x * 1103515245 + 12345;\n    if((x % 3) == 0){\n      close(open(\"x\", O_RDWR | O_CREATE));\n    } else if((x % 3) == 1){\n      link(\"cat\", \"x\");\n    } else {\n      unlink(\"x\");\n    }\n  }\n\n  if(pid)\n    wait();\n  else\n    exit();\n\n  printf(1, \"linkunlink ok\\n\");\n}\n\n// directory that uses indirect blocks\nvoid\nbigdir(void)\n{\n  int i, fd;\n  char name[10];\n\n  printf(1, \"bigdir test\\n\");\n  unlink(\"bd\");\n\n  fd = open(\"bd\", O_CREATE);\n  if(fd < 0){\n    printf(1, \"bigdir create failed\\n\");\n    exit();\n  }\n  close(fd);\n\n  for(i = 0; i < 500; i++){\n    name[0] = 'x';\n    name[1] = '0' + (i / 64);\n    name[2] = '0' + (i % 64);\n    name[3] = '\\0';\n    if(link(\"bd\", name) != 0){\n      printf(1, \"bigdir link failed\\n\");\n      exit();\n    }\n  }\n\n  unlink(\"bd\");\n  for(i = 0; i < 500; i++){\n    name[0] = 'x';\n    name[1] = '0' + (i / 64);\n    name[2] = '0' + (i % 64);\n    name[3] = '\\0';\n    if(unlink(name) != 0){\n      printf(1, \"bigdir unlink failed\");\n      exit();\n    }\n  }\n\n  printf(1, \"bigdir ok\\n\");\n}\n\nvoid\nsubdir(void)\n{\n  int fd, cc;\n\n  printf(1, \"subdir test\\n\");\n\n  unlink(\"ff\");\n  if(mkdir(\"dd\") != 0){\n    printf(1, \"subdir mkdir dd failed\\n\");\n    exit();\n  }\n\n  fd = open(\"dd/ff\", O_CREATE | O_RDWR);\n  if(fd < 0){\n    printf(1, \"create dd/ff failed\\n\");\n    exit();\n  }\n  write(fd, \"ff\", 2);\n  close(fd);\n\n  if(unlink(\"dd\") >= 0){\n    printf(1, \"unlink dd (non-empty dir) succeeded!\\n\");\n    exit();\n  }\n\n  if(mkdir(\"/dd/dd\") != 0){\n    printf(1, \"subdir mkdir dd/dd failed\\n\");\n    exit();\n  }\n\n  fd = open(\"dd/dd/ff\", O_CREATE | O_RDWR);\n  if(fd < 0){\n    printf(1, \"create dd/dd/ff failed\\n\");\n    exit();\n  }\n  write(fd, \"FF\", 2);\n  close(fd);\n\n  fd = open(\"dd/dd/../ff\", 0);\n  if(fd < 0){\n    printf(1, \"open dd/dd/../ff failed\\n\");\n    exit();\n  }\n  cc = read(fd, buf, sizeof(buf));\n  if(cc != 2 || buf[0] != 'f'){\n    printf(1, \"dd/dd/../ff wrong content\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(link(\"dd/dd/ff\", \"dd/dd/ffff\") != 0){\n    printf(1, \"link dd/dd/ff dd/dd/ffff failed\\n\");\n    exit();\n  }\n\n  if(unlink(\"dd/dd/ff\") != 0){\n    printf(1, \"unlink dd/dd/ff failed\\n\");\n    exit();\n  }\n  if(open(\"dd/dd/ff\", O_RDONLY) >= 0){\n    printf(1, \"open (unlinked) dd/dd/ff succeeded\\n\");\n    exit();\n  }\n\n  if(chdir(\"dd\") != 0){\n    printf(1, \"chdir dd failed\\n\");\n    exit();\n  }\n  if(chdir(\"dd/../../dd\") != 0){\n    printf(1, \"chdir dd/../../dd failed\\n\");\n    exit();\n  }\n  if(chdir(\"dd/../../../dd\") != 0){\n    printf(1, \"chdir dd/../../dd failed\\n\");\n    exit();\n  }\n  if(chdir(\"./..\") != 0){\n    printf(1, \"chdir ./.. failed\\n\");\n    exit();\n  }\n\n  fd = open(\"dd/dd/ffff\", 0);\n  if(fd < 0){\n    printf(1, \"open dd/dd/ffff failed\\n\");\n    exit();\n  }\n  if(read(fd, buf, sizeof(buf)) != 2){\n    printf(1, \"read dd/dd/ffff wrong len\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(open(\"dd/dd/ff\", O_RDONLY) >= 0){\n    printf(1, \"open (unlinked) dd/dd/ff succeeded!\\n\");\n    exit();\n  }\n\n  if(open(\"dd/ff/ff\", O_CREATE|O_RDWR) >= 0){\n    printf(1, \"create dd/ff/ff succeeded!\\n\");\n    exit();\n  }\n  if(open(\"dd/xx/ff\", O_CREATE|O_RDWR) >= 0){\n    printf(1, \"create dd/xx/ff succeeded!\\n\");\n    exit();\n  }\n  if(open(\"dd\", O_CREATE) >= 0){\n    printf(1, \"create dd succeeded!\\n\");\n    exit();\n  }\n  if(open(\"dd\", O_RDWR) >= 0){\n    printf(1, \"open dd rdwr succeeded!\\n\");\n    exit();\n  }\n  if(open(\"dd\", O_WRONLY) >= 0){\n    printf(1, \"open dd wronly succeeded!\\n\");\n    exit();\n  }\n  if(link(\"dd/ff/ff\", \"dd/dd/xx\") == 0){\n    printf(1, \"link dd/ff/ff dd/dd/xx succeeded!\\n\");\n    exit();\n  }\n  if(link(\"dd/xx/ff\", \"dd/dd/xx\") == 0){\n    printf(1, \"link dd/xx/ff dd/dd/xx succeeded!\\n\");\n    exit();\n  }\n  if(link(\"dd/ff\", \"dd/dd/ffff\") == 0){\n    printf(1, \"link dd/ff dd/dd/ffff succeeded!\\n\");\n    exit();\n  }\n  if(mkdir(\"dd/ff/ff\") == 0){\n    printf(1, \"mkdir dd/ff/ff succeeded!\\n\");\n    exit();\n  }\n  if(mkdir(\"dd/xx/ff\") == 0){\n    printf(1, \"mkdir dd/xx/ff succeeded!\\n\");\n    exit();\n  }\n  if(mkdir(\"dd/dd/ffff\") == 0){\n    printf(1, \"mkdir dd/dd/ffff succeeded!\\n\");\n    exit();\n  }\n  if(unlink(\"dd/xx/ff\") == 0){\n    printf(1, \"unlink dd/xx/ff succeeded!\\n\");\n    exit();\n  }\n  if(unlink(\"dd/ff/ff\") == 0){\n    printf(1, \"unlink dd/ff/ff succeeded!\\n\");\n    exit();\n  }\n  if(chdir(\"dd/ff\") == 0){\n    printf(1, \"chdir dd/ff succeeded!\\n\");\n    exit();\n  }\n  if(chdir(\"dd/xx\") == 0){\n    printf(1, \"chdir dd/xx succeeded!\\n\");\n    exit();\n  }\n\n  if(unlink(\"dd/dd/ffff\") != 0){\n    printf(1, \"unlink dd/dd/ff failed\\n\");\n    exit();\n  }\n  if(unlink(\"dd/ff\") != 0){\n    printf(1, \"unlink dd/ff failed\\n\");\n    exit();\n  }\n  if(unlink(\"dd\") == 0){\n    printf(1, \"unlink non-empty dd succeeded!\\n\");\n    exit();\n  }\n  if(unlink(\"dd/dd\") < 0){\n    printf(1, \"unlink dd/dd failed\\n\");\n    exit();\n  }\n  if(unlink(\"dd\") < 0){\n    printf(1, \"unlink dd failed\\n\");\n    exit();\n  }\n\n  printf(1, \"subdir ok\\n\");\n}\n\n// test writes that are larger than the log.\nvoid\nbigwrite(void)\n{\n  int fd, sz;\n\n  printf(1, \"bigwrite test\\n\");\n\n  unlink(\"bigwrite\");\n  for(sz = 499; sz < 12*512; sz += 471){\n    fd = open(\"bigwrite\", O_CREATE | O_RDWR);\n    if(fd < 0){\n      printf(1, \"cannot create bigwrite\\n\");\n      exit();\n    }\n    int i;\n    for(i = 0; i < 2; i++){\n      int cc = write(fd, buf, sz);\n      if(cc != sz){\n        printf(1, \"write(%d) ret %d\\n\", sz, cc);\n        exit();\n      }\n    }\n    close(fd);\n    unlink(\"bigwrite\");\n  }\n\n  printf(1, \"bigwrite ok\\n\");\n}\n\nvoid\nbigfile(void)\n{\n  int fd, i, total, cc;\n\n  printf(1, \"bigfile test\\n\");\n\n  unlink(\"bigfile\");\n  fd = open(\"bigfile\", O_CREATE | O_RDWR);\n  if(fd < 0){\n    printf(1, \"cannot create bigfile\");\n    exit();\n  }\n  for(i = 0; i < 20; i++){\n    memset(buf, i, 600);\n    if(write(fd, buf, 600) != 600){\n      printf(1, \"write bigfile failed\\n\");\n      exit();\n    }\n  }\n  close(fd);\n\n  fd = open(\"bigfile\", 0);\n  if(fd < 0){\n    printf(1, \"cannot open bigfile\\n\");\n    exit();\n  }\n  total = 0;\n  for(i = 0; ; i++){\n    cc = read(fd, buf, 300);\n    if(cc < 0){\n      printf(1, \"read bigfile failed\\n\");\n      exit();\n    }\n    if(cc == 0)\n      break;\n    if(cc != 300){\n      printf(1, \"short read bigfile\\n\");\n      exit();\n    }\n    if(buf[0] != i/2 || buf[299] != i/2){\n      printf(1, \"read bigfile wrong data\\n\");\n      exit();\n    }\n    total += cc;\n  }\n  close(fd);\n  if(total != 20*600){\n    printf(1, \"read bigfile wrong total\\n\");\n    exit();\n  }\n  unlink(\"bigfile\");\n\n  printf(1, \"bigfile test ok\\n\");\n}\n\nvoid\nfourteen(void)\n{\n  int fd;\n\n  // DIRSIZ is 14.\n  printf(1, \"fourteen test\\n\");\n\n  if(mkdir(\"12345678901234\") != 0){\n    printf(1, \"mkdir 12345678901234 failed\\n\");\n    exit();\n  }\n  if(mkdir(\"12345678901234/123456789012345\") != 0){\n    printf(1, \"mkdir 12345678901234/123456789012345 failed\\n\");\n    exit();\n  }\n  fd = open(\"123456789012345/123456789012345/123456789012345\", O_CREATE);\n  if(fd < 0){\n    printf(1, \"create 123456789012345/123456789012345/123456789012345 failed\\n\");\n    exit();\n  }\n  close(fd);\n  fd = open(\"12345678901234/12345678901234/12345678901234\", 0);\n  if(fd < 0){\n    printf(1, \"open 12345678901234/12345678901234/12345678901234 failed\\n\");\n    exit();\n  }\n  close(fd);\n\n  if(mkdir(\"12345678901234/12345678901234\") == 0){\n    printf(1, \"mkdir 12345678901234/12345678901234 succeeded!\\n\");\n    exit();\n  }\n  if(mkdir(\"123456789012345/12345678901234\") == 0){\n    printf(1, \"mkdir 12345678901234/123456789012345 succeeded!\\n\");\n    exit();\n  }\n\n  printf(1, \"fourteen ok\\n\");\n}\n\nvoid\nrmdot(void)\n{\n  printf(1, \"rmdot test\\n\");\n  if(mkdir(\"dots\") != 0){\n    printf(1, \"mkdir dots failed\\n\");\n    exit();\n  }\n  if(chdir(\"dots\") != 0){\n    printf(1, \"chdir dots failed\\n\");\n    exit();\n  }\n  if(unlink(\".\") == 0){\n    printf(1, \"rm . worked!\\n\");\n    exit();\n  }\n  if(unlink(\"..\") == 0){\n    printf(1, \"rm .. worked!\\n\");\n    exit();\n  }\n  if(chdir(\"/\") != 0){\n    printf(1, \"chdir / failed\\n\");\n    exit();\n  }\n  if(unlink(\"dots/.\") == 0){\n    printf(1, \"unlink dots/. worked!\\n\");\n    exit();\n  }\n  if(unlink(\"dots/..\") == 0){\n    printf(1, \"unlink dots/.. worked!\\n\");\n    exit();\n  }\n  if(unlink(\"dots\") != 0){\n    printf(1, \"unlink dots failed!\\n\");\n    exit();\n  }\n  printf(1, \"rmdot ok\\n\");\n}\n\nvoid\ndirfile(void)\n{\n  int fd;\n\n  printf(1, \"dir vs file\\n\");\n\n  fd = open(\"dirfile\", O_CREATE);\n  if(fd < 0){\n    printf(1, \"create dirfile failed\\n\");\n    exit();\n  }\n  close(fd);\n  if(chdir(\"dirfile\") == 0){\n    printf(1, \"chdir dirfile succeeded!\\n\");\n    exit();\n  }\n  fd = open(\"dirfile/xx\", 0);\n  if(fd >= 0){\n    printf(1, \"create dirfile/xx succeeded!\\n\");\n    exit();\n  }\n  fd = open(\"dirfile/xx\", O_CREATE);\n  if(fd >= 0){\n    printf(1, \"create dirfile/xx succeeded!\\n\");\n    exit();\n  }\n  if(mkdir(\"dirfile/xx\") == 0){\n    printf(1, \"mkdir dirfile/xx succeeded!\\n\");\n    exit();\n  }\n  if(unlink(\"dirfile/xx\") == 0){\n    printf(1, \"unlink dirfile/xx succeeded!\\n\");\n    exit();\n  }\n  if(link(\"README\", \"dirfile/xx\") == 0){\n    printf(1, \"link to dirfile/xx succeeded!\\n\");\n    exit();\n  }\n  if(unlink(\"dirfile\") != 0){\n    printf(1, \"unlink dirfile failed!\\n\");\n    exit();\n  }\n\n  fd = open(\".\", O_RDWR);\n  if(fd >= 0){\n    printf(1, \"open . for writing succeeded!\\n\");\n    exit();\n  }\n  fd = open(\".\", 0);\n  if(write(fd, \"x\", 1) > 0){\n    printf(1, \"write . succeeded!\\n\");\n    exit();\n  }\n  close(fd);\n\n  printf(1, \"dir vs file OK\\n\");\n}\n\n// test that iput() is called at the end of _namei()\nvoid\niref(void)\n{\n  int i, fd;\n\n  printf(1, \"empty file name\\n\");\n\n  // the 50 is NINODE\n  for(i = 0; i < 50 + 1; i++){\n    if(mkdir(\"irefd\") != 0){\n      printf(1, \"mkdir irefd failed\\n\");\n      exit();\n    }\n    if(chdir(\"irefd\") != 0){\n      printf(1, \"chdir irefd failed\\n\");\n      exit();\n    }\n\n    mkdir(\"\");\n    link(\"README\", \"\");\n    fd = open(\"\", O_CREATE);\n    if(fd >= 0)\n      close(fd);\n    fd = open(\"xx\", O_CREATE);\n    if(fd >= 0)\n      close(fd);\n    unlink(\"xx\");\n  }\n\n  chdir(\"/\");\n  printf(1, \"empty file name OK\\n\");\n}\n\n// test that fork fails gracefully\n// the forktest binary also does this, but it runs out of proc entries first.\n// inside the bigger usertests binary, we run out of memory first.\nvoid\nforktest(void)\n{\n  int n, pid;\n\n  printf(1, \"fork test\\n\");\n\n  for(n=0; n<1000; n++){\n    pid = fork();\n    if(pid < 0)\n      break;\n    if(pid == 0)\n      exit();\n  }\n\n  if(n == 1000){\n    printf(1, \"fork claimed to work 1000 times!\\n\");\n    exit();\n  }\n\n  for(; n > 0; n--){\n    if(wait() < 0){\n      printf(1, \"wait stopped early\\n\");\n      exit();\n    }\n  }\n\n  if(wait() != -1){\n    printf(1, \"wait got too many\\n\");\n    exit();\n  }\n\n  printf(1, \"fork test OK\\n\");\n}\n\nvoid\nsbrktest(void)\n{\n  int fds[2], pid, pids[10], ppid;\n  char *a, *b, *c, *lastaddr, *oldbrk, *p, scratch;\n  uint amt;\n\n  printf(stdout, \"sbrk test\\n\");\n  oldbrk = sbrk(0);\n\n  // can one sbrk() less than a page?\n  a = sbrk(0);\n  int i;\n  for(i = 0; i < 5000; i++){\n    b = sbrk(1);\n    if(b != a){\n      printf(stdout, \"sbrk test failed %d %x %x\\n\", i, a, b);\n      exit();\n    }\n    *b = 1;\n    a = b + 1;\n  }\n  pid = fork();\n  if(pid < 0){\n    printf(stdout, \"sbrk test fork failed\\n\");\n    exit();\n  }\n  c = sbrk(1);\n  c = sbrk(1);\n  if(c != a + 1){\n    printf(stdout, \"sbrk test failed post-fork\\n\");\n    exit();\n  }\n  if(pid == 0)\n    exit();\n  wait();\n\n  // can one grow address space to something big?\n#define BIG (100*1024*1024)\n  a = sbrk(0);\n  amt = (BIG) - (uint)a;\n  p = sbrk(amt);\n  if (p != a) {\n    printf(stdout, \"sbrk test failed to grow big address space; enough phys mem?\\n\");\n    exit();\n  }\n  lastaddr = (char*) (BIG-1);\n  *lastaddr = 99;\n\n  // can one de-allocate?\n  a = sbrk(0);\n  c = sbrk(-4096);\n  if(c == (char*)0xffffffff){\n    printf(stdout, \"sbrk could not deallocate\\n\");\n    exit();\n  }\n  c = sbrk(0);\n  if(c != a - 4096){\n    printf(stdout, \"sbrk deallocation produced wrong address, a %x c %x\\n\", a, c);\n    exit();\n  }\n\n  // can one re-allocate that page?\n  a = sbrk(0);\n  c = sbrk(4096);\n  if(c != a || sbrk(0) != a + 4096){\n    printf(stdout, \"sbrk re-allocation failed, a %x c %x\\n\", a, c);\n    exit();\n  }\n  if(*lastaddr == 99){\n    // should be zero\n    printf(stdout, \"sbrk de-allocation didn't really deallocate\\n\");\n    exit();\n  }\n\n  a = sbrk(0);\n  c = sbrk(-(sbrk(0) - oldbrk));\n  if(c != a){\n    printf(stdout, \"sbrk downsize failed, a %x c %x\\n\", a, c);\n    exit();\n  }\n\n  // can we read the kernel's memory?\n  for(a = (char*)(KERNBASE); a < (char*) (KERNBASE+2000000); a += 50000){\n    ppid = getpid();\n    pid = fork();\n    if(pid < 0){\n      printf(stdout, \"fork failed\\n\");\n      exit();\n    }\n    if(pid == 0){\n      printf(stdout, \"oops could read %x = %x\\n\", a, *a);\n      kill(ppid);\n      exit();\n    }\n    wait();\n  }\n\n  // if we run the system out of memory, does it clean up the last\n  // failed allocation?\n  if(pipe(fds) != 0){\n    printf(1, \"pipe() failed\\n\");\n    exit();\n  }\n  for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){\n    if((pids[i] = fork()) == 0){\n      // allocate a lot of memory\n      sbrk(BIG - (uint)sbrk(0));\n      write(fds[1], \"x\", 1);\n      // sit around until killed\n      for(;;) sleep(1000);\n    }\n    if(pids[i] != -1)\n      read(fds[0], &scratch, 1);\n  }\n  // if those failed allocations freed up the pages they did allocate,\n  // we'll be able to allocate here\n  c = sbrk(4096);\n  for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){\n    if(pids[i] == -1)\n      continue;\n    kill(pids[i]);\n    wait();\n  }\n  if(c == (char*)0xffffffff){\n    printf(stdout, \"failed sbrk leaked memory\\n\");\n    exit();\n  }\n\n  if(sbrk(0) > oldbrk)\n    sbrk(-(sbrk(0) - oldbrk));\n\n  printf(stdout, \"sbrk test OK\\n\");\n}\n\nvoid\nvalidateint(int *p)\n{\n  int res;\n  asm(\"mov %%esp, %%ebx\\n\\t\"\n      \"mov %3, %%esp\\n\\t\"\n      \"int %2\\n\\t\"\n      \"mov %%ebx, %%esp\" :\n      \"=a\" (res) :\n      \"a\" (SYS_sleep), \"n\" (T_SYSCALL), \"c\" (p) :\n      \"ebx\");\n}\n\nvoid\nvalidatetest(void)\n{\n  int hi, pid;\n  uint p;\n\n  printf(stdout, \"validate test\\n\");\n  hi = 1100*1024;\n\n  for(p = 0; p <= (uint)hi; p += 4096){\n    if((pid = fork()) == 0){\n      // try to crash the kernel by passing in a badly placed integer\n      validateint((int*)p);\n      exit();\n    }\n    sleep(0);\n    sleep(0);\n    kill(pid);\n    wait();\n\n    // try to crash the kernel by passing in a bad string pointer\n    if(link(\"nosuchfile\", (char*)p) != -1){\n      printf(stdout, \"link should not succeed\\n\");\n      exit();\n    }\n  }\n\n  printf(stdout, \"validate ok\\n\");\n}\n\n// does unintialized data start out zero?\nchar uninit[10000];\nvoid\nbsstest(void)\n{\n  int i;\n\n  printf(stdout, \"bss test\\n\");\n  for(i = 0; i < sizeof(uninit); i++){\n    if(uninit[i] != '\\0'){\n      printf(stdout, \"bss test failed\\n\");\n      exit();\n    }\n  }\n  printf(stdout, \"bss test ok\\n\");\n}\n\n// does exec return an error if the arguments\n// are larger than a page? or does it write\n// below the stack and wreck the instructions/data?\nvoid\nbigargtest(void)\n{\n  int pid, fd;\n\n  unlink(\"bigarg-ok\");\n  pid = fork();\n  if(pid == 0){\n    static char *args[MAXARG];\n    int i;\n    for(i = 0; i < MAXARG-1; i++)\n      args[i] = \"bigargs test: failed\\n                                                                                                                                                                                                       \";\n    args[MAXARG-1] = 0;\n    printf(stdout, \"bigarg test\\n\");\n    exec(\"echo\", args);\n    printf(stdout, \"bigarg test ok\\n\");\n    fd = open(\"bigarg-ok\", O_CREATE);\n    close(fd);\n    exit();\n  } else if(pid < 0){\n    printf(stdout, \"bigargtest: fork failed\\n\");\n    exit();\n  }\n  wait();\n  fd = open(\"bigarg-ok\", 0);\n  if(fd < 0){\n    printf(stdout, \"bigarg test failed!\\n\");\n    exit();\n  }\n  close(fd);\n  unlink(\"bigarg-ok\");\n}\n\n// what happens when the file system runs out of blocks?\n// answer: balloc panics, so this test is not useful.\nvoid\nfsfull()\n{\n  int nfiles;\n  int fsblocks = 0;\n\n  printf(1, \"fsfull test\\n\");\n\n  for(nfiles = 0; ; nfiles++){\n    char name[64];\n    name[0] = 'f';\n    name[1] = '0' + nfiles / 1000;\n    name[2] = '0' + (nfiles % 1000) / 100;\n    name[3] = '0' + (nfiles % 100) / 10;\n    name[4] = '0' + (nfiles % 10);\n    name[5] = '\\0';\n    printf(1, \"writing %s\\n\", name);\n    int fd = open(name, O_CREATE|O_RDWR);\n    if(fd < 0){\n      printf(1, \"open %s failed\\n\", name);\n      break;\n    }\n    int total = 0;\n    while(1){\n      int cc = write(fd, buf, 512);\n      if(cc < 512)\n        break;\n      total += cc;\n      fsblocks++;\n    }\n    printf(1, \"wrote %d bytes\\n\", total);\n    close(fd);\n    if(total == 0)\n      break;\n  }\n\n  while(nfiles >= 0){\n    char name[64];\n    name[0] = 'f';\n    name[1] = '0' + nfiles / 1000;\n    name[2] = '0' + (nfiles % 1000) / 100;\n    name[3] = '0' + (nfiles % 100) / 10;\n    name[4] = '0' + (nfiles % 10);\n    name[5] = '\\0';\n    unlink(name);\n    nfiles--;\n  }\n\n  printf(1, \"fsfull test finished\\n\");\n}\n\nvoid\nuio()\n{\n  #define RTC_ADDR 0x70\n  #define RTC_DATA 0x71\n\n  ushort port = 0;\n  uchar val = 0;\n  int pid;\n\n  printf(1, \"uio test\\n\");\n  pid = fork();\n  if(pid == 0){\n    port = RTC_ADDR;\n    val = 0x09;  /* year */\n    /* http://wiki.osdev.org/Inline_Assembly/Examples */\n    asm volatile(\"outb %0,%1\"::\"a\"(val), \"d\" (port));\n    port = RTC_DATA;\n    asm volatile(\"inb %1,%0\" : \"=a\" (val) : \"d\" (port));\n    printf(1, \"uio: uio succeeded; test FAILED\\n\");\n    exit();\n  } else if(pid < 0){\n    printf (1, \"fork failed\\n\");\n    exit();\n  }\n  wait();\n  printf(1, \"uio test done\\n\");\n}\n\nvoid argptest()\n{\n  int fd;\n  fd = open(\"init\", O_RDONLY);\n  if (fd < 0) {\n    printf(2, \"open failed\\n\");\n    exit();\n  }\n  read(fd, sbrk(0) - 1, -1);\n  close(fd);\n  printf(1, \"arg test passed\\n\");\n}\n\nunsigned long randstate = 1;\nunsigned int\nrand()\n{\n  randstate = randstate * 1664525 + 1013904223;\n  return randstate;\n}\n\nint\nmain(int argc, char *argv[])\n{\n  printf(1, \"usertests starting\\n\");\n\n  if(open(\"usertests.ran\", 0) >= 0){\n    printf(1, \"already ran user tests -- rebuild fs.img\\n\");\n    exit();\n  }\n  close(open(\"usertests.ran\", O_CREATE));\n\n  argptest();\n  createdelete();\n  linkunlink();\n  concreate();\n  fourfiles();\n  sharedfd();\n\n  bigargtest();\n  bigwrite();\n  bigargtest();\n  bsstest();\n  sbrktest();\n  validatetest();\n\n  opentest();\n  writetest();\n  writetest1();\n  createtest();\n\n  openiputtest();\n  exitiputtest();\n  iputtest();\n\n  mem();\n  pipe1();\n  preempt();\n  exitwait();\n\n  rmdot();\n  fourteen();\n  bigfile();\n  subdir();\n  linktest();\n  unlinkread();\n  dirfile();\n  iref();\n  forktest();\n  bigdir(); // slow\n\n  uio();\n\n  exectest();\n\n  exit();\n}\n"
  },
  {
    "path": "usys.S",
    "content": "#include \"syscall.h\"\n#include \"traps.h\"\n\n#define SYSCALL(name) \\\n  .globl name; \\\n  name: \\\n    movl $SYS_ ## name, %eax; \\\n    int $T_SYSCALL; \\\n    ret\n\nSYSCALL(fork)\nSYSCALL(exit)\nSYSCALL(wait)\nSYSCALL(pipe)\nSYSCALL(read)\nSYSCALL(write)\nSYSCALL(close)\nSYSCALL(kill)\nSYSCALL(exec)\nSYSCALL(open)\nSYSCALL(mknod)\nSYSCALL(unlink)\nSYSCALL(fstat)\nSYSCALL(link)\nSYSCALL(mkdir)\nSYSCALL(chdir)\nSYSCALL(dup)\nSYSCALL(getpid)\nSYSCALL(sbrk)\nSYSCALL(sleep)\nSYSCALL(uptime)\n"
  },
  {
    "path": "vectors.pl",
    "content": "#!/usr/bin/perl -w\n\n# Generate vectors.S, the trap/interrupt entry points.\n# There has to be one entry point per interrupt number\n# since otherwise there's no way for trap() to discover\n# the interrupt number.\n\nprint \"# generated by vectors.pl - do not edit\\n\";\nprint \"# handlers\\n\";\nprint \".globl alltraps\\n\";\nfor(my $i = 0; $i < 256; $i++){\n    print \".globl vector$i\\n\";\n    print \"vector$i:\\n\";\n    if(!($i == 8 || ($i >= 10 && $i <= 14) || $i == 17)){\n        print \"  pushl \\$0\\n\";\n    }\n    print \"  pushl \\$$i\\n\";\n    print \"  jmp alltraps\\n\";\n}\n\nprint \"\\n# vector table\\n\";\nprint \".data\\n\";\nprint \".globl vectors\\n\";\nprint \"vectors:\\n\";\nfor(my $i = 0; $i < 256; $i++){\n    print \"  .long vector$i\\n\";\n}\n\n# sample output:\n#   # handlers\n#   .globl alltraps\n#   .globl vector0\n#   vector0:\n#     pushl $0\n#     pushl $0\n#     jmp alltraps\n#   ...\n#   \n#   # vector table\n#   .data\n#   .globl vectors\n#   vectors:\n#     .long vector0\n#     .long vector1\n#     .long vector2\n#   ...\n\n"
  },
  {
    "path": "vm.c",
    "content": "#include \"param.h\"\n#include \"types.h\"\n#include \"defs.h\"\n#include \"x86.h\"\n#include \"memlayout.h\"\n#include \"mmu.h\"\n#include \"proc.h\"\n#include \"elf.h\"\n\nextern char data[];  // defined by kernel.ld\npde_t *kpgdir;  // for use in scheduler()\n\n// Set up CPU's kernel segment descriptors.\n// Run once on entry on each CPU.\nvoid\nseginit(void)\n{\n  struct cpu *c;\n\n  // Map \"logical\" addresses to virtual addresses using identity map.\n  // Cannot share a CODE descriptor for both kernel and user\n  // because it would have to have DPL_USR, but the CPU forbids\n  // an interrupt from CPL=0 to DPL=3.\n  c = &cpus[cpuid()];\n  c->gdt[SEG_KCODE] = SEG(STA_X|STA_R, 0, 0xffffffff, 0);\n  c->gdt[SEG_KDATA] = SEG(STA_W, 0, 0xffffffff, 0);\n  c->gdt[SEG_UCODE] = SEG(STA_X|STA_R, 0, 0xffffffff, DPL_USER);\n  c->gdt[SEG_UDATA] = SEG(STA_W, 0, 0xffffffff, DPL_USER);\n  lgdt(c->gdt, sizeof(c->gdt));\n}\n\n// Return the address of the PTE in page table pgdir\n// that corresponds to virtual address va.  If alloc!=0,\n// create any required page table pages.\nstatic pte_t *\nwalkpgdir(pde_t *pgdir, const void *va, int alloc)\n{\n  pde_t *pde;\n  pte_t *pgtab;\n\n  pde = &pgdir[PDX(va)];\n  if(*pde & PTE_P){\n    pgtab = (pte_t*)P2V(PTE_ADDR(*pde));\n  } else {\n    if(!alloc || (pgtab = (pte_t*)kalloc()) == 0)\n      return 0;\n    // Make sure all those PTE_P bits are zero.\n    memset(pgtab, 0, PGSIZE);\n    // The permissions here are overly generous, but they can\n    // be further restricted by the permissions in the page table\n    // entries, if necessary.\n    *pde = V2P(pgtab) | PTE_P | PTE_W | PTE_U;\n  }\n  return &pgtab[PTX(va)];\n}\n\n// Create PTEs for virtual addresses starting at va that refer to\n// physical addresses starting at pa. va and size might not\n// be page-aligned.\nstatic int\nmappages(pde_t *pgdir, void *va, uint size, uint pa, int perm)\n{\n  char *a, *last;\n  pte_t *pte;\n\n  a = (char*)PGROUNDDOWN((uint)va);\n  last = (char*)PGROUNDDOWN(((uint)va) + size - 1);\n  for(;;){\n    if((pte = walkpgdir(pgdir, a, 1)) == 0)\n      return -1;\n    if(*pte & PTE_P)\n      panic(\"remap\");\n    *pte = pa | perm | PTE_P;\n    if(a == last)\n      break;\n    a += PGSIZE;\n    pa += PGSIZE;\n  }\n  return 0;\n}\n\n// There is one page table per process, plus one that's used when\n// a CPU is not running any process (kpgdir). The kernel uses the\n// current process's page table during system calls and interrupts;\n// page protection bits prevent user code from using the kernel's\n// mappings.\n//\n// setupkvm() and exec() set up every page table like this:\n//\n//   0..KERNBASE: user memory (text+data+stack+heap), mapped to\n//                phys memory allocated by the kernel\n//   KERNBASE..KERNBASE+EXTMEM: mapped to 0..EXTMEM (for I/O space)\n//   KERNBASE+EXTMEM..data: mapped to EXTMEM..V2P(data)\n//                for the kernel's instructions and r/o data\n//   data..KERNBASE+PHYSTOP: mapped to V2P(data)..PHYSTOP,\n//                                  rw data + free physical memory\n//   0xfe000000..0: mapped direct (devices such as ioapic)\n//\n// The kernel allocates physical memory for its heap and for user memory\n// between V2P(end) and the end of physical memory (PHYSTOP)\n// (directly addressable from end..P2V(PHYSTOP)).\n\n// This table defines the kernel's mappings, which are present in\n// every process's page table.\nstatic struct kmap {\n  void *virt;\n  uint phys_start;\n  uint phys_end;\n  int perm;\n} kmap[] = {\n { (void*)KERNBASE, 0,             EXTMEM,    PTE_W}, // I/O space\n { (void*)KERNLINK, V2P(KERNLINK), V2P(data), 0},     // kern text+rodata\n { (void*)data,     V2P(data),     PHYSTOP,   PTE_W}, // kern data+memory\n { (void*)DEVSPACE, DEVSPACE,      0,         PTE_W}, // more devices\n};\n\n// Set up kernel part of a page table.\npde_t*\nsetupkvm(void)\n{\n  pde_t *pgdir;\n  struct kmap *k;\n\n  if((pgdir = (pde_t*)kalloc()) == 0)\n    return 0;\n  memset(pgdir, 0, PGSIZE);\n  if (P2V(PHYSTOP) > (void*)DEVSPACE)\n    panic(\"PHYSTOP too high\");\n  for(k = kmap; k < &kmap[NELEM(kmap)]; k++)\n    if(mappages(pgdir, k->virt, k->phys_end - k->phys_start,\n                (uint)k->phys_start, k->perm) < 0) {\n      freevm(pgdir);\n      return 0;\n    }\n  return pgdir;\n}\n\n// Allocate one page table for the machine for the kernel address\n// space for scheduler processes.\nvoid\nkvmalloc(void)\n{\n  kpgdir = setupkvm();\n  switchkvm();\n}\n\n// Switch h/w page table register to the kernel-only page table,\n// for when no process is running.\nvoid\nswitchkvm(void)\n{\n  lcr3(V2P(kpgdir));   // switch to the kernel page table\n}\n\n// Switch TSS and h/w page table to correspond to process p.\nvoid\nswitchuvm(struct proc *p)\n{\n  if(p == 0)\n    panic(\"switchuvm: no process\");\n  if(p->kstack == 0)\n    panic(\"switchuvm: no kstack\");\n  if(p->pgdir == 0)\n    panic(\"switchuvm: no pgdir\");\n\n  pushcli();\n  mycpu()->gdt[SEG_TSS] = SEG16(STS_T32A, &mycpu()->ts,\n                                sizeof(mycpu()->ts)-1, 0);\n  mycpu()->gdt[SEG_TSS].s = 0;\n  mycpu()->ts.ss0 = SEG_KDATA << 3;\n  mycpu()->ts.esp0 = (uint)p->kstack + KSTACKSIZE;\n  // setting IOPL=0 in eflags *and* iomb beyond the tss segment limit\n  // forbids I/O instructions (e.g., inb and outb) from user space\n  mycpu()->ts.iomb = (ushort) 0xFFFF;\n  ltr(SEG_TSS << 3);\n  lcr3(V2P(p->pgdir));  // switch to process's address space\n  popcli();\n}\n\n// Load the initcode into address 0 of pgdir.\n// sz must be less than a page.\nvoid\ninituvm(pde_t *pgdir, char *init, uint sz)\n{\n  char *mem;\n\n  if(sz >= PGSIZE)\n    panic(\"inituvm: more than a page\");\n  mem = kalloc();\n  memset(mem, 0, PGSIZE);\n  mappages(pgdir, 0, PGSIZE, V2P(mem), PTE_W|PTE_U);\n  memmove(mem, init, sz);\n}\n\n// Load a program segment into pgdir.  addr must be page-aligned\n// and the pages from addr to addr+sz must already be mapped.\nint\nloaduvm(pde_t *pgdir, char *addr, struct inode *ip, uint offset, uint sz)\n{\n  uint i, pa, n;\n  pte_t *pte;\n\n  if((uint) addr % PGSIZE != 0)\n    panic(\"loaduvm: addr must be page aligned\");\n  for(i = 0; i < sz; i += PGSIZE){\n    if((pte = walkpgdir(pgdir, addr+i, 0)) == 0)\n      panic(\"loaduvm: address should exist\");\n    pa = PTE_ADDR(*pte);\n    if(sz - i < PGSIZE)\n      n = sz - i;\n    else\n      n = PGSIZE;\n    if(readi(ip, P2V(pa), offset+i, n) != n)\n      return -1;\n  }\n  return 0;\n}\n\n// Allocate page tables and physical memory to grow process from oldsz to\n// newsz, which need not be page aligned.  Returns new size or 0 on error.\nint\nallocuvm(pde_t *pgdir, uint oldsz, uint newsz)\n{\n  char *mem;\n  uint a;\n\n  if(newsz >= KERNBASE)\n    return 0;\n  if(newsz < oldsz)\n    return oldsz;\n\n  a = PGROUNDUP(oldsz);\n  for(; a < newsz; a += PGSIZE){\n    mem = kalloc();\n    if(mem == 0){\n      cprintf(\"allocuvm out of memory\\n\");\n      deallocuvm(pgdir, newsz, oldsz);\n      return 0;\n    }\n    memset(mem, 0, PGSIZE);\n    if(mappages(pgdir, (char*)a, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0){\n      cprintf(\"allocuvm out of memory (2)\\n\");\n      deallocuvm(pgdir, newsz, oldsz);\n      kfree(mem);\n      return 0;\n    }\n  }\n  return newsz;\n}\n\n// Deallocate user pages to bring the process size from oldsz to\n// newsz.  oldsz and newsz need not be page-aligned, nor does newsz\n// need to be less than oldsz.  oldsz can be larger than the actual\n// process size.  Returns the new process size.\nint\ndeallocuvm(pde_t *pgdir, uint oldsz, uint newsz)\n{\n  pte_t *pte;\n  uint a, pa;\n\n  if(newsz >= oldsz)\n    return oldsz;\n\n  a = PGROUNDUP(newsz);\n  for(; a  < oldsz; a += PGSIZE){\n    pte = walkpgdir(pgdir, (char*)a, 0);\n    if(!pte)\n      a = PGADDR(PDX(a) + 1, 0, 0) - PGSIZE;\n    else if((*pte & PTE_P) != 0){\n      pa = PTE_ADDR(*pte);\n      if(pa == 0)\n        panic(\"kfree\");\n      char *v = P2V(pa);\n      kfree(v);\n      *pte = 0;\n    }\n  }\n  return newsz;\n}\n\n// Free a page table and all the physical memory pages\n// in the user part.\nvoid\nfreevm(pde_t *pgdir)\n{\n  uint i;\n\n  if(pgdir == 0)\n    panic(\"freevm: no pgdir\");\n  deallocuvm(pgdir, KERNBASE, 0);\n  for(i = 0; i < NPDENTRIES; i++){\n    if(pgdir[i] & PTE_P){\n      char * v = P2V(PTE_ADDR(pgdir[i]));\n      kfree(v);\n    }\n  }\n  kfree((char*)pgdir);\n}\n\n// Clear PTE_U on a page. Used to create an inaccessible\n// page beneath the user stack.\nvoid\nclearpteu(pde_t *pgdir, char *uva)\n{\n  pte_t *pte;\n\n  pte = walkpgdir(pgdir, uva, 0);\n  if(pte == 0)\n    panic(\"clearpteu\");\n  *pte &= ~PTE_U;\n}\n\n// Given a parent process's page table, create a copy\n// of it for a child.\npde_t*\ncopyuvm(pde_t *pgdir, uint sz)\n{\n  pde_t *d;\n  pte_t *pte;\n  uint pa, i, flags;\n  char *mem;\n\n  if((d = setupkvm()) == 0)\n    return 0;\n  for(i = 0; i < sz; i += PGSIZE){\n    if((pte = walkpgdir(pgdir, (void *) i, 0)) == 0)\n      panic(\"copyuvm: pte should exist\");\n    if(!(*pte & PTE_P))\n      panic(\"copyuvm: page not present\");\n    pa = PTE_ADDR(*pte);\n    flags = PTE_FLAGS(*pte);\n    if((mem = kalloc()) == 0)\n      goto bad;\n    memmove(mem, (char*)P2V(pa), PGSIZE);\n    if(mappages(d, (void*)i, PGSIZE, V2P(mem), flags) < 0) {\n      kfree(mem);\n      goto bad;\n    }\n  }\n  return d;\n\nbad:\n  freevm(d);\n  return 0;\n}\n\n//PAGEBREAK!\n// Map user virtual address to kernel address.\nchar*\nuva2ka(pde_t *pgdir, char *uva)\n{\n  pte_t *pte;\n\n  pte = walkpgdir(pgdir, uva, 0);\n  if((*pte & PTE_P) == 0)\n    return 0;\n  if((*pte & PTE_U) == 0)\n    return 0;\n  return (char*)P2V(PTE_ADDR(*pte));\n}\n\n// Copy len bytes from p to user address va in page table pgdir.\n// Most useful when pgdir is not the current page table.\n// uva2ka ensures this only works for PTE_U pages.\nint\ncopyout(pde_t *pgdir, uint va, void *p, uint len)\n{\n  char *buf, *pa0;\n  uint n, va0;\n\n  buf = (char*)p;\n  while(len > 0){\n    va0 = (uint)PGROUNDDOWN(va);\n    pa0 = uva2ka(pgdir, (char*)va0);\n    if(pa0 == 0)\n      return -1;\n    n = PGSIZE - (va - va0);\n    if(n > len)\n      n = len;\n    memmove(pa0 + (va - va0), buf, n);\n    len -= n;\n    buf += n;\n    va = va0 + PGSIZE;\n  }\n  return 0;\n}\n\n//PAGEBREAK!\n// Blank page.\n//PAGEBREAK!\n// Blank page.\n//PAGEBREAK!\n// Blank page.\n\n"
  },
  {
    "path": "wc.c",
    "content": "#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nchar buf[512];\n\nvoid\nwc(int fd, char *name)\n{\n  int i, n;\n  int l, w, c, inword;\n\n  l = w = c = 0;\n  inword = 0;\n  while((n = read(fd, buf, sizeof(buf))) > 0){\n    for(i=0; i<n; i++){\n      c++;\n      if(buf[i] == '\\n')\n        l++;\n      if(strchr(\" \\r\\t\\n\\v\", buf[i]))\n        inword = 0;\n      else if(!inword){\n        w++;\n        inword = 1;\n      }\n    }\n  }\n  if(n < 0){\n    printf(1, \"wc: read error\\n\");\n    exit();\n  }\n  printf(1, \"%d %d %d %s\\n\", l, w, c, name);\n}\n\nint\nmain(int argc, char *argv[])\n{\n  int fd, i;\n\n  if(argc <= 1){\n    wc(0, \"\");\n    exit();\n  }\n\n  for(i = 1; i < argc; i++){\n    if((fd = open(argv[i], 0)) < 0){\n      printf(1, \"wc: cannot open %s\\n\", argv[i]);\n      exit();\n    }\n    wc(fd, argv[i]);\n    close(fd);\n  }\n  exit();\n}\n"
  },
  {
    "path": "x86.h",
    "content": "// Routines to let C code use special x86 instructions.\n\nstatic inline uchar\ninb(ushort port)\n{\n  uchar data;\n\n  asm volatile(\"in %1,%0\" : \"=a\" (data) : \"d\" (port));\n  return data;\n}\n\nstatic inline void\ninsl(int port, void *addr, int cnt)\n{\n  asm volatile(\"cld; rep insl\" :\n               \"=D\" (addr), \"=c\" (cnt) :\n               \"d\" (port), \"0\" (addr), \"1\" (cnt) :\n               \"memory\", \"cc\");\n}\n\nstatic inline void\noutb(ushort port, uchar data)\n{\n  asm volatile(\"out %0,%1\" : : \"a\" (data), \"d\" (port));\n}\n\nstatic inline void\noutw(ushort port, ushort data)\n{\n  asm volatile(\"out %0,%1\" : : \"a\" (data), \"d\" (port));\n}\n\nstatic inline void\noutsl(int port, const void *addr, int cnt)\n{\n  asm volatile(\"cld; rep outsl\" :\n               \"=S\" (addr), \"=c\" (cnt) :\n               \"d\" (port), \"0\" (addr), \"1\" (cnt) :\n               \"cc\");\n}\n\nstatic inline void\nstosb(void *addr, int data, int cnt)\n{\n  asm volatile(\"cld; rep stosb\" :\n               \"=D\" (addr), \"=c\" (cnt) :\n               \"0\" (addr), \"1\" (cnt), \"a\" (data) :\n               \"memory\", \"cc\");\n}\n\nstatic inline void\nstosl(void *addr, int data, int cnt)\n{\n  asm volatile(\"cld; rep stosl\" :\n               \"=D\" (addr), \"=c\" (cnt) :\n               \"0\" (addr), \"1\" (cnt), \"a\" (data) :\n               \"memory\", \"cc\");\n}\n\nstruct segdesc;\n\nstatic inline void\nlgdt(struct segdesc *p, int size)\n{\n  volatile ushort pd[3];\n\n  pd[0] = size-1;\n  pd[1] = (uint)p;\n  pd[2] = (uint)p >> 16;\n\n  asm volatile(\"lgdt (%0)\" : : \"r\" (pd));\n}\n\nstruct gatedesc;\n\nstatic inline void\nlidt(struct gatedesc *p, int size)\n{\n  volatile ushort pd[3];\n\n  pd[0] = size-1;\n  pd[1] = (uint)p;\n  pd[2] = (uint)p >> 16;\n\n  asm volatile(\"lidt (%0)\" : : \"r\" (pd));\n}\n\nstatic inline void\nltr(ushort sel)\n{\n  asm volatile(\"ltr %0\" : : \"r\" (sel));\n}\n\nstatic inline uint\nreadeflags(void)\n{\n  uint eflags;\n  asm volatile(\"pushfl; popl %0\" : \"=r\" (eflags));\n  return eflags;\n}\n\nstatic inline void\nloadgs(ushort v)\n{\n  asm volatile(\"movw %0, %%gs\" : : \"r\" (v));\n}\n\nstatic inline void\ncli(void)\n{\n  asm volatile(\"cli\");\n}\n\nstatic inline void\nsti(void)\n{\n  asm volatile(\"sti\");\n}\n\nstatic inline uint\nxchg(volatile uint *addr, uint newval)\n{\n  uint result;\n\n  // The + in \"+m\" denotes a read-modify-write operand.\n  asm volatile(\"lock; xchgl %0, %1\" :\n               \"+m\" (*addr), \"=a\" (result) :\n               \"1\" (newval) :\n               \"cc\");\n  return result;\n}\n\nstatic inline uint\nrcr2(void)\n{\n  uint val;\n  asm volatile(\"movl %%cr2,%0\" : \"=r\" (val));\n  return val;\n}\n\nstatic inline void\nlcr3(uint val)\n{\n  asm volatile(\"movl %0,%%cr3\" : : \"r\" (val));\n}\n\n//PAGEBREAK: 36\n// Layout of the trap frame built on the stack by the\n// hardware and by trapasm.S, and passed to trap().\nstruct trapframe {\n  // registers as pushed by pusha\n  uint edi;\n  uint esi;\n  uint ebp;\n  uint oesp;      // useless & ignored\n  uint ebx;\n  uint edx;\n  uint ecx;\n  uint eax;\n\n  // rest of trap frame\n  ushort gs;\n  ushort padding1;\n  ushort fs;\n  ushort padding2;\n  ushort es;\n  ushort padding3;\n  ushort ds;\n  ushort padding4;\n  uint trapno;\n\n  // below here defined by x86 hardware\n  uint err;\n  uint eip;\n  ushort cs;\n  ushort padding5;\n  uint eflags;\n\n  // below here only when crossing rings, such as from user to kernel\n  uint esp;\n  ushort ss;\n  ushort padding6;\n};\n"
  },
  {
    "path": "zombie.c",
    "content": "// Create a zombie process that\n// must be reparented at exit.\n\n#include \"types.h\"\n#include \"stat.h\"\n#include \"user.h\"\n\nint\nmain(void)\n{\n  if(fork() > 0)\n    sleep(5);  // Let child exit before parent.\n  exit();\n}\n"
  }
]