diff --git a/Makefile b/Makefile index fa7b33b..e0a4253 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ RS = src/*.rs # Cross-compiling (e.g., on Mac OS X) #TOOLPREFIX = i386-jos-elf -#TOOLPREFIX = i386-elf- +# TOOLPREFIX = i686-elf- # Using native tools (e.g., on X86 Linux) #TOOLPREFIX = @@ -69,19 +69,25 @@ xv6.img: bootblock kernel dd if=bootblock of=xv6.img conv=notrunc dd if=kernel of=xv6.img seek=1 conv=notrunc +mkfs: src/mkfs.rs + rustc -W warnings -o mkfs src/mkfs.rs + +fs.img: mkfs welcome.txt + ./mkfs fs.img welcome.txt + bootblock: bootasm.S bootmain.c $(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c $(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S $(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o $(OBJDUMP) -S -D bootblock.o > bootblock.asm $(OBJCOPY) -S -O binary -j .text bootblock.o bootblock - ./sign.pl bootblock + perl sign.pl bootblock kernel.a: $(RS) - cargo rustc -Z build-std=core -Z build-std-features=compiler-builtins-mem --target ./targets/i686.json --lib --release -- -A warnings --emit link=kernel.a + cargo rustc -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec --target ./targets/i686.json --lib --release -- -A warnings --emit link=kernel.a kernel: kernel.a $(OBJS) ./linkers/kernel.ld - ld -m elf_i386 -T ./linkers/kernel.ld -o kernel $(OBJS) kernel.a + $(LD) -m elf_i386 -T ./linkers/kernel.ld -o kernel $(OBJS) kernel.a $(OBJDUMP) -S -D kernel > kernel.asm $(OBJDUMP) -t kernel | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernel.sym @@ -100,12 +106,12 @@ vectors.S: vectors.pl clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ - *.a *.o *.d *.asm *.sym bootblock kernel xv6.img .gdbinit vectors.S - rm -r target + *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img .gdbinit vectors.S mkfs + rm -rf target # run in emulators # try to generate a unique GDB port -GDBPORT = $(shell expr `id -u` % 5000 + 25000) +GDBPORT = $(shell expr `id -u` % 5000 + 25001) # QEMU's gdb stub command line changed in 0.11 QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ then echo "-gdb tcp::$(GDBPORT)"; \ @@ -116,14 +122,14 @@ endif # For debugging # QEMUEXTRA = -no-reboot -d int,cpu_reset -QEMUOPTS = -drive file=xv6.img,index=0,media=disk,format=raw -smp $(CPUS) -m 512 $(QEMUEXTRA) +QEMUOPTS = -drive file=xv6.img,index=0,media=disk,format=raw -drive file=fs.img,index=1,media=disk,format=raw -smp $(CPUS) -m 512 $(QEMUEXTRA) -qemu: xv6.img +qemu: xv6.img fs.img $(QEMU) -nographic $(QEMUOPTS) .gdbinit: .gdbinit.tmpl sed "s/localhost:1234/localhost:$(GDBPORT)/" < $^ > $@ -qemu-gdb: xv6.img .gdbinit +qemu-gdb: xv6.img .gdbinit fs.img @echo "*** Now run 'gdb'." 1>&2 - $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) \ No newline at end of file + $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..079b0db --- /dev/null +++ b/src/Makefile @@ -0,0 +1,130 @@ +OBJS = entry.o vectors.o trapasm.o +RS = src/*.rs + +# Cross-compiling (e.g., on Mac OS X) +#TOOLPREFIX = i386-jos-elf +#TOOLPREFIX = i386-elf- + +# Using native tools (e.g., on X86 Linux) +#TOOLPREFIX = + +# Try to infer the correct TOOLPREFIX if not set +ifndef TOOLPREFIX +TOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/dev/null 2>&1; \ + then echo 'i386-jos-elf-'; \ + elif objdump -i 2>&1 | grep 'elf32-i386' >/dev/null 2>&1; \ + then echo ''; \ + else echo "***" 1>&2; \ + echo "*** Error: Couldn't find an i386-*-elf version of GCC/binutils." 1>&2; \ + echo "*** Is the directory with i386-jos-elf-gcc in your PATH?" 1>&2; \ + echo "*** If your i386-*-elf toolchain is installed with a command" 1>&2; \ + echo "*** prefix other than 'i386-jos-elf-', set your TOOLPREFIX" 1>&2; \ + echo "*** environment variable to that prefix and run 'make' again." 1>&2; \ + echo "*** To turn off this error, run 'gmake TOOLPREFIX= ...'." 1>&2; \ + echo "***" 1>&2; exit 1; fi) +endif + +# If the makefile can't find QEMU, specify its path here +# QEMU = qemu-system-i386 + +# Try to infer the correct QEMU +ifndef QEMU +QEMU = $(shell if which qemu > /dev/null; \ + then echo qemu; exit; \ + elif which qemu-system-i386 > /dev/null; \ + then echo qemu-system-i386; exit; \ + elif which qemu-system-x86_64 > /dev/null; \ + then echo qemu-system-x86_64; exit; \ + else \ + qemu=/Applications/Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu; \ + if test -x $$qemu; then echo $$qemu; exit; fi; fi; \ + echo "***" 1>&2; \ + echo "*** Error: Couldn't find a working QEMU executable." 1>&2; \ + echo "*** Is the directory containing the qemu binary in your PATH" 1>&2; \ + echo "*** or have you tried setting the QEMU variable in Makefile?" 1>&2; \ + echo "***" 1>&2; exit 1) +endif + +CC = $(TOOLPREFIX)gcc +AS = $(TOOLPREFIX)gas +LD = $(TOOLPREFIX)ld +OBJCOPY = $(TOOLPREFIX)objcopy +OBJDUMP = $(TOOLPREFIX)objdump +CFLAGS = -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer +CFLAGS += $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector) +ASFLAGS = -m32 -gdwarf-2 -Wa,-divide +LDFLAGS += -m $(shell $(LD) -V | grep elf_i386 2>/dev/null | head -n 1) + +# Disable PIE when possible (for Ubuntu 16.10 toolchain) +ifneq ($(shell $(CC) -dumpspecs 2>/dev/null | grep -e '[^f]no-pie'),) +CFLAGS += -fno-pie -no-pie +endif +ifneq ($(shell $(CC) -dumpspecs 2>/dev/null | grep -e '[^f]nopie'),) +CFLAGS += -fno-pie -nopie +endif + +# Disk image with bootblock + kernel +xv6.img: bootblock kernel + dd if=/dev/zero of=xv6.img count=10000 + dd if=bootblock of=xv6.img conv=notrunc + dd if=kernel of=xv6.img seek=1 conv=notrunc + +mkfs: ../../col331/mkfs.c ../../col331/fs.h ../../col331/types.h ../../col331/stat.h ../../col331/param.h + gcc -Werror -Wall -o mkfs ../../col331/mkfs.c + +fs: fs.img + +fs.img: mkfs ../welcome.txt + ./mkfs fs.img ../welcome.txt + +bootblock: bootasm.S bootmain.c + $(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c + $(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S + $(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o + $(OBJDUMP) -S -D bootblock.o > bootblock.asm + $(OBJCOPY) -S -O binary -j .text bootblock.o bootblock + perl sign.pl bootblock + +kernel.a: $(RS) + cargo rustc -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec --target ./targets/i686.json --lib --release -- -A warnings --emit link=kernel.a + + +kernel: kernel.a $(OBJS) ./linkers/kernel.ld + ld -m elf_i386 -T ./linkers/kernel.ld -o kernel $(OBJS) kernel.a + $(OBJDUMP) -S -D kernel > kernel.asm + $(OBJDUMP) -t kernel | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernel.sym + +vectors.S: vectors.pl + ./vectors.pl > vectors.S + +.PRECIOUS: %.o +-include *.d + +clean: + rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ + *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img .gdbinit vectors.S mkfs + rm -rf target + +# run in emulators +GDBPORT = $(shell expr `id -u` % 5000 + 25000) +QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ + then echo "-gdb tcp::$(GDBPORT)"; \ + else echo "-s -p $(GDBPORT)"; fi) +ifndef CPUS + CPUS := 1 +endif + +# Attach fs.img as disk1 (index=1), like the C version +QEMUOPTS = -drive file=xv6.img,index=0,media=disk,format=raw \ + -drive file=fs.img,index=1,media=disk,format=raw \ + -smp $(CPUS) -m 512 $(QEMUEXTRA) + +qemu: xv6.img fs.img + $(QEMU) -nographic $(QEMUOPTS) + +.gdbinit: .gdbinit.tmpl + sed "s/localhost:1234/localhost:$(GDBPORT)/" < $^ > $@ + +qemu-gdb: xv6.img fs .gdbinit + @echo "*** Now run 'gdb'." 1>&2 + $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) diff --git a/src/bio.rs b/src/bio.rs new file mode 100644 index 0000000..30e6d81 --- /dev/null +++ b/src/bio.rs @@ -0,0 +1,148 @@ +use core::sync::atomic::Ordering; + +use crate::buf::{Buf, B_DIRTY, B_VALID, NBUF}; + +const HEAD: usize = NBUF; // sentinel index + +struct BCache { + buf: [Buf; NBUF], + head_prev: usize, + head_next: usize, +} + +impl BCache { + pub const fn new() -> Self { + Self { + buf: [const { Buf::new() }; NBUF], + head_prev: HEAD, + head_next: HEAD, + } + } +} + +static mut BCACHE: BCache = BCache::new(); + +pub fn binit() { + unsafe { + // empty list + BCACHE.head_prev = HEAD; + BCACHE.head_next = HEAD; + + // insert all buffers at head (MRU side) + for i in 0..NBUF { + insert_at_head(i); + } + } +} + +#[inline] +fn insert_at_head(i: usize) { + unsafe { + let first = BCACHE.head_next; + + BCACHE.buf[i].prev = HEAD; + BCACHE.buf[i].next = first; + + if first == HEAD { + // list was empty + BCACHE.head_prev = i; + } else { + BCACHE.buf[first].prev = i; + } + + BCACHE.head_next = i; + } +} + +#[inline] +fn remove_from_list(i: usize) { + unsafe { + let prev = BCACHE.buf[i].prev; + let next = BCACHE.buf[i].next; + + if prev == HEAD { + BCACHE.head_next = next; + } else { + BCACHE.buf[prev].next = next; + } + + if next == HEAD { + BCACHE.head_prev = prev; + } else { + BCACHE.buf[next].prev = prev; + } + } +} + +// Return mutable buf by index. +// Safe to call only when you “own” the buffer logically (like xv6 “locked buf”). +pub fn buf_mut(idx: usize) -> &'static mut Buf { + unsafe { &mut BCACHE.buf[idx] } +} + +// Look for cached block; else recycle an unused non-dirty buffer. +fn bget(dev: u32, blockno: u32) -> usize { + unsafe { + // Is the block already cached? + let mut b = BCACHE.head_next; + while b != HEAD { + if BCACHE.buf[b].dev == dev && BCACHE.buf[b].blockno == blockno { + BCACHE.buf[b].refcnt += 1; + return b; + } + b = BCACHE.buf[b].next; + } + + // Not cached; recycle from LRU end. + let mut b = BCACHE.head_prev; + while b != HEAD { + let flags = BCACHE.buf[b].flags.load(Ordering::Acquire); + if BCACHE.buf[b].refcnt == 0 && (flags & B_DIRTY) == 0 { + BCACHE.buf[b].dev = dev; + BCACHE.buf[b].blockno = blockno; + BCACHE.buf[b].flags.store(0, Ordering::Release); + BCACHE.buf[b].refcnt = 1; + BCACHE.buf[b].qnext = None; + return b; + } + b = BCACHE.buf[b].prev; + } + + panic!("bget: no buffers"); + } +} + +// Return buffer index with contents of block. +pub fn bread(dev: u32, blockno: u32) -> usize { + let idx = bget(dev, blockno); + + let flags = buf_mut(idx).flags.load(Ordering::Acquire); + if (flags & B_VALID) == 0 { + crate::ide::iderw(idx); + } + + idx +} + +// Mark dirty + write to disk. +pub fn bwrite(idx: usize) { + let b = buf_mut(idx); + b.flags.fetch_or(B_DIRTY, Ordering::AcqRel); + crate::ide::iderw(idx); +} + +// Release buffer. If refcnt hits 0, move to MRU head. +pub fn brelse(idx: usize) { + unsafe { + let b = &mut BCACHE.buf[idx]; + if b.refcnt == 0 { + panic!("brelse: refcnt underflow"); + } + + b.refcnt -= 1; + if b.refcnt == 0 { + remove_from_list(idx); + insert_at_head(idx); + } + } +} \ No newline at end of file diff --git a/src/buf.rs b/src/buf.rs new file mode 100644 index 0000000..870a4e3 --- /dev/null +++ b/src/buf.rs @@ -0,0 +1,39 @@ +use core::sync::atomic::AtomicU32; + +pub const BSIZE: usize = 512; // block size +pub const NBUF: usize = 30; // same as xv6 default; can tune later + +pub const B_VALID: u32 = 0x2; // buffer has been read from disk +pub const B_DIRTY: u32 = 0x4; // buffer needs to be written to disk + +#[repr(C)] +pub struct Buf { + pub flags: AtomicU32, + pub dev: u32, + pub blockno: u32, + pub refcnt: u32, + + // LRU list (intrusive, by index) + pub prev: usize, + pub next: usize, + + // disk queue (by index) + pub qnext: Option, + + pub data: [u8; BSIZE], +} + +impl Buf { + pub const fn new() -> Self { + Self { + flags: AtomicU32::new(0), + dev: 0, + blockno: 0, + refcnt: 0, + prev: 0, + next: 0, + qnext: None, + data: [0; BSIZE], + } + } +} \ No newline at end of file diff --git a/src/console.rs b/src/console.rs index 0f62712..b9ea7fa 100644 --- a/src/console.rs +++ b/src/console.rs @@ -12,8 +12,27 @@ impl Write for Console { } const BACKSPACE: char = '\x08'; +const INPUT_BUF: u32 = 128; -fn consputc(c: char) { +struct Input { + buf: [u8; INPUT_BUF as usize], + r: u32, // Read index + w: u32, // Write index + e: u32, // Edit index +} + +static mut INPUT: Input = Input { + buf: [0; INPUT_BUF as usize], + r: 0, + w: 0, + e: 0, +}; + +const fn ctrl(x: u8) -> u8 { + x - b'@' +} + +pub fn consputc(c: char) { if c == BACKSPACE { uartputc(BACKSPACE); uartputc(' '); @@ -21,4 +40,45 @@ fn consputc(c: char) { } else { uartputc(c); } -} \ No newline at end of file +} + +pub fn consoleintr(getc: fn() -> i32) { + loop { + let ch_raw = getc(); + if ch_raw < 0 { + break; + } + + unsafe { + match ch_raw as u8 { + x if x == ctrl(b'U') => { + while INPUT.e != INPUT.w + && INPUT.buf[((INPUT.e - 1) % INPUT_BUF) as usize] != b'\n' + { + INPUT.e -= 1; + consputc(BACKSPACE); + } + } + x if x == ctrl(b'H') || x == 0x7f => { + if INPUT.e != INPUT.w { + INPUT.e -= 1; + consputc(BACKSPACE); + } + } + mut ch => { + if ch != 0 && INPUT.e - INPUT.r < INPUT_BUF { + if ch == b'\r' { + ch = b'\n'; + } + INPUT.buf[(INPUT.e % INPUT_BUF) as usize] = ch; + INPUT.e += 1; + consputc(ch as char); + if ch == b'\n' || ch == ctrl(b'D') || INPUT.e == INPUT.r + INPUT_BUF { + INPUT.w = INPUT.e; + } + } + } + } + } + } +} diff --git a/src/constants.rs b/src/constants.rs index d06b826..5388c0a 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -60,7 +60,7 @@ pub const IRQ_COM1: u32 = 4; pub const IRQ_IDE: u32 = 14; pub const IRQ_ERROR: u32 = 19; pub const IRQ_SPURIOUS: u32 = 31; - +pub const IDE_TRAP: u32 = T_IRQ0 + IRQ_IDE; // ------------------------------------------------------ MP RELATED ------------------------------------------------------- diff --git a/src/fs.rs b/src/fs.rs new file mode 100644 index 0000000..73944d9 --- /dev/null +++ b/src/fs.rs @@ -0,0 +1,496 @@ +use core::cmp::min; + +use crate::bio; +use crate::buf::BSIZE; +use crate::param::NINODE; +use crate::println; + +pub const ROOTINO: u32 = 1; +pub const NDIRECT: usize = 12; +pub const NINDIRECT: usize = BSIZE / core::mem::size_of::(); +pub const DIRSIZ: usize = 14; +pub const DIRENT_SIZE: usize = 2 + DIRSIZ; + +pub const T_DIR: i16 = 1; // Directory +pub const T_FILE: i16 = 2; // File +pub const T_DEV: i16 = 3; // Device + +const DINODE_SIZE: usize = 2 + 2 + 2 + 2 + 4 + ((NDIRECT + 1) * 4); +const IPB: u32 = (BSIZE / DINODE_SIZE) as u32; + +#[derive(Copy, Clone)] +#[repr(C)] +pub struct Superblock { + pub size: u32, + pub nblocks: u32, + pub ninodes: u32, + pub nlog: u32, + pub logstart: u32, + pub inodestart: u32, + pub bmapstart: u32, +} + +impl Superblock { + pub const fn new() -> Self { + Self { + size: 0, + nblocks: 0, + ninodes: 0, + nlog: 0, + logstart: 0, + inodestart: 0, + bmapstart: 0, + } + } +} + +#[repr(C)] +pub struct Inode { + pub dev: u32, + pub inum: u32, + pub refcnt: i32, + pub valid: i32, + + pub type_: i16, + pub major: i16, + pub minor: i16, + pub nlink: i16, + pub size: u32, + pub addrs: [u32; NDIRECT + 1], +} + +impl Inode { + pub const fn new() -> Self { + Self { + dev: 0, + inum: 0, + refcnt: 0, + valid: 0, + type_: 0, + major: 0, + minor: 0, + nlink: 0, + size: 0, + addrs: [0; NDIRECT + 1], + } + } +} + +#[repr(C)] +pub struct Stat { + pub type_: i16, + pub dev: i32, + pub ino: u32, + pub nlink: i16, + pub size: u32, +} + +impl Stat { + pub const fn new() -> Self { + Self { + type_: 0, + dev: 0, + ino: 0, + nlink: 0, + size: 0, + } + } +} + +#[derive(Copy, Clone)] +#[repr(C)] +pub struct Dirent { + pub inum: u16, + pub name: [u8; DIRSIZ], +} + +impl Dirent { + pub const fn new() -> Self { + Self { + inum: 0, + name: [0; DIRSIZ], + } + } +} + +struct ICache { + inode: [Inode; NINODE], +} + +impl ICache { + const fn new() -> Self { + Self { + inode: [const { Inode::new() }; NINODE], + } + } +} + +static mut SB: Superblock = Superblock::new(); +static mut ICACHE: ICache = ICache::new(); + +#[inline] +fn read_u16_le(data: &[u8], off: usize) -> u16 { + u16::from_le_bytes([data[off], data[off + 1]]) +} + +#[inline] +fn read_i16_le(data: &[u8], off: usize) -> i16 { + i16::from_le_bytes([data[off], data[off + 1]]) +} + +#[inline] +fn read_u32_le(data: &[u8], off: usize) -> u32 { + u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]) +} + +#[inline] +fn iblock(inum: u32, sb: &Superblock) -> u32 { + inum / IPB + sb.inodestart +} + +pub fn parse_dirent(raw: &[u8]) -> Dirent { + let mut de = Dirent::new(); + de.inum = read_u16_le(raw, 0); + de.name.copy_from_slice(&raw[2..2 + DIRSIZ]); + de +} + +pub fn readsb(dev: u32, sb: &mut Superblock) { + let bp = bio::bread(dev, 1); + let data = &bio::buf_mut(bp).data; + + sb.size = read_u32_le(data, 0); + sb.nblocks = read_u32_le(data, 4); + sb.ninodes = read_u32_le(data, 8); + sb.nlog = read_u32_le(data, 12); + sb.logstart = read_u32_le(data, 16); + sb.inodestart = read_u32_le(data, 20); + sb.bmapstart = read_u32_le(data, 24); + + bio::brelse(bp); +} + +pub fn iinit(dev: u32) { + unsafe { + readsb(dev, &mut SB); + println!( + "sb: size {} nblocks {} ninodes {} nlog {} logstart {} inodestart {} bmap start {}", + SB.size, SB.nblocks, SB.ninodes, SB.nlog, SB.logstart, SB.inodestart, SB.bmapstart + ); + } +} + +/// Decrement reference count of inode at index idx. +/// Mirrors C: static void irelse(struct inode *ip) { ip->ref--; } +fn irelse(idx: usize) { + unsafe { + if idx >= NINODE { + panic!("irelse: bad inode index"); + } + ICACHE.inode[idx].refcnt -= 1; + } +} + +pub fn iget(dev: u32, inum: u32) -> usize { + unsafe { + let mut empty: Option = None; + + for i in 0..NINODE { + let ip = &mut ICACHE.inode[i]; + + if ip.refcnt > 0 && ip.dev == dev && ip.inum == inum { + ip.refcnt += 1; + return i; + } + + if empty.is_none() && ip.refcnt == 0 { + empty = Some(i); + } + } + + let idx = empty.unwrap_or_else(|| panic!("iget: no inodes")); + let ip = &mut ICACHE.inode[idx]; + + ip.dev = dev; + ip.inum = inum; + ip.refcnt = 1; + ip.valid = 0; + + idx + } +} + +pub fn iread(idx: usize) { + unsafe { + if idx >= NINODE { + panic!("iread: bad inode index"); + } + + let ip = &mut ICACHE.inode[idx]; + if ip.refcnt < 1 { + panic!("iread"); + } + + if ip.valid == 0 { + let bp = bio::bread(ip.dev, iblock(ip.inum, &SB)); + let data = &bio::buf_mut(bp).data; + + let off = (ip.inum % IPB) as usize * DINODE_SIZE; + ip.type_ = read_i16_le(data, off); + ip.major = read_i16_le(data, off + 2); + ip.minor = read_i16_le(data, off + 4); + ip.nlink = read_i16_le(data, off + 6); + ip.size = read_u32_le(data, off + 8); + + for i in 0..(NDIRECT + 1) { + ip.addrs[i] = read_u32_le(data, off + 12 + (i * 4)); + } + + bio::brelse(bp); + + ip.valid = 1; + if ip.type_ == 0 { + panic!("iread: no type"); + } + } + } +} + +fn bmap(ip: &Inode, bn: u32) -> u32 { + if (bn as usize) < NDIRECT { + return ip.addrs[bn as usize]; + } + + let bn = bn - (NDIRECT as u32); + if (bn as usize) < NINDIRECT { + let bp = bio::bread(ip.dev, ip.addrs[NDIRECT]); + let addr = { + let data = &bio::buf_mut(bp).data; + read_u32_le(data, (bn as usize) * 4) + }; + bio::brelse(bp); + return addr; + } + + panic!("bmap: out of range"); +} + +pub fn stati(idx: usize, st: &mut Stat) { + unsafe { + if idx >= NINODE { + panic!("stati: bad inode index"); + } + + let ip = &ICACHE.inode[idx]; + st.dev = ip.dev as i32; + st.ino = ip.inum; + st.type_ = ip.type_; + st.nlink = ip.nlink; + st.size = ip.size; + } +} + +pub fn readi(idx: usize, dst: &mut [u8], off: u32, n: u32) -> i32 { + unsafe { + if idx >= NINODE { + panic!("readi: bad inode index"); + } + + let ip = &ICACHE.inode[idx]; + if off > ip.size || off.checked_add(n).is_none() { + return -1; + } + + let mut n = n; + if off + n > ip.size { + n = ip.size - off; + } + + if (n as usize) > dst.len() { + panic!("readi: destination too small"); + } + + let mut tot: u32 = 0; + let mut cur_off = off; + + while tot < n { + let bp = bio::bread(ip.dev, bmap(ip, cur_off / (BSIZE as u32))); + + let m = min((n - tot) as usize, BSIZE - (cur_off as usize % BSIZE)); + let boff = cur_off as usize % BSIZE; + dst[tot as usize..tot as usize + m] + .copy_from_slice(&bio::buf_mut(bp).data[boff..boff + m]); + bio::brelse(bp); + + tot += m as u32; + cur_off += m as u32; + } + + n as i32 + } +} + +// ===================================================================== +// Directories +// ===================================================================== + +/// Compare two directory entry names (up to DIRSIZ bytes). +pub fn namecmp(s: &[u8], t: &[u8]) -> bool { + let slen = s.iter().take(DIRSIZ).position(|&b| b == 0).unwrap_or(DIRSIZ.min(s.len())); + let tlen = t.iter().take(DIRSIZ).position(|&b| b == 0).unwrap_or(DIRSIZ.min(t.len())); + if slen != tlen { + return false; + } + for i in 0..slen { + if s[i] != t[i] { + return false; + } + } + true +} + +/// Look for a directory entry in a directory inode. +/// If found, return the inode cache index of the entry. +pub fn dirlookup(dp_idx: usize, name: &[u8]) -> Option { + unsafe { + if dp_idx >= NINODE { + panic!("dirlookup: bad inode index"); + } + + let dp = &ICACHE.inode[dp_idx]; + if dp.type_ != T_DIR { + panic!("dirlookup not DIR"); + } + + let mut off: u32 = 0; + let de_size = DIRENT_SIZE as u32; + + while off < dp.size { + let mut raw = [0u8; DIRENT_SIZE]; + if readi(dp_idx, &mut raw, off, de_size) != de_size as i32 { + panic!("dirlookup read"); + } + + let de = parse_dirent(&raw); + if de.inum == 0 { + off += de_size; + continue; + } + + if namecmp(name, &de.name) { + // entry matches path element + let inum = de.inum as u32; + return Some(iget(dp.dev, inum)); + } + off += de_size; + } + + None + } +} + +// ===================================================================== +// Paths +// ===================================================================== + +/// Copy the next path element from path into name. +/// Return the remaining path after the element (with leading slashes stripped), +/// or None if there is no element to extract. +fn skipelem<'a>(path: &'a [u8], name: &mut [u8; DIRSIZ]) -> Option<&'a [u8]> { + let mut i = 0; + + // Skip leading slashes + while i < path.len() && path[i] == b'/' { + i += 1; + } + if i >= path.len() || path[i] == 0 { + return None; + } + + let start = i; + // Find end of this path element + while i < path.len() && path[i] != b'/' && path[i] != 0 { + i += 1; + } + let len = i - start; + + // Copy element into name + if len >= DIRSIZ { + name.copy_from_slice(&path[start..start + DIRSIZ]); + } else { + name[..len].copy_from_slice(&path[start..start + len]); + name[len] = 0; + // Zero out rest of name for cleanliness + for j in (len + 1)..DIRSIZ { + name[j] = 0; + } + } + + // Skip trailing slashes + while i < path.len() && path[i] == b'/' { + i += 1; + } + + Some(&path[i..]) +} + +/// Look up and return the inode cache index for a path name. +/// If nameiparent_flag is true, return the inode for the parent and copy +/// the final path element into name. +fn namex(path: &[u8], nameiparent_flag: bool, name: &mut [u8; DIRSIZ]) -> Option { + let mut ip = iget(crate::param::ROOTDEV, ROOTINO); + + let mut remaining = path; + loop { + match skipelem(remaining, name) { + None => break, + Some(rest) => { + iread(ip); + unsafe { + if ICACHE.inode[ip].type_ != T_DIR { + irelse(ip); + return None; + } + } + + // If looking for parent and this is the last element + if nameiparent_flag && (rest.is_empty() || rest[0] == 0) { + // Stop one level early. + return Some(ip); + } + + match dirlookup(ip, name) { + None => { + irelse(ip); + return None; + } + Some(next) => { + irelse(ip); + ip = next; + } + } + remaining = rest; + } + } + } + + if nameiparent_flag { + irelse(ip); + return None; + } + Some(ip) +} + +/// Look up the inode cache index for a path name. +/// Mirrors C: struct inode* namei(char *path) +pub fn namei(path: &[u8]) -> Option { + let mut name = [0u8; DIRSIZ]; + namex(path, false, &mut name) +} + +/// Look up the parent inode for a path name, and copy the final +/// path element into name. +/// Mirrors C: struct inode* nameiparent(char *path, char *name) +pub fn nameiparent(path: &[u8], name: &mut [u8; DIRSIZ]) -> Option { + namex(path, true, name) +} \ No newline at end of file diff --git a/src/ide.rs b/src/ide.rs new file mode 100644 index 0000000..e7ac913 --- /dev/null +++ b/src/ide.rs @@ -0,0 +1,170 @@ +use core::sync::atomic::Ordering; +use crate::buf::{BSIZE, B_DIRTY, B_VALID}; +use crate::x86; + +const SECTOR_SIZE: usize = 512; + +const IDE_BSY: u8 = 0x80; +const IDE_DRDY: u8 = 0x40; +const IDE_DF: u8 = 0x20; +const IDE_ERR: u8 = 0x01; + +const IDE_CMD_READ: u8 = 0x20; +const IDE_CMD_WRITE: u8 = 0x30; +const IDE_CMD_RDMUL: u8 = 0xC4; +const IDE_CMD_WRMUL: u8 = 0xC5; + +// If you later build a real FS image, keep this consistent with your mkfs. +// xv6 uses 1000. +const FSSIZE: u32 = 1000; + +static mut IDEQUEUE: Option = None; +static mut HAVEDISK1: bool = false; + +fn idewait(checkerr: bool) -> i32 { + let mut r: u8; + loop { + r = x86::inb(0x1F7); + if (r & (IDE_BSY | IDE_DRDY)) == IDE_DRDY { + break; + } + } + if checkerr && (r & (IDE_DF | IDE_ERR)) != 0 { + return -1; + } + 0 +} + +pub fn ideinit() { + // Route IDE IRQ somewhere; simplest is CPU 0 for now. + crate::ioapic::ioapic_enable(crate::constants::IRQ_IDE, 0); + + idewait(false); + + // Check if disk 1 is present + unsafe { + x86::outb(0x1F6, 0xE0 | (1 << 4)); + for _ in 0..1000 { + if x86::inb(0x1F7) != 0 { + HAVEDISK1 = true; + break; + } + } + // Switch back to disk 0 + x86::outb(0x1F6, 0xE0 | (0 << 4)); + } +} + +fn idestart(idx: usize) { + let b = crate::bio::buf_mut(idx); + + if b.blockno >= FSSIZE { + panic!("idestart: incorrect blockno"); + } + + let sector_per_block = BSIZE / SECTOR_SIZE; // usually 1 + let sector = (b.blockno as usize) * sector_per_block; + + let read_cmd = if sector_per_block == 1 { IDE_CMD_READ } else { IDE_CMD_RDMUL }; + let write_cmd = if sector_per_block == 1 { IDE_CMD_WRITE } else { IDE_CMD_WRMUL }; + + if sector_per_block > 7 { + panic!("idestart: sector_per_block > 7"); + } + + idewait(false); + x86::outb(0x3F6, 0); // generate interrupt + + x86::outb(0x1F2, sector_per_block as u8); // number of sectors + x86::outb(0x1F3, (sector & 0xFF) as u8); + x86::outb(0x1F4, ((sector >> 8) & 0xFF) as u8); + x86::outb(0x1F5, ((sector >> 16) & 0xFF) as u8); + x86::outb( + 0x1F6, + 0xE0 | (((b.dev & 1) as u8) << 4) | (((sector >> 24) & 0x0F) as u8), + ); + + let flags = b.flags.load(Ordering::Acquire); + if (flags & B_DIRTY) != 0 { + x86::outb(0x1F7, write_cmd); + + // write BSIZE bytes as u32 words + unsafe { + x86::outsl(0x1F0, b.data.as_ptr() as *const u32, BSIZE / 4); + } + } else { + x86::outb(0x1F7, read_cmd); + } +} + +// Interrupt handler. +pub fn ideintr() { + let idx = unsafe { + match IDEQUEUE { + None => return, + Some(i) => { + let b = crate::bio::buf_mut(i); + IDEQUEUE = b.qnext; + b.qnext = None; + i + } + } + }; + + let b = crate::bio::buf_mut(idx); + + let flags = b.flags.load(Ordering::Acquire); + + // Read data if needed. + if (flags & B_DIRTY) == 0 && idewait(true) >= 0 { + unsafe { + x86::insl(0x1F0, b.data.as_mut_ptr() as *mut u32, BSIZE / 4); + } + } + + b.flags.fetch_or(B_VALID, Ordering::AcqRel); + b.flags.fetch_and(!B_DIRTY, Ordering::AcqRel); + + // Start next buffer in queue. + unsafe { + if let Some(next) = IDEQUEUE { + idestart(next); + } + } +} + +// ide.rs +pub fn iderw(idx: usize) { + let b = crate::bio::buf_mut(idx); + + let flags = b.flags.load(Ordering::Acquire); + if (flags & (B_VALID | B_DIRTY)) == B_VALID { + panic!("iderw: nothing to do"); + } + + unsafe { + if b.dev != 0 && !HAVEDISK1 { + panic!("iderw: ide disk 1 not present"); + } + } + + // PURE POLLING: issue the command directly (no IDEQUEUE). + idestart(idx); + + // Wait for completion. + if idewait(true) < 0 { + panic!("iderw: ide error"); + } + + // If it was a read, pull data now. + let flags_now = b.flags.load(Ordering::Acquire); + if (flags_now & B_DIRTY) == 0 { + unsafe { + crate::x86::insl(0x1F0, b.data.as_mut_ptr() as *mut u32, BSIZE / 4); + } + } + // If it was a write, data was already pushed in idestart() via outsl(). + + b.flags.fetch_or(B_VALID, Ordering::AcqRel); + b.flags.fetch_and(!B_DIRTY, Ordering::AcqRel); +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index aa34772..ecf6b6e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,10 @@ mod mp; mod proc; mod traps; mod constants; - +mod buf; +mod bio; +mod ide; +mod fs; use crate::traps::*; #[macro_export] @@ -35,8 +38,44 @@ fn halt() -> ! { } } +fn print_bytes(bytes: &[u8]) { + for &ch in bytes { + console::consputc(ch as char); + } +} + +fn print_cstr(bytes: &[u8]) { + for &ch in bytes { + if ch == 0 { + break; + } + console::consputc(ch as char); + } +} + +fn welcome() { + // p9: Use namei to look up /welcome.txt by path instead of manually + // reading directory entries from the root inode. + let wtxt = fs::namei(b"/welcome.txt").unwrap_or_else(|| { + panic!("welcome: /welcome.txt not found"); + }); + fs::iread(wtxt); + let mut st = fs::Stat::new(); + fs::stati(wtxt, &mut st); + println!( + "\nwelcome.txt stats: Device {}, inode number {}, type {}, number of links {}, size {}", + st.dev, st.ino, st.type_, st.nlink, st.size + ); + + let mut greet = [0u8; 512]; + let n = fs::readi(wtxt, &mut greet, 0, st.size); + println!("Read {} bytes from welcome.txt", n); + print_bytes(&greet[..n as usize]); + console::consputc('\n'); +} + extern "C" { - pub static alltraps: fn(); + pub fn alltraps(); } #[no_mangle] @@ -46,9 +85,14 @@ pub extern "C" fn entryofrust() -> ! { picirq::picinit(); ioapic::ioapic_init(); uart::uartinit(); + ide::ideinit(); tvinit(); + bio::binit(); idtinit(); x86::sti(); + fs::iinit(param::ROOTDEV); + welcome(); + loop { x86::wfi(); } @@ -58,4 +102,4 @@ pub extern "C" fn entryofrust() -> ! { fn panic(info: &PanicInfo) -> ! { println!("Kernel Panic: {:?}", info); loop {} -} \ No newline at end of file +} diff --git a/src/mkfs.rs b/src/mkfs.rs new file mode 100644 index 0000000..6363752 --- /dev/null +++ b/src/mkfs.rs @@ -0,0 +1,358 @@ +use std::env; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::mem::size_of; +use std::path::Path; + +// File system constants — must match param.h / fs.h from C repo p9-name-layer +const BSIZE: usize = 512; +const FSSIZE: u32 = 1000; +const NINODES: u32 = 200; +const LOGSIZE: u32 = 0; + +const ROOTINO: u32 = 1; +const NDIRECT: usize = 12; +const NINDIRECT: usize = BSIZE / size_of::(); +const MAXFILE: usize = NDIRECT + NINDIRECT; +const DIRSIZ: usize = 14; + +const T_DIR: u16 = 1; +const T_FILE: u16 = 2; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Superblock { + size: u32, + nblocks: u32, + ninodes: u32, + nlog: u32, + logstart: u32, + inodestart: u32, + bmapstart: u32, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Dinode { + typ: u16, + major: u16, + minor: u16, + nlink: u16, + size: u32, + addrs: [u32; NDIRECT + 1], +} + +impl Default for Dinode { + fn default() -> Self { + Self { + typ: 0, + major: 0, + minor: 0, + nlink: 0, + size: 0, + addrs: [0; NDIRECT + 1], + } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Dirent { + inum: u16, + name: [u8; DIRSIZ], +} + +impl Default for Dirent { + fn default() -> Self { + Self { + inum: 0, + name: [0; DIRSIZ], + } + } +} + +struct Mkfs { + fsfd: File, + sb: Superblock, + freeinode: u32, + freeblock: u32, +} + +fn as_bytes(val: &T) -> &[u8] { + unsafe { std::slice::from_raw_parts((val as *const T).cast::(), size_of::()) } +} + +fn from_bytes(bytes: &[u8]) -> T { + assert_eq!(bytes.len(), size_of::()); + let mut out = std::mem::MaybeUninit::::uninit(); + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out.as_mut_ptr().cast::(), bytes.len()); + out.assume_init() + } +} + +fn name_to_dirent(name: &str, inum: u16) -> Dirent { + let mut de = Dirent { + inum: inum.to_le(), + ..Default::default() + }; + let name_bytes = name.as_bytes(); + let copy_len = name_bytes.len().min(DIRSIZ); + de.name[..copy_len].copy_from_slice(&name_bytes[..copy_len]); + de +} + +impl Mkfs { + fn new(fsfd: File, sb: Superblock, freeblock: u32) -> Self { + Self { + fsfd, + sb, + freeinode: 1, + freeblock, + } + } + + fn wsect(&mut self, sec: u32, buf: &[u8; BSIZE]) { + let off = (sec as u64) * (BSIZE as u64); + self.fsfd + .seek(SeekFrom::Start(off)) + .expect("lseek(write) failed"); + self.fsfd.write_all(buf).expect("write failed"); + } + + fn rsect(&mut self, sec: u32, buf: &mut [u8; BSIZE]) { + let off = (sec as u64) * (BSIZE as u64); + self.fsfd + .seek(SeekFrom::Start(off)) + .expect("lseek(read) failed"); + self.fsfd.read_exact(buf).expect("read failed"); + } + + fn iblock(&self, inum: u32) -> u32 { + (inum / ipb() as u32) + u32::from_le(self.sb.inodestart) + } + + fn winode(&mut self, inum: u32, ip: &Dinode) { + let mut buf = [0u8; BSIZE]; + let bn = self.iblock(inum); + self.rsect(bn, &mut buf); + + let off = (inum as usize % ipb()) * size_of::(); + let src = as_bytes(ip); + buf[off..off + size_of::()].copy_from_slice(src); + self.wsect(bn, &buf); + } + + fn rinode(&mut self, inum: u32) -> Dinode { + let mut buf = [0u8; BSIZE]; + let bn = self.iblock(inum); + self.rsect(bn, &mut buf); + + let off = (inum as usize % ipb()) * size_of::(); + from_bytes::(&buf[off..off + size_of::()]) + } + + fn ialloc(&mut self, typ: u16) -> u32 { + let inum = self.freeinode; + self.freeinode += 1; + + let din = Dinode { + typ: typ.to_le(), + nlink: 1u16.to_le(), + size: 0u32.to_le(), + ..Default::default() + }; + self.winode(inum, &din); + inum + } + + fn balloc(&mut self, used: u32) { + assert!(used < (BSIZE * 8) as u32); + println!("balloc: first {} blocks have been allocated", used); + + let mut buf = [0u8; BSIZE]; + for i in 0..used { + let idx = (i / 8) as usize; + let bit = (i % 8) as u8; + buf[idx] |= 1u8 << bit; + } + + let bmapstart = u32::from_le(self.sb.bmapstart); + println!("balloc: write bitmap block at sector {}", bmapstart); + self.wsect(bmapstart, &buf); + } + + fn iappend(&mut self, inum: u32, mut p: &[u8]) { + let mut din = self.rinode(inum); + let mut off = u32::from_le(din.size); + + while !p.is_empty() { + let fbn = (off as usize) / BSIZE; + assert!(fbn < MAXFILE); + + let x: u32; + if fbn < NDIRECT { + if u32::from_le(din.addrs[fbn]) == 0 { + din.addrs[fbn] = self.freeblock.to_le(); + self.freeblock += 1; + } + x = u32::from_le(din.addrs[fbn]); + } else { + if u32::from_le(din.addrs[NDIRECT]) == 0 { + din.addrs[NDIRECT] = self.freeblock.to_le(); + self.freeblock += 1; + } + + let mut indirect_sector = [0u8; BSIZE]; + let indirect_blockno = u32::from_le(din.addrs[NDIRECT]); + self.rsect(indirect_blockno, &mut indirect_sector); + + let indirect_idx = fbn - NDIRECT; + let byte_off = indirect_idx * size_of::(); + let mut indirect_entry = u32::from_le(from_bytes::( + &indirect_sector[byte_off..byte_off + size_of::()], + )); + + if indirect_entry == 0 { + indirect_entry = self.freeblock; + self.freeblock += 1; + let le = indirect_entry.to_le(); + indirect_sector[byte_off..byte_off + size_of::()] + .copy_from_slice(as_bytes(&le)); + self.wsect(indirect_blockno, &indirect_sector); + } + + x = indirect_entry; + } + + let mut buf = [0u8; BSIZE]; + self.rsect(x, &mut buf); + + let n1 = p + .len() + .min((fbn as u32 + 1) as usize * BSIZE - off as usize); + let block_off = off as usize - (fbn * BSIZE); + buf[block_off..block_off + n1].copy_from_slice(&p[..n1]); + self.wsect(x, &buf); + + off += n1 as u32; + p = &p[n1..]; + } + + din.size = off.to_le(); + self.winode(inum, &din); + } +} + +fn ipb() -> usize { + BSIZE / size_of::() +} + +fn main() { + assert_eq!(size_of::(), 4, "Integers must be 4 bytes"); + assert_eq!(BSIZE % size_of::(), 0); + assert_eq!(BSIZE % size_of::(), 0); + + let mut args = env::args().collect::>(); + if args.len() < 2 { + eprintln!("Usage: mkfs fs.img files..."); + std::process::exit(1); + } + + let fs_img = args.remove(1); + + let nbitmap = FSSIZE / (BSIZE as u32 * 8) + 1; + let ninodeblocks = NINODES / ipb() as u32 + 1; + let nlog = LOGSIZE; + let nmeta = 2 + nlog + ninodeblocks + nbitmap; + let nblocks = FSSIZE - nmeta; + + let sb = Superblock { + size: FSSIZE.to_le(), + nblocks: nblocks.to_le(), + ninodes: NINODES.to_le(), + nlog: nlog.to_le(), + logstart: 2u32.to_le(), + inodestart: (2 + nlog).to_le(), + bmapstart: (2 + nlog + ninodeblocks).to_le(), + }; + + println!( + "nmeta {} (boot, super, log blocks {} inode blocks {}, bitmap blocks {}) blocks {} total {}", + nmeta, nlog, ninodeblocks, nbitmap, nblocks, FSSIZE + ); + + let fsfd = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&fs_img) + .unwrap_or_else(|e| { + eprintln!("{}: {}", fs_img, e); + std::process::exit(1); + }); + + let mut mkfs = Mkfs::new(fsfd, sb, nmeta); + + let zeroes = [0u8; BSIZE]; + for i in 0..FSSIZE { + mkfs.wsect(i, &zeroes); + } + + let mut sb_buf = [0u8; BSIZE]; + sb_buf[..size_of::()].copy_from_slice(as_bytes(&mkfs.sb)); + mkfs.wsect(1, &sb_buf); + + let rootino = mkfs.ialloc(T_DIR); + assert_eq!(rootino, ROOTINO); + + let dot = name_to_dirent(".", rootino as u16); + mkfs.iappend(rootino, as_bytes(&dot)); + + let dotdot = name_to_dirent("..", rootino as u16); + mkfs.iappend(rootino, as_bytes(&dotdot)); + + for path in &args[1..] { + if path.contains('/') { + eprintln!("{}: must be a basename (no /)", path); + std::process::exit(1); + } + + let mut host_file = File::open(path).unwrap_or_else(|e| { + eprintln!("{}: {}", path, e); + std::process::exit(1); + }); + + let file_name = if let Some(stripped) = path.strip_prefix('_') { + stripped + } else { + Path::new(path) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(path) + }; + + let inum = mkfs.ialloc(T_FILE); + let de = name_to_dirent(file_name, inum as u16); + mkfs.iappend(rootino, as_bytes(&de)); + + let mut buf = [0u8; BSIZE]; + loop { + let cc = host_file.read(&mut buf).expect("read input file failed"); + if cc == 0 { + break; + } + mkfs.iappend(inum, &buf[..cc]); + } + } + + // fix size of root inode dir + let mut din = mkfs.rinode(rootino); + let mut off = u32::from_le(din.size); + off = ((off / BSIZE as u32) + 1) * BSIZE as u32; + din.size = off.to_le(); + mkfs.winode(rootino, &din); + + mkfs.balloc(mkfs.freeblock); +} \ No newline at end of file diff --git a/src/param.rs b/src/param.rs index 4341329..63a19c7 100644 --- a/src/param.rs +++ b/src/param.rs @@ -1,2 +1,4 @@ pub const KSTACKSIZE: usize = 4096; // size of per-process kernel stack pub const NCPU: usize = 8; // maximum number of CPUs +pub const NINODE: usize = 50; // maximum number of active i-nodes +pub const ROOTDEV: u32 = 1; // device number of file system root disk diff --git a/src/traps.rs b/src/traps.rs index 0643fcc..1278148 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -14,6 +14,7 @@ pub const T_IRQ0: u32 = 32; pub const IRQ_TIMER: u32 = 0; pub const IRQ_ERROR: u32 = 19; pub const IRQ_SPURIOUS: u32 = 31; +const LOG_TICKS: bool = false; extern "C" { static vectors: [usize; 256]; // remove assembly. @@ -96,7 +97,7 @@ pub fn tvinit() { 0 // Descriptor privilege level. ); } - IDT.idt.set(arr); + let _ = IDT.idt.set(arr); } pub fn idtinit() { @@ -116,11 +117,12 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { const TIMER: u32 = T_IRQ0 + IRQ_TIMER; const SPURIOUS: u32 = T_IRQ0 + IRQ_SPURIOUS; const SEVEN: u32 = T_IRQ0 + 7; - match tf.trapno { TIMER => { *IDT.ticks.borrow_mut() += 1; - println!("Tick {}!", IDT.ticks.borrow()); + if LOG_TICKS { + println!("Tick {}!", IDT.ticks.borrow()); + } lapic::lapiceoi(); } SEVEN | SPURIOUS => { @@ -132,6 +134,11 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { ); lapiceoi(); } + crate::constants::IDE_TRAP => { + crate::ide::ideintr(); + crate::lapic::lapiceoi(); + } + _ => { println!( "unexpected trap {} from cpu {} eip {} (cr2=0x{:x})\n", @@ -143,4 +150,4 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { panic!("trap happened"); } } -} \ No newline at end of file +} diff --git a/src/uart.rs b/src/uart.rs index 9888088..a6c800b 100644 --- a/src/uart.rs +++ b/src/uart.rs @@ -1,7 +1,12 @@ use crate::x86::{outb, inb}; +use crate::console::consoleintr; use crate::ioapic::ioapic_enable; +use core::sync::atomic::{AtomicBool, Ordering}; const COM1: u16 = 0x3F8; // COM1 port address pub const IRQ_COM1: u32 = 4; + +static UART_PRESENT: AtomicBool = AtomicBool::new(false); + pub fn uartinit() { // Turn off the FIFO. outb(COM1 + 2, 0); @@ -19,7 +24,9 @@ pub fn uartinit() { if inb(COM1 + 5) == 0xFF { return; } - + + UART_PRESENT.store(true, Ordering::Relaxed); + // Acknowledge pre-existing interrupt conditions; // enable interrupts. inb(COM1+2); @@ -33,10 +40,27 @@ pub fn uartinit() { } pub fn uartputc(c: char) { + if !UART_PRESENT.load(Ordering::Relaxed) { + return; + } for _ in 0..128 { if inb(COM1 + 5) & 0x20 != 0 { break; } } outb(COM1 + 0, c as u8); -} \ No newline at end of file +} + +fn uartgetc() -> i32 { + if !UART_PRESENT.load(Ordering::Relaxed) { + return -1; + } + if (inb(COM1 + 5) & 0x01) == 0 { + return -1; + } + inb(COM1 + 0) as i32 +} + +pub fn uartintr() { + consoleintr(uartgetc); +} diff --git a/src/x86.rs b/src/x86.rs index ba0598c..fb341ef 100644 --- a/src/x86.rs +++ b/src/x86.rs @@ -112,6 +112,39 @@ pub fn lidt(gdt: *const [GateDesc; 256], size: usize) { } } +pub fn noop() { + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); +} + +// x86.rs +pub unsafe fn insl(port: u16, addr: *mut u32, cnt: usize) { + core::arch::asm!( + "cld", + "rep insd", + in("dx") port, + inout("edi") (addr as usize) => _, + inout("ecx") cnt => _, + options(nostack, preserves_flags), + ); +} + + + +pub unsafe fn outsl(port: u16, addr: *const u32, cnt: usize) { + let mut p = addr; + for _ in 0..cnt { + let val = core::ptr::read(p); + asm!( + "out dx, eax", + in("dx") port, + in("eax") val, + options(nomem, nostack, preserves_flags), + ); + p = p.add(1); + } +} + + /// Halts the CPU until the next interrupt occurs. /// The `hlt` instruction: /// 1. Stops instruction execution and places the processor in a HALT state diff --git a/welcome.txt b/welcome.txt new file mode 100644 index 0000000..5809c82 --- /dev/null +++ b/welcome.txt @@ -0,0 +1,7 @@ + ### + # # ###### # #### #### # # ###### ### + # # # # # # # # ## ## # ### + # # ##### # # # # # ## # ##### # + # ## # # # # # # # # # + ## ## # # # # # # # # # ### + # # ###### ###### #### #### # # ###### ###