From 514579c5863782ab85335de94fc2ca611cd560b2 Mon Sep 17 00:00:00 2001 From: ahilaan Date: Sat, 14 Feb 2026 07:51:10 +0000 Subject: [PATCH 01/40] p6: add IDE driver + buffer cache --- Makefile | 45 +++++++------ src/bio.rs | 148 +++++++++++++++++++++++++++++++++++++++++ src/buf.rs | 39 +++++++++++ src/constants.rs | 7 +- src/ide.rs | 170 +++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 30 ++++++++- src/traps.rs | 8 ++- src/x86.rs | 33 +++++++++ welcome.txt | 8 +++ 9 files changed, 459 insertions(+), 29 deletions(-) create mode 100644 src/bio.rs create mode 100644 src/buf.rs create mode 100644 src/ide.rs create mode 100644 welcome.txt diff --git a/Makefile b/Makefile index fa7b33b..9e81b2f 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ RS = src/*.rs #TOOLPREFIX = i386-elf- # Using native tools (e.g., on X86 Linux) -#TOOLPREFIX = +#TOOLPREFIX = # Try to infer the correct TOOLPREFIX if not set ifndef TOOLPREFIX @@ -53,7 +53,6 @@ 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 -# FreeBSD ld wants ``elf_i386_fbsd'' LDFLAGS += -m $(shell $(LD) -V | grep elf_i386 2>/dev/null | head -n 1) # Disable PIE when possible (for Ubuntu 16.10 toolchain) @@ -64,11 +63,19 @@ 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 +# Second disk (fs.img) with welcome text (2 sectors, like C version) +fs: fs.img + +fs.img: welcome.txt + dd if=/dev/zero of=fs.img count=2 + dd if=welcome.txt of=fs.img conv=notrunc + bootblock: bootasm.S bootmain.c $(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c $(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S @@ -78,7 +85,13 @@ bootblock: bootasm.S bootmain.c ./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 build -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec \ + --target ./targets/i686.json --release + @tdir=$$(cargo metadata --format-version=1 --no-deps | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p'); \ + lib=$$(find "$$tdir" -maxdepth 4 -type f -name 'libkernel.a' | head -n 1); \ + if [ -z "$$lib" ]; then echo "ERROR: libkernel.a not found"; exit 1; fi; \ + cp "$$lib" kernel.a + kernel: kernel.a $(OBJS) ./linkers/kernel.ld ld -m elf_i386 -T ./linkers/kernel.ld -o kernel $(OBJS) kernel.a @@ -88,25 +101,16 @@ kernel: kernel.a $(OBJS) ./linkers/kernel.ld vectors.S: vectors.pl ./vectors.pl > vectors.S -# $(LD) $(LDFLAGS) -T kernel.ld -o kernel entry.o kernel.a -b binary -# ld -m elf_i386 -T kernel.ld -o kernel entry.o kernel.a -b binary -# Prevent deletion of intermediate files, e.g. cat.o, after first build, so -# that disk image changes after first build are persistent until clean. More -# details: -# http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html .PRECIOUS: %.o - -include *.d -clean: +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 + rm -rf target # run in emulators -# try to generate a unique GDB port GDBPORT = $(shell expr `id -u` % 5000 + 25000) -# QEMU's gdb stub command line changed in 0.11 QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ then echo "-gdb tcp::$(GDBPORT)"; \ else echo "-s -p $(GDBPORT)"; fi) @@ -114,16 +118,17 @@ ifndef CPUS CPUS := 1 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) +# 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 +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 fs .gdbinit @echo "*** Now run 'gdb'." 1>&2 $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) \ No newline at end of file diff --git a/src/bio.rs b/src/bio.rs new file mode 100644 index 0000000..a9ceb74 --- /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..2c4cfb2 --- /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/constants.rs b/src/constants.rs index d06b826..b36418c 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -51,17 +51,14 @@ pub const T_SIMDERR: u32 = 19; // SIMD floating point error // processor defined exceptions or interrupt vectors pub const T_SYSCALL: u32 = 64; // system call pub const T_DEFAULT: u32 = 500; // catchall - -pub const T_IRQ0: u32 = 32; // IRQ 0 corresponds to int T_IRQ - +pub const T_IRQ0: u32 = 32; pub const IRQ_TIMER: u32 = 0; pub const IRQ_KBD: u32 = 1; 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 ------------------------------------------------------- // Processor flags diff --git a/src/ide.rs b/src/ide.rs new file mode 100644 index 0000000..4ae4ee2 --- /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..561ebcc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,9 @@ mod mp; mod proc; mod traps; mod constants; - +mod buf; +mod bio; +mod ide; use crate::traps::*; #[macro_export] @@ -35,8 +37,28 @@ fn halt() -> ! { } } +fn welcome() { + let b0 = bio::bread(1, 0); + let data0 = bio::buf_mut(b0).data; + + for &byte in data0.iter() { + if byte == 0 { break; } + console::consputc(byte as char); + } + bio::brelse(b0); + + let b1 = bio::bread(1, 1); + let count = bio::buf_mut(b1).data[0]; + + println!("\nAfter preparing fs.img, we have rebooted {} times\n", count); + + bio::buf_mut(b1).data[0] = count.wrapping_add(1); + bio::bwrite(b1); + bio::brelse(b1); +} + extern "C" { - pub static alltraps: fn(); + pub fn alltraps(); } #[no_mangle] @@ -46,9 +68,13 @@ pub extern "C" fn entryofrust() -> ! { picirq::picinit(); ioapic::ioapic_init(); uart::uartinit(); + ide::ideinit(); tvinit(); + bio::binit(); idtinit(); x86::sti(); + welcome(); + loop { x86::wfi(); } diff --git a/src/traps.rs b/src/traps.rs index 0643fcc..6899856 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -96,7 +96,7 @@ pub fn tvinit() { 0 // Descriptor privilege level. ); } - IDT.idt.set(arr); + let _ = IDT.idt.set(arr); } pub fn idtinit() { @@ -116,7 +116,6 @@ 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; @@ -132,6 +131,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", 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..3ab143e --- /dev/null +++ b/welcome.txt @@ -0,0 +1,8 @@ + ### + # # ###### # #### #### # # ###### ### + # # # # # # # # ## ## # ### + # # ##### # # # # # ## # ##### # + # ## # # # # # # # # # + ## ## # # # # # # # # # ### + # # ###### ###### #### #### # # ###### ### + From c0420075e90c028345afe28cc964b59d9bd34c61 Mon Sep 17 00:00:00 2001 From: ahilaan Date: Sat, 14 Feb 2026 08:13:05 +0000 Subject: [PATCH 02/40] p6: add IDE driver and buffer cache layer --- src/console.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/console.rs b/src/console.rs index 0f62712..12abba1 100644 --- a/src/console.rs +++ b/src/console.rs @@ -13,7 +13,7 @@ impl Write for Console { const BACKSPACE: char = '\x08'; -fn consputc(c: char) { +pub fn consputc(c: char) { if c == BACKSPACE { uartputc(BACKSPACE); uartputc(' '); From d373ec5fc0c5c64a5b2352f37427c4769a813717 Mon Sep 17 00:00:00 2001 From: Nipun Goel Date: Sat, 14 Feb 2026 15:29:13 +0530 Subject: [PATCH 03/40] mkfs implemented --- Makefile | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index fa7b33b..34b0be2 100644 --- a/Makefile +++ b/Makefile @@ -69,6 +69,12 @@ 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 *.txt + ./mkfs fs.img *.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 @@ -88,6 +94,7 @@ kernel: kernel.a $(OBJS) ./linkers/kernel.ld vectors.S: vectors.pl ./vectors.pl > vectors.S + # $(LD) $(LDFLAGS) -T kernel.ld -o kernel entry.o kernel.a -b binary # ld -m elf_i386 -T kernel.ld -o kernel entry.o kernel.a -b binary # Prevent deletion of intermediate files, e.g. cat.o, after first build, so @@ -100,7 +107,7 @@ 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 + *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img mkfs .gdbinit vectors.S rm -r target # run in emulators From 6dd333f5a310fe98cf1ea5ac3bc23d88ca2f7c4e Mon Sep 17 00:00:00 2001 From: Nipun Goel Date: Sat, 14 Feb 2026 17:21:17 +0530 Subject: [PATCH 04/40] mkfs implemented --- src/mkfs.rs | 359 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 359 insertions(+) create mode 100644 src/mkfs.rs diff --git a/src/mkfs.rs b/src/mkfs.rs new file mode 100644 index 0000000..9bfb77b --- /dev/null +++ b/src/mkfs.rs @@ -0,0 +1,359 @@ +use std::env; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::mem::size_of; +use std::path::Path; + + +// constants to be included in constants.rs under "FILE SYSTEM" section, +// declared here for now to avoid merge conflicts + +const BSIZE: usize = 512; +const FSSIZE: u32 = 10_000; +const NINODES: u32 = 200; +const LOGSIZE: u32 = 30; + +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]); + } + } + + 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); +} From 5e2d7e19d3e0e3590a0d1f32a2ad4417f5a54944 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Sun, 15 Feb 2026 17:28:24 +0000 Subject: [PATCH 05/40] Refactor traps module: centralize constants, remove duplicates, decouple ticks from IDT --- .cargo/config.toml | 6 ++++++ Makefile | 2 +- rust-toolchain.toml | 1 + src/lapic.rs | 2 +- src/traps.rs | 49 +++++++++------------------------------------ 5 files changed, 18 insertions(+), 42 deletions(-) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..0953166 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +[build] +target = "targets/i686.json" + +[unstable] +build-std = ["core"] +build-std-features = ["compiler-builtins-mem"] diff --git a/Makefile b/Makefile index fa7b33b..56e0958 100644 --- a/Makefile +++ b/Makefile @@ -78,7 +78,7 @@ bootblock: bootasm.S bootmain.c ./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 diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 5d56faf..87b5402 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,3 @@ [toolchain] channel = "nightly" +components = ["rust-src"] \ No newline at end of file diff --git a/src/lapic.rs b/src/lapic.rs index 1ce725f..14f76e6 100644 --- a/src/lapic.rs +++ b/src/lapic.rs @@ -1,6 +1,6 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::traps::{T_IRQ0, IRQ_TIMER, IRQ_SPURIOUS, IRQ_ERROR}; +use crate::constants::{T_IRQ0, IRQ_TIMER, IRQ_ERROR, IRQ_SPURIOUS}; const ID: isize = 0x0020 / 4; const VER: isize = 0x0030 / 4; diff --git a/src/traps.rs b/src/traps.rs index 0643fcc..b593740 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -3,17 +3,9 @@ use core::cell::{OnceCell, RefCell}; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; -use crate::x86::{lidt,rcr2}; +use crate::x86::{lidt, rcr2, TrapFrame}; use crate::lapic; - -const SEG_KCODE: u16 = 1; -const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate -const STS_TG32: u8 = 0xF; // 32-bit Trap Gate - -pub const T_IRQ0: u32 = 32; -pub const IRQ_TIMER: u32 = 0; -pub const IRQ_ERROR: u32 = 19; -pub const IRQ_SPURIOUS: u32 = 31; +use crate::constants::{SEG_KCODE, STS_IG32, STS_TG32, T_IRQ0, IRQ_TIMER, IRQ_ERROR, IRQ_SPURIOUS}; extern "C" { static vectors: [usize; 256]; // remove assembly. @@ -52,38 +44,15 @@ impl GateDesc { #[repr(C)] pub struct IDTOnce { pub idt: OnceCell<[GateDesc; 256]>, - pub ticks: RefCell } unsafe impl Sync for IDTOnce {} -pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new(), ticks: RefCell::new(0) }; - - -#[repr(C)] -pub struct TrapFrame { - // registers as pushed by pusha - pub edi: u32, - pub esi: u32, - pub ebp: u32, - pub oesp: u32, // useless & ignored - pub ebx: u32, - pub edx: u32, - pub ecx: u32, - pub eax: u32, - - pub trapno: u32, - - // below here defined by x86 hardware - pub err: u32, - pub eip: u32, - pub cs: u16, - pub padding5: u16, - pub eflags: u32, +pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new() }; - // below here only when crossing rings, such as from user to kernel - pub esp: u32, - pub ss: u16, - pub padding6: u16, +struct TickCounter { + ticks: RefCell } +unsafe impl Sync for TickCounter {} +static TICKS: TickCounter = TickCounter { ticks: RefCell::new(0) }; pub fn tvinit() { @@ -119,8 +88,8 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { match tf.trapno { TIMER => { - *IDT.ticks.borrow_mut() += 1; - println!("Tick {}!", IDT.ticks.borrow()); + *TICKS.ticks.borrow_mut() += 1; + println!("Tick {}!", TICKS.ticks.borrow()); lapic::lapiceoi(); } SEVEN | SPURIOUS => { From 416b5f33b59abb1d622d90292626f1d97dc23d89 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Sun, 15 Feb 2026 21:29:02 +0000 Subject: [PATCH 06/40] Updated TickCounter struct to pub --- src/traps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/traps.rs b/src/traps.rs index b593740..aa1c1a3 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -48,7 +48,7 @@ pub struct IDTOnce { unsafe impl Sync for IDTOnce {} pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new() }; -struct TickCounter { +pub struct TickCounter { ticks: RefCell } unsafe impl Sync for TickCounter {} From 706653547a7d55c04fe33e70f799a64557ca452c Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Sun, 1 Mar 2026 03:44:16 +0000 Subject: [PATCH 07/40] Cherrypicked Improvements from p3-pic --- Cargo.toml | 1 + bootasm.S | 5 +++- entry.S | 3 ++ src/ioapic.rs | 6 ++-- src/lapic.rs | 12 ++++---- src/mp.rs | 15 ++++++---- src/param.rs | 2 +- src/x86.rs | 78 +++++++++++++++++++++++++++++---------------------- 8 files changed, 72 insertions(+), 50 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2dd5beb..6c2171c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ name = "xv6" version = "0.1.0" edition = "2021" +autobins = false [lib] name = "kernel" diff --git a/bootasm.S b/bootasm.S index 81c0d52..3121176 100644 --- a/bootasm.S +++ b/bootasm.S @@ -83,4 +83,7 @@ gdt: gdtdesc: .word (gdtdesc - gdt - 1) # sizeof(gdt) - 1 - .long gdt # address gdt \ No newline at end of file + .long gdt # address gdt + +# Add .note.GNU-stack section for non-executable stack marking +.section .note.GNU-stack,"",@progbits \ No newline at end of file diff --git a/entry.S b/entry.S index a7f6755..26000a2 100644 --- a/entry.S +++ b/entry.S @@ -48,3 +48,6 @@ entry: call entryofrust .comm stack, KSTACKSIZE + +# Add .note.GNU-stack section for non-executable stack marking +.section .note.GNU-stack,"",@progbits diff --git a/src/ioapic.rs b/src/ioapic.rs index 15cf837..1196087 100644 --- a/src/ioapic.rs +++ b/src/ioapic.rs @@ -14,9 +14,9 @@ const REG_TABLE: u32 = 0x10; // Redirection table base (0x10 / 4) // Redirection table configuration bits const INT_DISABLED: u32 = 0x00010000; // Interrupt disabled -const INT_LEVEL: u32 = 0x00008000; // Level-triggered -const INT_ACTIVELOW: u32 = 0x00002000; // Active low -const INT_LOGICAL: u32 = 0x00000800; // Destination is CPU ID +// const INT_LEVEL: u32 = 0x00008000; // Unused in p3 - Level-triggered +// const INT_ACTIVELOW: u32 = 0x00002000; // Unused in p3 - Active low +// const INT_LOGICAL: u32 = 0x00000800; // Unused in p3 - Destination is CPU ID pub const T_IRQ0: u32 = 32; diff --git a/src/lapic.rs b/src/lapic.rs index 14f76e6..3a1aa17 100644 --- a/src/lapic.rs +++ b/src/lapic.rs @@ -14,14 +14,14 @@ const ESR: isize = 0x0280 / 4; const ICRLO: isize = 0x0300 / 4; const INIT: u32 = 0x00000500; -const STARTUP: u32 = 0x00000600; +// const STARTUP: u32 = 0x00000600; // Unused in p3 - for AP startup const DELIVS: u32 = 0x00001000; -const ASSERT: u32 = 0x00004000; -const DEASSERT: u32 = 0x00000000; +// const ASSERT: u32 = 0x00004000; // Unused in p3 - for IPI +// const DEASSERT: u32 = 0x00000000; // Unused in p3 - for IPI const LEVEL: u32 = 0x00008000; const BCAST: u32 = 0x00080000; -const BUSY: u32 = 0x00001000; -const FIXED: u32 = 0x00000000; +// const BUSY: u32 = 0x00001000; // Unused in p3 +// const FIXED: u32 = 0x00000000; // Unused in p3 const ICRHI: isize = 0x0310 / 4; const TIMER: isize = 0x0320 / 4; @@ -35,7 +35,7 @@ const ERROR: isize = 0x0370 / 4; const MASKED: u32 = 0x00010000; const TICR: isize = 0x0380 / 4; -const TCCR: isize = 0x0390 / 4; +// const TCCR: isize = 0x0390 / 4; // Unused in p3 - timer current count const TDCR: isize = 0x03E0 / 4; // Volatile write to LAPIC diff --git a/src/mp.rs b/src/mp.rs index 9684f51..3eecf6a 100644 --- a/src/mp.rs +++ b/src/mp.rs @@ -4,7 +4,8 @@ use crate::x86::{outb, inb}; use crate::proc::Cpu; use core::cell::OnceCell; -pub static mut IOAPICID: u8 = 0; +// Removed: replaced by MP_ONCE.ioapic_id OnceCell pattern +// pub static mut IOAPICID: u8 = 0; #[derive(Debug, Clone, Copy)] #[repr(C)] @@ -59,7 +60,7 @@ pub struct MpIoApic { } // Processor flags -pub const MPBOOT: u8 = 0x02; // This proc is the bootstrap processor +// pub const MPBOOT: u8 = 0x02; // Unused in p3 - This proc is the bootstrap processor // Table entry types pub const MPPROC: u8 = 0x00; // One per processor @@ -194,7 +195,8 @@ pub fn mpinit() { let conf = unsafe { *(mp.physaddr as *mut MpConf) }; let mut ismp = true; - MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32); + MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32) + .expect("lapic_base already initialized"); let mut p = (mp.physaddr as usize + mem::size_of::()) as *const u8; let e = (mp.physaddr as usize + conf.length as usize) as *const u8; @@ -218,8 +220,8 @@ pub fn mpinit() { MPIOAPIC => { let ioapic = p as *const MpIoApic; let ioapicid = unsafe { (*ioapic).apicno }; - MP_ONCE.ioapic_id.set(ioapicid); - // p = unsafe{ p.add(mem::size_of::()) }; + MP_ONCE.ioapic_id.set(ioapicid) + .expect("ioapic_id already initialized"); p = p.wrapping_add(mem::size_of::()); } MPBUS | MPIOINTR | MPLINTR => { @@ -236,7 +238,8 @@ pub fn mpinit() { if !ismp { panic!("Didn't find a suitable machine"); } - MP_ONCE.cpus.set(cpus); + MP_ONCE.cpus.set(cpus) + .expect("cpus array already initialized"); if mp.imcrp != 0 { // Bochs doesn't support IMCR, so this doesn't run on Bochs. diff --git a/src/param.rs b/src/param.rs index 4341329..a28e84c 100644 --- a/src/param.rs +++ b/src/param.rs @@ -1,2 +1,2 @@ -pub const KSTACKSIZE: usize = 4096; // size of per-process kernel stack +// pub const KSTACKSIZE: usize = 4096; // size of per-process kernel stack (unused in p3) pub const NCPU: usize = 8; // maximum number of CPUs diff --git a/src/x86.rs b/src/x86.rs index ba0598c..6028974 100644 --- a/src/x86.rs +++ b/src/x86.rs @@ -25,18 +25,19 @@ pub fn outb(port: u16, value: u8) { } } -pub fn inw(port: u16) -> u16 { - let result: u16; - unsafe { - asm!( - "in ax, dx", - in("dx") port, - out("ax") result, - options(nomem, nostack) - ); - result - } -} +// Unused in p3 - needed for later phases +// pub fn inw(port: u16) -> u16 { +// let result: u16; +// unsafe { +// asm!( +// "in ax, dx", +// in("dx") port, +// out("ax") result, +// options(nomem, nostack) +// ); +// result +// } +// } pub fn outw(port: u16, value: u16) { unsafe { @@ -49,27 +50,38 @@ pub fn outw(port: u16, value: u16) { } } -pub fn inl(port: u16) -> u32 { - unsafe { - let result: u32; - asm!( - "in eax, dx", - in("dx") port, - out("eax") result, - options(nomem, nostack) - ); - result - } -} - -pub fn outl(port: u16, value: u32) { - unsafe { - asm!( - "out dx, eax", - in("dx") port, - in("eax") value, - options(nomem, nostack) - ); +// Unused in p3 - needed for later phases +// pub fn inl(port: u16) -> u32 { +// unsafe { +// let result: u32; +// asm!( +// "in eax, dx", +// in("dx") port, +// out("eax") result, +// options(nomem, nostack) +// ); +// result +// } +// } + +// pub fn outl(port: u16, value: u32) { +// unsafe { +// asm!( +// "out dx, eax", +// in("dx") port, +// in("eax") value, +// options(nomem, nostack) +// ); +// } +// } + +/// Disable interrupts +/// +/// Clear the interrupt flag (IF) in EFLAGS to prevent the processor +/// from responding to maskable hardware interrupts. +pub fn cli() { + unsafe { + asm!("cli", options(nomem, nostack)); } } From cf5aed903799431961cbbbf11cf5307e99b922b8 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Sun, 1 Mar 2026 04:45:46 +0000 Subject: [PATCH 08/40] Refleted panic changes of p3-pic --- src/lib.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index aa34772..91ff1d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,17 @@ macro_rules! println { }); } +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + // Disable interrupts to prevent interrupt handlers from interfering + cli(); + // Print panic message with LAPIC ID to identify which CPU panicked + println!("lapicid {}:\n{:#?}", lapicid(), info); + unsafe { PANICKED = true; } + // Halt the system + loop {} +} + fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { @@ -54,8 +65,3 @@ pub extern "C" fn entryofrust() -> ! { } } -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - println!("Kernel Panic: {:?}", info); - loop {} -} \ No newline at end of file From 9d6fa5ac83825c0a031427fcf05ff0fa0eda2035 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Sun, 1 Mar 2026 04:50:41 +0000 Subject: [PATCH 09/40] Fixed Scope Issues --- src/lib.rs | 4 ++++ src/x86.rs | 49 ------------------------------------------------- 2 files changed, 4 insertions(+), 49 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 91ff1d9..7808508 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,8 @@ #![no_main] // No main function use core::panic::PanicInfo; +use crate::x86::cli; +use crate::lapic::lapicid; mod param; mod x86; @@ -27,6 +29,8 @@ macro_rules! println { }); } +static mut PANICKED: bool = false; + #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Disable interrupts to prevent interrupt handlers from interfering diff --git a/src/x86.rs b/src/x86.rs index 6028974..3aab64b 100644 --- a/src/x86.rs +++ b/src/x86.rs @@ -25,20 +25,6 @@ pub fn outb(port: u16, value: u8) { } } -// Unused in p3 - needed for later phases -// pub fn inw(port: u16) -> u16 { -// let result: u16; -// unsafe { -// asm!( -// "in ax, dx", -// in("dx") port, -// out("ax") result, -// options(nomem, nostack) -// ); -// result -// } -// } - pub fn outw(port: u16, value: u16) { unsafe { asm!( @@ -50,41 +36,6 @@ pub fn outw(port: u16, value: u16) { } } -// Unused in p3 - needed for later phases -// pub fn inl(port: u16) -> u32 { -// unsafe { -// let result: u32; -// asm!( -// "in eax, dx", -// in("dx") port, -// out("eax") result, -// options(nomem, nostack) -// ); -// result -// } -// } - -// pub fn outl(port: u16, value: u32) { -// unsafe { -// asm!( -// "out dx, eax", -// in("dx") port, -// in("eax") value, -// options(nomem, nostack) -// ); -// } -// } - -/// Disable interrupts -/// -/// Clear the interrupt flag (IF) in EFLAGS to prevent the processor -/// from responding to maskable hardware interrupts. -pub fn cli() { - unsafe { - asm!("cli", options(nomem, nostack)); - } -} - pub fn readeflags() -> u32 { unsafe { let eflags: u32; From 09daea8a4796827f61bd4dc09e0f1b71b8931e02 Mon Sep 17 00:00:00 2001 From: Arinjay Singhal <137890548+ArinjaySinghal19@users.noreply.github.com> Date: Mon, 16 Feb 2026 17:19:34 +0530 Subject: [PATCH 10/40] p5: add UART interrupt and console input support --- Makefile | 31 +++++++--------------- src/console.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++----- src/lapic.rs | 4 +-- src/lib.rs | 2 +- src/traps.rs | 67 +++++++++++++++++++++++------------------------ src/uart.rs | 31 +++++++++++++++++++--- 6 files changed, 138 insertions(+), 68 deletions(-) diff --git a/Makefile b/Makefile index 9e81b2f..0d99f98 100644 --- a/Makefile +++ b/Makefile @@ -16,18 +16,9 @@ TOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/d 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) + 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; \ @@ -35,14 +26,7 @@ QEMU = $(shell if which qemu > /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) + else echo "*** Error: Couldn't find QEMU." 1>&2; exit 1; fi) endif CC = $(TOOLPREFIX)gcc @@ -50,12 +34,13 @@ 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 @@ -94,7 +79,7 @@ kernel.a: $(RS) 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 @@ -104,6 +89,7 @@ vectors.S: vectors.pl .PRECIOUS: %.o -include *.d +clean: clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img .gdbinit vectors.S @@ -114,8 +100,9 @@ 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 +CPUS := 1 endif # Attach fs.img as disk1 (index=1), like the C version @@ -131,4 +118,4 @@ qemu: xv6.img fs.img qemu-gdb: xv6.img fs .gdbinit @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/console.rs b/src/console.rs index 12abba1..25bde2f 100644 --- a/src/console.rs +++ b/src/console.rs @@ -5,20 +5,79 @@ pub struct Console {} impl Write for Console { fn write_str(&mut self, s: &str) -> Result { for c in s.chars() { - consputc(c); + consputc(c as i32); } Ok(()) } } -const BACKSPACE: char = '\x08'; +const BACKSPACE: i32 = 0x100; +const INPUT_BUF: usize = 128; +const CTRL_D: i32 = C('D'); -pub fn consputc(c: char) { +#[allow(non_snake_case)] +const fn C(c: char) -> i32 { + (c as i32) - ('@' as i32) +} + +#[derive(Clone, Copy)] +struct Input { + buf: [u8; INPUT_BUF], + r: usize, + w: usize, + e: usize, +} + +static mut INPUT: Input = Input { + buf: [0; INPUT_BUF], + r: 0, + w: 0, + e: 0, +}; + +fn consputc(c: i32) { if c == BACKSPACE { - uartputc(BACKSPACE); - uartputc(' '); - uartputc(BACKSPACE); + uartputc('\x08' as i32); + uartputc(' ' as i32); + uartputc('\x08' as i32); } else { uartputc(c); } +} + +pub fn consoleintr(getc: fn() -> i32) { + loop { + let c = getc(); + if c < 0 { + break; + } + + let input = unsafe { &mut INPUT }; + + match c { + x if x == C('U') => { + while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { + input.e -= 1; + consputc(BACKSPACE); + } + } + x if x == C('H') || x == 0x7f => { + if input.e != input.w { + input.e -= 1; + consputc(BACKSPACE); + } + } + _ => { + if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + input.buf[input.e % INPUT_BUF] = c as u8; + input.e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { + input.w = input.e; + } + } + } + } + } } \ No newline at end of file diff --git a/src/lapic.rs b/src/lapic.rs index 1ce725f..1bafa51 100644 --- a/src/lapic.rs +++ b/src/lapic.rs @@ -1,6 +1,6 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::traps::{T_IRQ0, IRQ_TIMER, IRQ_SPURIOUS, IRQ_ERROR}; +use crate::constants::{IRQ_ERROR, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; const ID: isize = 0x0020 / 4; const VER: isize = 0x0030 / 4; @@ -70,7 +70,7 @@ pub fn lapicinit() { // TICR would be calibrated using an external time source. lapicw(TDCR, X1); lapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); - lapicw(TICR, 1000000000); + lapicw(TICR, 10000000); // Disable logical interrupt lines. diff --git a/src/lib.rs b/src/lib.rs index 561ebcc..fa1cc42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,5 +83,5 @@ pub extern "C" fn entryofrust() -> ! { #[panic_handler] fn panic(info: &PanicInfo) -> ! { println!("Kernel Panic: {:?}", info); - loop {} + halt() } \ No newline at end of file diff --git a/src/traps.rs b/src/traps.rs index 6899856..4010605 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,27 +1,25 @@ use modular_bitfield::prelude::*; -use core::cell::{OnceCell, RefCell}; +use core::cell::OnceCell; +use core::sync::atomic::{AtomicU32, Ordering}; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt,rcr2}; use crate::lapic; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::uart::uartintr; const SEG_KCODE: u16 = 1; const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate const STS_TG32: u8 = 0xF; // 32-bit Trap Gate -pub const T_IRQ0: u32 = 32; -pub const IRQ_TIMER: u32 = 0; -pub const IRQ_ERROR: u32 = 19; -pub const IRQ_SPURIOUS: u32 = 31; - extern "C" { - static vectors: [usize; 256]; // remove assembly. + static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } #[bitfield] #[repr(C, packed)] -#[derive(Clone, Copy, Default)] // debug can be removed ? do we need to ? +#[derive(Clone, Copy, Default)] pub struct GateDesc { off_15_0: B16, // low 16 bits of offset in segment cs: B16, // code segment selector @@ -40,7 +38,7 @@ impl GateDesc { self.set_args(0); self.set_rsv1(0); let typ = if is_trap { STS_TG32 } else { STS_IG32 }; - self.set_r_type(typ); // for an interrupt gate, for example. + self.set_r_type(typ); self.set_s(0); self.set_dpl(dpl); self.set_p(1); @@ -49,13 +47,8 @@ impl GateDesc { } -#[repr(C)] -pub struct IDTOnce { - pub idt: OnceCell<[GateDesc; 256]>, - pub ticks: RefCell -} -unsafe impl Sync for IDTOnce {} -pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new(), ticks: RefCell::new(0) }; +static mut IDT: OnceCell<[GateDesc; 256]> = OnceCell::new(); +pub static TICKS: AtomicU32 = AtomicU32::new(0); #[repr(C)] @@ -90,17 +83,20 @@ pub fn tvinit() { let mut arr = [GateDesc::default(); 256]; for i in 0..256 { arr[i].set_gate( - false, // Use an interrupt gate. - SEG_KCODE << 3, // Code segment selector (shifted as in the C code). - unsafe { vectors[i] }, // Offset from the external vector table. - 0 // Descriptor privilege level. + false, + SEG_KCODE << 3, + unsafe { vectors[i] }, + 0 ); } - let _ = IDT.idt.set(arr); + unsafe { + let _ = IDT.set(arr); + } } pub fn idtinit() { - lidt(IDT.idt.get().unwrap() , core::mem::size_of::<[GateDesc; 256]>() as usize); + let idt = unsafe { IDT.get().expect("IDT not initialized") }; + lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } @@ -117,18 +113,21 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { 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()); - lapic::lapiceoi(); - } - SEVEN | SPURIOUS => { - println!( - "cpu{}: spurious interrupt at {}:{}\n", - cpuid() , - tf.cs, - tf.eip - ); + TIMER => { + TICKS.fetch_add(1, Ordering::Relaxed); + lapic::lapiceoi(); + } + x if x == T_IRQ0 + IRQ_COM1 => { + uartintr(); + lapiceoi(); + } + SEVEN | SPURIOUS => { + println!( + "cpu{}: spurious interrupt at {:x}:{:x}\n", + cpuid(), + tf.cs, + tf.eip + ); lapiceoi(); } crate::constants::IDE_TRAP => { diff --git a/src/uart.rs b/src/uart.rs index 9888088..aaf3137 100644 --- a/src/uart.rs +++ b/src/uart.rs @@ -1,7 +1,13 @@ -use crate::x86::{outb, inb}; +use crate::console::consoleintr; +use crate::x86::{inb, outb}; 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_READY: AtomicBool = AtomicBool::new(false); + pub fn uartinit() { // Turn off the FIFO. outb(COM1 + 2, 0); @@ -19,6 +25,7 @@ pub fn uartinit() { if inb(COM1 + 5) == 0xFF { return; } + UART_READY.store(true, Ordering::SeqCst); // Acknowledge pre-existing interrupt conditions; // enable interrupts. @@ -28,15 +35,33 @@ pub fn uartinit() { // Announce that the UART is active. for p in "xv6...\n".chars() { - uartputc(p); + uartputc(p as i32); } } -pub fn uartputc(c: char) { +pub fn uartputc(c: i32) { + if !UART_READY.load(Ordering::SeqCst) { + return; + } + for _ in 0..128 { if inb(COM1 + 5) & 0x20 != 0 { break; } } outb(COM1 + 0, c as u8); +} + +fn uartgetc() -> i32 { + if !UART_READY.load(Ordering::SeqCst) { + return -1; + } + if (inb(COM1 + 5) & 0x01) == 0 { + return -1; + } + inb(COM1) as i32 +} + +pub fn uartintr() { + consoleintr(uartgetc); } \ No newline at end of file From c31ec4ab8fd5df8cec9c1fd7e7421024377590af Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 14:54:32 +0000 Subject: [PATCH 11/40] Updated console::consputc function call API --- src/console.rs | 2 +- src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/console.rs b/src/console.rs index 25bde2f..59f186a 100644 --- a/src/console.rs +++ b/src/console.rs @@ -35,7 +35,7 @@ static mut INPUT: Input = Input { e: 0, }; -fn consputc(c: i32) { +pub fn consputc(c: i32) { if c == BACKSPACE { uartputc('\x08' as i32); uartputc(' ' as i32); diff --git a/src/lib.rs b/src/lib.rs index fa1cc42..4421108 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,7 +43,7 @@ fn welcome() { for &byte in data0.iter() { if byte == 0 { break; } - console::consputc(byte as char); + console::consputc(byte as i32); } bio::brelse(b0); From e21d58fc74ec01570ce9899ebe03bf4a636fad56 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 04:28:43 +0000 Subject: [PATCH 12/40] Updated project level config.toml --- .cargo/config.toml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..0953166 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +[build] +target = "targets/i686.json" + +[unstable] +build-std = ["core"] +build-std-features = ["compiler-builtins-mem"] From 09318fbf1c0eb5627c7e452d5a8f91142a5d5601 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 04:47:41 +0000 Subject: [PATCH 13/40] Accumulated older changes --- Cargo.toml | 1 + src/lib.rs | 13 +++++++++++-- src/mp.rs | 12 ++++++++---- src/traps.rs | 6 +----- 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2dd5beb..6c2171c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ name = "xv6" version = "0.1.0" edition = "2021" +autobins = false [lib] name = "kernel" diff --git a/src/lib.rs b/src/lib.rs index 4421108..b8c2f0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,8 @@ #![no_main] // No main function use core::panic::PanicInfo; +use crate::x86::cli; +use crate::lapic::lapicid; mod param; mod x86; @@ -80,8 +82,15 @@ pub extern "C" fn entryofrust() -> ! { } } +static mut PANICKED: bool = false; + #[panic_handler] fn panic(info: &PanicInfo) -> ! { - println!("Kernel Panic: {:?}", info); - halt() + // Disable interrupts to prevent interrupt handlers from interfering + cli(); + // Print panic message with LAPIC ID to identify which CPU panicked + println!("lapicid {}:\n{:#?}", lapicid(), info); + unsafe { PANICKED = true; } + // Halt the system + loop {} } \ No newline at end of file diff --git a/src/mp.rs b/src/mp.rs index 9684f51..f291c43 100644 --- a/src/mp.rs +++ b/src/mp.rs @@ -4,7 +4,8 @@ use crate::x86::{outb, inb}; use crate::proc::Cpu; use core::cell::OnceCell; -pub static mut IOAPICID: u8 = 0; +// Removed: replaced by MP_ONCE.ioapic_id OnceCell pattern +// pub static mut IOAPICID: u8 = 0; #[derive(Debug, Clone, Copy)] #[repr(C)] @@ -194,7 +195,8 @@ pub fn mpinit() { let conf = unsafe { *(mp.physaddr as *mut MpConf) }; let mut ismp = true; - MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32); + MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32) + .expect("lapic_base already initialized"); let mut p = (mp.physaddr as usize + mem::size_of::()) as *const u8; let e = (mp.physaddr as usize + conf.length as usize) as *const u8; @@ -218,7 +220,8 @@ pub fn mpinit() { MPIOAPIC => { let ioapic = p as *const MpIoApic; let ioapicid = unsafe { (*ioapic).apicno }; - MP_ONCE.ioapic_id.set(ioapicid); + MP_ONCE.ioapic_id.set(ioapicid) + .expect("ioapic_id already initialized"); // p = unsafe{ p.add(mem::size_of::()) }; p = p.wrapping_add(mem::size_of::()); } @@ -236,7 +239,8 @@ pub fn mpinit() { if !ismp { panic!("Didn't find a suitable machine"); } - MP_ONCE.cpus.set(cpus); + MP_ONCE.cpus.set(cpus) + .expect("cpus array already initialized"); if mp.imcrp != 0 { // Bochs doesn't support IMCR, so this doesn't run on Bochs. diff --git a/src/traps.rs b/src/traps.rs index 4010605..4974746 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -6,13 +6,9 @@ use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt,rcr2}; use crate::lapic; -use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0, SEG_KCODE, STS_IG32, STS_TG32}; use crate::uart::uartintr; -const SEG_KCODE: u16 = 1; -const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate -const STS_TG32: u8 = 0xF; // 32-bit Trap Gate - extern "C" { static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } From b6642c8302b606bf2de8ab8983d03c107cf99b18 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 05:15:11 +0000 Subject: [PATCH 14/40] Fixed static mutable warnings --- src/console.rs | 43 ++++++++++++++++++++++--------------------- src/ioapic.rs | 4 ++-- src/lib.rs | 2 ++ src/proc.rs | 2 +- src/traps.rs | 5 +++-- 5 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/console.rs b/src/console.rs index 59f186a..61f0aa3 100644 --- a/src/console.rs +++ b/src/console.rs @@ -52,29 +52,30 @@ pub fn consoleintr(getc: fn() -> i32) { break; } - let input = unsafe { &mut INPUT }; - - match c { - x if x == C('U') => { - while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { - input.e -= 1; - consputc(BACKSPACE); + unsafe { + let input = &raw mut INPUT; + match c { + x if x == C('U') => { + while (*input).e != (*input).w && (*input).buf[((*input).e - 1) % INPUT_BUF] != b'\n' { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - x if x == C('H') || x == 0x7f => { - if input.e != input.w { - input.e -= 1; - consputc(BACKSPACE); + x if x == C('H') || x == 0x7f => { + if (*input).e != (*input).w { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - _ => { - if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { - let c = if c == '\r' as i32 { '\n' as i32 } else { c }; - input.buf[input.e % INPUT_BUF] = c as u8; - input.e += 1; - consputc(c); - if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { - input.w = input.e; + _ => { + if c != 0 && (*input).e.wrapping_sub((*input).r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + (*input).buf[(*input).e % INPUT_BUF] = c as u8; + (*input).e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || (*input).e == (*input).r + INPUT_BUF { + (*input).w = (*input).e; + } } } } diff --git a/src/ioapic.rs b/src/ioapic.rs index 15cf837..979cfd0 100644 --- a/src/ioapic.rs +++ b/src/ioapic.rs @@ -1,7 +1,7 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::console::Console; -use core::fmt::Write; +// use crate::console::Console; +// use core::fmt::Write; use crate::println; // I/O APIC default physical address diff --git a/src/lib.rs b/src/lib.rs index b8c2f0a..9727da0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ #![no_std] // No standard library #![no_main] // No main function +#![allow(dead_code)] use core::panic::PanicInfo; use crate::x86::cli; @@ -59,6 +60,7 @@ fn welcome() { bio::brelse(b1); } +// alltraps is an assembly label not a static function pointer in Rust extern "C" { pub fn alltraps(); } diff --git a/src/proc.rs b/src/proc.rs index 279364c..713ad58 100644 --- a/src/proc.rs +++ b/src/proc.rs @@ -1,5 +1,5 @@ use crate::mp::MP_ONCE; // Import the MP_ONCE static from mp.rs -use core::ptr; +// use core::ptr; use crate::x86::readeflags; use crate::constants::{FL_IF,NCPU}; use crate::lapic; diff --git a/src/traps.rs b/src/traps.rs index 4974746..4806d32 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,6 +1,7 @@ use modular_bitfield::prelude::*; use core::cell::OnceCell; use core::sync::atomic::{AtomicU32, Ordering}; +use core::ptr::addr_of_mut; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; @@ -86,12 +87,12 @@ pub fn tvinit() { ); } unsafe { - let _ = IDT.set(arr); + let _ = (*addr_of_mut!(IDT)).set(arr); } } pub fn idtinit() { - let idt = unsafe { IDT.get().expect("IDT not initialized") }; + let idt = unsafe { (*addr_of_mut!(IDT)).get().expect("IDT not initialized") }; lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } From ac785d11d0bc5d2f932c614d900e893dbf31a8b4 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 16:25:12 +0000 Subject: [PATCH 15/40] p6: Fixed iderw to use interrupt-driven design --- Makefile | 1 - src/ide.rs | 40 +++++++++++++++++++++++++--------------- src/lib.rs | 4 ++-- src/x86.rs | 27 ++++++++++++++------------- 4 files changed, 41 insertions(+), 31 deletions(-) diff --git a/Makefile b/Makefile index 0d99f98..6e9abeb 100644 --- a/Makefile +++ b/Makefile @@ -89,7 +89,6 @@ vectors.S: vectors.pl .PRECIOUS: %.o -include *.d -clean: clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img .gdbinit vectors.S diff --git a/src/ide.rs b/src/ide.rs index 4ae4ee2..180b78e 100644 --- a/src/ide.rs +++ b/src/ide.rs @@ -133,7 +133,9 @@ pub fn ideintr() { } } -// ide.rs +// Sync buf with disk. +// If B_DIRTY is set, write buf to disk, clear B_DIRTY, set B_VALID. +// Else if B_VALID is not set, read buf from disk, set B_VALID. pub fn iderw(idx: usize) { let b = crate::bio::buf_mut(idx); @@ -148,23 +150,31 @@ pub fn iderw(idx: usize) { } } - // PURE POLLING: issue the command directly (no IDEQUEUE). - idestart(idx); - - // Wait for completion. - if idewait(true) < 0 { - panic!("iderw: ide error"); + // Append b to idequeue. + b.qnext = None; + unsafe { + let mut pp: *mut Option = &raw mut IDEQUEUE; + while let Some(next_idx) = *pp { + pp = &raw mut crate::bio::buf_mut(next_idx).qnext; + } + *pp = Some(idx); } - // 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); + // Start disk if necessary. + unsafe { + if IDEQUEUE == Some(idx) { + idestart(idx); } } - // 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); + // Wait for request to finish. + // The interrupt handler will set B_VALID when done. + loop { + let flags = b.flags.load(Ordering::Acquire); + if (flags & (B_VALID | B_DIRTY)) == B_VALID { + break; + } + // Force compiler to re-read b->flags which is modified by ideintr() + x86::noop(); + } } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 9727da0..21209db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,8 +35,8 @@ macro_rules! println { fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { - x86::outw(0x604, 0x2000); - x86::outw(0xB004, 0x2000); + x86::outw(0x602, 0x2000); // QEMU isa-debug-exit device + x86::outw(0xB002, 0x2000); // VirtualBox shutdown port } } diff --git a/src/x86.rs b/src/x86.rs index fb341ef..ba0db57 100644 --- a/src/x86.rs +++ b/src/x86.rs @@ -129,22 +129,23 @@ pub unsafe fn insl(port: u16, addr: *mut u32, cnt: usize) { } - +// Output string of dwords to port using rep outsd instruction. +// Matches the C implementation: outsl(port, addr, cnt) +// Note: ESI must be saved/restored as LLVM restricts its use in 32-bit mode 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); - } + let addr_val = addr as u32; + core::arch::asm!( + "push esi", + "mov esi, {addr}", + "cld", + "rep outsd", + "pop esi", + addr = in(reg) addr_val, + in("dx") port, + inout("ecx") cnt => _, + ); } - /// Halts the CPU until the next interrupt occurs. /// The `hlt` instruction: /// 1. Stops instruction execution and places the processor in a HALT state From 4feb5666572917fb35f241ff091d6b45c9c9a5e2 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 16:39:04 +0000 Subject: [PATCH 16/40] Updated port exit status --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 21209db..b714a15 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,8 +35,8 @@ macro_rules! println { fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { - x86::outw(0x602, 0x2000); // QEMU isa-debug-exit device - x86::outw(0xB002, 0x2000); // VirtualBox shutdown port + x86::outw(0x604, 0x2000); // QEMU isa-debug-exit device + x86::outw(0xB004, 0x2000); // VirtualBox shutdown port } } From d2aa22a35799ef9f7386e047fa3596fb3a7545e0 Mon Sep 17 00:00:00 2001 From: Naman Garg Date: Mon, 9 Feb 2026 17:33:54 +0530 Subject: [PATCH 17/40] Initial commit From b2ebc350d2249378780137bb1ca9d80c9326a085 Mon Sep 17 00:00:00 2001 From: ahilaan Date: Sat, 14 Feb 2026 07:51:10 +0000 Subject: [PATCH 18/40] p6: add IDE driver + buffer cache --- Makefile | 30 +++++---- src/bio.rs | 148 +++++++++++++++++++++++++++++++++++++++++ src/buf.rs | 39 +++++++++++ src/constants.rs | 7 +- src/ide.rs | 170 +++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 30 ++++++++- src/traps.rs | 8 ++- src/x86.rs | 33 +++++++++ welcome.txt | 8 +++ 9 files changed, 451 insertions(+), 22 deletions(-) create mode 100644 src/bio.rs create mode 100644 src/buf.rs create mode 100644 src/ide.rs create mode 100644 welcome.txt diff --git a/Makefile b/Makefile index 34b0be2..61d8093 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ RS = src/*.rs #TOOLPREFIX = i386-elf- # Using native tools (e.g., on X86 Linux) -#TOOLPREFIX = +#TOOLPREFIX = # Try to infer the correct TOOLPREFIX if not set ifndef TOOLPREFIX @@ -53,7 +53,6 @@ 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 -# FreeBSD ld wants ``elf_i386_fbsd'' LDFLAGS += -m $(shell $(LD) -V | grep elf_i386 2>/dev/null | head -n 1) # Disable PIE when possible (for Ubuntu 16.10 toolchain) @@ -64,6 +63,7 @@ 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 @@ -84,7 +84,13 @@ bootblock: bootasm.S bootmain.c ./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 build -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec \ + --target ./targets/i686.json --release + @tdir=$$(cargo metadata --format-version=1 --no-deps | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p'); \ + lib=$$(find "$$tdir" -maxdepth 4 -type f -name 'libkernel.a' | head -n 1); \ + if [ -z "$$lib" ]; then echo "ERROR: libkernel.a not found"; exit 1; fi; \ + cp "$$lib" kernel.a + kernel: kernel.a $(OBJS) ./linkers/kernel.ld ld -m elf_i386 -T ./linkers/kernel.ld -o kernel $(OBJS) kernel.a @@ -102,18 +108,15 @@ vectors.S: vectors.pl # details: # http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html .PRECIOUS: %.o - -include *.d -clean: +clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img mkfs .gdbinit vectors.S - rm -r target + rm -rf target # run in emulators -# try to generate a unique GDB port GDBPORT = $(shell expr `id -u` % 5000 + 25000) -# QEMU's gdb stub command line changed in 0.11 QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ then echo "-gdb tcp::$(GDBPORT)"; \ else echo "-s -p $(GDBPORT)"; fi) @@ -121,16 +124,17 @@ ifndef CPUS CPUS := 1 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) +# 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 +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 fs .gdbinit @echo "*** Now run 'gdb'." 1>&2 $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) \ No newline at end of file diff --git a/src/bio.rs b/src/bio.rs new file mode 100644 index 0000000..a9ceb74 --- /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..2c4cfb2 --- /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/constants.rs b/src/constants.rs index d06b826..b36418c 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -51,17 +51,14 @@ pub const T_SIMDERR: u32 = 19; // SIMD floating point error // processor defined exceptions or interrupt vectors pub const T_SYSCALL: u32 = 64; // system call pub const T_DEFAULT: u32 = 500; // catchall - -pub const T_IRQ0: u32 = 32; // IRQ 0 corresponds to int T_IRQ - +pub const T_IRQ0: u32 = 32; pub const IRQ_TIMER: u32 = 0; pub const IRQ_KBD: u32 = 1; 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 ------------------------------------------------------- // Processor flags diff --git a/src/ide.rs b/src/ide.rs new file mode 100644 index 0000000..4ae4ee2 --- /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..561ebcc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,9 @@ mod mp; mod proc; mod traps; mod constants; - +mod buf; +mod bio; +mod ide; use crate::traps::*; #[macro_export] @@ -35,8 +37,28 @@ fn halt() -> ! { } } +fn welcome() { + let b0 = bio::bread(1, 0); + let data0 = bio::buf_mut(b0).data; + + for &byte in data0.iter() { + if byte == 0 { break; } + console::consputc(byte as char); + } + bio::brelse(b0); + + let b1 = bio::bread(1, 1); + let count = bio::buf_mut(b1).data[0]; + + println!("\nAfter preparing fs.img, we have rebooted {} times\n", count); + + bio::buf_mut(b1).data[0] = count.wrapping_add(1); + bio::bwrite(b1); + bio::brelse(b1); +} + extern "C" { - pub static alltraps: fn(); + pub fn alltraps(); } #[no_mangle] @@ -46,9 +68,13 @@ pub extern "C" fn entryofrust() -> ! { picirq::picinit(); ioapic::ioapic_init(); uart::uartinit(); + ide::ideinit(); tvinit(); + bio::binit(); idtinit(); x86::sti(); + welcome(); + loop { x86::wfi(); } diff --git a/src/traps.rs b/src/traps.rs index 0643fcc..6899856 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -96,7 +96,7 @@ pub fn tvinit() { 0 // Descriptor privilege level. ); } - IDT.idt.set(arr); + let _ = IDT.idt.set(arr); } pub fn idtinit() { @@ -116,7 +116,6 @@ 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; @@ -132,6 +131,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", 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..3ab143e --- /dev/null +++ b/welcome.txt @@ -0,0 +1,8 @@ + ### + # # ###### # #### #### # # ###### ### + # # # # # # # # ## ## # ### + # # ##### # # # # # ## # ##### # + # ## # # # # # # # # # + ## ## # # # # # # # # # ### + # # ###### ###### #### #### # # ###### ### + From e32b47b11454c8663b04febff11fabf701992b20 Mon Sep 17 00:00:00 2001 From: ahilaan Date: Sat, 14 Feb 2026 08:13:05 +0000 Subject: [PATCH 19/40] p6: add IDE driver and buffer cache layer --- src/console.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/console.rs b/src/console.rs index 0f62712..12abba1 100644 --- a/src/console.rs +++ b/src/console.rs @@ -13,7 +13,7 @@ impl Write for Console { const BACKSPACE: char = '\x08'; -fn consputc(c: char) { +pub fn consputc(c: char) { if c == BACKSPACE { uartputc(BACKSPACE); uartputc(' '); From 4ced3ca36c0d01df4155f6750be54be0655825d5 Mon Sep 17 00:00:00 2001 From: Nipun Goel Date: Sat, 14 Feb 2026 15:29:13 +0530 Subject: [PATCH 20/40] mkfs implemented --- Makefile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Makefile b/Makefile index 61d8093..54a83fa 100644 --- a/Makefile +++ b/Makefile @@ -75,6 +75,12 @@ mkfs: src/mkfs.rs fs.img: mkfs *.txt ./mkfs fs.img *.txt +mkfs: src/mkfs.rs + rustc -W warnings -o mkfs src/mkfs.rs + +fs.img: mkfs *.txt + ./mkfs fs.img *.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 From a0f29fbcfc2d47fbfb570309d170ba2950bd4162 Mon Sep 17 00:00:00 2001 From: Nipun Goel Date: Sat, 14 Feb 2026 17:21:17 +0530 Subject: [PATCH 21/40] mkfs implemented From 6cf347606051955f0896a203e55fef19b9fb5e24 Mon Sep 17 00:00:00 2001 From: Arinjay Singhal <137890548+ArinjaySinghal19@users.noreply.github.com> Date: Mon, 16 Feb 2026 17:19:34 +0530 Subject: [PATCH 22/40] p5: add UART interrupt and console input support --- Makefile | 31 +++++++--------------- src/console.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++----- src/lapic.rs | 4 +-- src/lib.rs | 2 +- src/traps.rs | 67 +++++++++++++++++++++++------------------------ src/uart.rs | 31 +++++++++++++++++++--- 6 files changed, 138 insertions(+), 68 deletions(-) diff --git a/Makefile b/Makefile index 54a83fa..884fb32 100644 --- a/Makefile +++ b/Makefile @@ -16,18 +16,9 @@ TOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/d 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) + 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; \ @@ -35,14 +26,7 @@ QEMU = $(shell if which qemu > /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) + else echo "*** Error: Couldn't find QEMU." 1>&2; exit 1; fi) endif CC = $(TOOLPREFIX)gcc @@ -50,12 +34,13 @@ 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 @@ -99,7 +84,7 @@ kernel.a: $(RS) 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 @@ -116,6 +101,7 @@ vectors.S: vectors.pl .PRECIOUS: %.o -include *.d +clean: clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img mkfs .gdbinit vectors.S @@ -126,8 +112,9 @@ 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 +CPUS := 1 endif # Attach fs.img as disk1 (index=1), like the C version @@ -143,4 +130,4 @@ qemu: xv6.img fs.img qemu-gdb: xv6.img fs .gdbinit @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/console.rs b/src/console.rs index 12abba1..25bde2f 100644 --- a/src/console.rs +++ b/src/console.rs @@ -5,20 +5,79 @@ pub struct Console {} impl Write for Console { fn write_str(&mut self, s: &str) -> Result { for c in s.chars() { - consputc(c); + consputc(c as i32); } Ok(()) } } -const BACKSPACE: char = '\x08'; +const BACKSPACE: i32 = 0x100; +const INPUT_BUF: usize = 128; +const CTRL_D: i32 = C('D'); -pub fn consputc(c: char) { +#[allow(non_snake_case)] +const fn C(c: char) -> i32 { + (c as i32) - ('@' as i32) +} + +#[derive(Clone, Copy)] +struct Input { + buf: [u8; INPUT_BUF], + r: usize, + w: usize, + e: usize, +} + +static mut INPUT: Input = Input { + buf: [0; INPUT_BUF], + r: 0, + w: 0, + e: 0, +}; + +fn consputc(c: i32) { if c == BACKSPACE { - uartputc(BACKSPACE); - uartputc(' '); - uartputc(BACKSPACE); + uartputc('\x08' as i32); + uartputc(' ' as i32); + uartputc('\x08' as i32); } else { uartputc(c); } +} + +pub fn consoleintr(getc: fn() -> i32) { + loop { + let c = getc(); + if c < 0 { + break; + } + + let input = unsafe { &mut INPUT }; + + match c { + x if x == C('U') => { + while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { + input.e -= 1; + consputc(BACKSPACE); + } + } + x if x == C('H') || x == 0x7f => { + if input.e != input.w { + input.e -= 1; + consputc(BACKSPACE); + } + } + _ => { + if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + input.buf[input.e % INPUT_BUF] = c as u8; + input.e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { + input.w = input.e; + } + } + } + } + } } \ No newline at end of file diff --git a/src/lapic.rs b/src/lapic.rs index 1ce725f..1bafa51 100644 --- a/src/lapic.rs +++ b/src/lapic.rs @@ -1,6 +1,6 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::traps::{T_IRQ0, IRQ_TIMER, IRQ_SPURIOUS, IRQ_ERROR}; +use crate::constants::{IRQ_ERROR, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; const ID: isize = 0x0020 / 4; const VER: isize = 0x0030 / 4; @@ -70,7 +70,7 @@ pub fn lapicinit() { // TICR would be calibrated using an external time source. lapicw(TDCR, X1); lapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); - lapicw(TICR, 1000000000); + lapicw(TICR, 10000000); // Disable logical interrupt lines. diff --git a/src/lib.rs b/src/lib.rs index 561ebcc..fa1cc42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,5 +83,5 @@ pub extern "C" fn entryofrust() -> ! { #[panic_handler] fn panic(info: &PanicInfo) -> ! { println!("Kernel Panic: {:?}", info); - loop {} + halt() } \ No newline at end of file diff --git a/src/traps.rs b/src/traps.rs index 6899856..4010605 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,27 +1,25 @@ use modular_bitfield::prelude::*; -use core::cell::{OnceCell, RefCell}; +use core::cell::OnceCell; +use core::sync::atomic::{AtomicU32, Ordering}; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt,rcr2}; use crate::lapic; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::uart::uartintr; const SEG_KCODE: u16 = 1; const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate const STS_TG32: u8 = 0xF; // 32-bit Trap Gate -pub const T_IRQ0: u32 = 32; -pub const IRQ_TIMER: u32 = 0; -pub const IRQ_ERROR: u32 = 19; -pub const IRQ_SPURIOUS: u32 = 31; - extern "C" { - static vectors: [usize; 256]; // remove assembly. + static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } #[bitfield] #[repr(C, packed)] -#[derive(Clone, Copy, Default)] // debug can be removed ? do we need to ? +#[derive(Clone, Copy, Default)] pub struct GateDesc { off_15_0: B16, // low 16 bits of offset in segment cs: B16, // code segment selector @@ -40,7 +38,7 @@ impl GateDesc { self.set_args(0); self.set_rsv1(0); let typ = if is_trap { STS_TG32 } else { STS_IG32 }; - self.set_r_type(typ); // for an interrupt gate, for example. + self.set_r_type(typ); self.set_s(0); self.set_dpl(dpl); self.set_p(1); @@ -49,13 +47,8 @@ impl GateDesc { } -#[repr(C)] -pub struct IDTOnce { - pub idt: OnceCell<[GateDesc; 256]>, - pub ticks: RefCell -} -unsafe impl Sync for IDTOnce {} -pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new(), ticks: RefCell::new(0) }; +static mut IDT: OnceCell<[GateDesc; 256]> = OnceCell::new(); +pub static TICKS: AtomicU32 = AtomicU32::new(0); #[repr(C)] @@ -90,17 +83,20 @@ pub fn tvinit() { let mut arr = [GateDesc::default(); 256]; for i in 0..256 { arr[i].set_gate( - false, // Use an interrupt gate. - SEG_KCODE << 3, // Code segment selector (shifted as in the C code). - unsafe { vectors[i] }, // Offset from the external vector table. - 0 // Descriptor privilege level. + false, + SEG_KCODE << 3, + unsafe { vectors[i] }, + 0 ); } - let _ = IDT.idt.set(arr); + unsafe { + let _ = IDT.set(arr); + } } pub fn idtinit() { - lidt(IDT.idt.get().unwrap() , core::mem::size_of::<[GateDesc; 256]>() as usize); + let idt = unsafe { IDT.get().expect("IDT not initialized") }; + lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } @@ -117,18 +113,21 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { 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()); - lapic::lapiceoi(); - } - SEVEN | SPURIOUS => { - println!( - "cpu{}: spurious interrupt at {}:{}\n", - cpuid() , - tf.cs, - tf.eip - ); + TIMER => { + TICKS.fetch_add(1, Ordering::Relaxed); + lapic::lapiceoi(); + } + x if x == T_IRQ0 + IRQ_COM1 => { + uartintr(); + lapiceoi(); + } + SEVEN | SPURIOUS => { + println!( + "cpu{}: spurious interrupt at {:x}:{:x}\n", + cpuid(), + tf.cs, + tf.eip + ); lapiceoi(); } crate::constants::IDE_TRAP => { diff --git a/src/uart.rs b/src/uart.rs index 9888088..aaf3137 100644 --- a/src/uart.rs +++ b/src/uart.rs @@ -1,7 +1,13 @@ -use crate::x86::{outb, inb}; +use crate::console::consoleintr; +use crate::x86::{inb, outb}; 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_READY: AtomicBool = AtomicBool::new(false); + pub fn uartinit() { // Turn off the FIFO. outb(COM1 + 2, 0); @@ -19,6 +25,7 @@ pub fn uartinit() { if inb(COM1 + 5) == 0xFF { return; } + UART_READY.store(true, Ordering::SeqCst); // Acknowledge pre-existing interrupt conditions; // enable interrupts. @@ -28,15 +35,33 @@ pub fn uartinit() { // Announce that the UART is active. for p in "xv6...\n".chars() { - uartputc(p); + uartputc(p as i32); } } -pub fn uartputc(c: char) { +pub fn uartputc(c: i32) { + if !UART_READY.load(Ordering::SeqCst) { + return; + } + for _ in 0..128 { if inb(COM1 + 5) & 0x20 != 0 { break; } } outb(COM1 + 0, c as u8); +} + +fn uartgetc() -> i32 { + if !UART_READY.load(Ordering::SeqCst) { + return -1; + } + if (inb(COM1 + 5) & 0x01) == 0 { + return -1; + } + inb(COM1) as i32 +} + +pub fn uartintr() { + consoleintr(uartgetc); } \ No newline at end of file From 2f4af2ff262e628d4ef607f59e37c248bf17a0b1 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 14:54:32 +0000 Subject: [PATCH 23/40] Updated console::consputc function call API --- src/console.rs | 2 +- src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/console.rs b/src/console.rs index 25bde2f..59f186a 100644 --- a/src/console.rs +++ b/src/console.rs @@ -35,7 +35,7 @@ static mut INPUT: Input = Input { e: 0, }; -fn consputc(c: i32) { +pub fn consputc(c: i32) { if c == BACKSPACE { uartputc('\x08' as i32); uartputc(' ' as i32); diff --git a/src/lib.rs b/src/lib.rs index fa1cc42..4421108 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,7 +43,7 @@ fn welcome() { for &byte in data0.iter() { if byte == 0 { break; } - console::consputc(byte as char); + console::consputc(byte as i32); } bio::brelse(b0); From 0baee77e3171d3468d4dddd3ce89cd330a8c836f Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 04:28:43 +0000 Subject: [PATCH 24/40] Updated project level config.toml --- .cargo/config.toml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..0953166 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +[build] +target = "targets/i686.json" + +[unstable] +build-std = ["core"] +build-std-features = ["compiler-builtins-mem"] From 3302f511ac33a593eecce959c5445cf1581c1e9d Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 04:47:41 +0000 Subject: [PATCH 25/40] Accumulated older changes --- Cargo.toml | 1 + src/lib.rs | 13 +++++++++++-- src/mp.rs | 12 ++++++++---- src/traps.rs | 6 +----- 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2dd5beb..6c2171c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ name = "xv6" version = "0.1.0" edition = "2021" +autobins = false [lib] name = "kernel" diff --git a/src/lib.rs b/src/lib.rs index 4421108..b8c2f0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,8 @@ #![no_main] // No main function use core::panic::PanicInfo; +use crate::x86::cli; +use crate::lapic::lapicid; mod param; mod x86; @@ -80,8 +82,15 @@ pub extern "C" fn entryofrust() -> ! { } } +static mut PANICKED: bool = false; + #[panic_handler] fn panic(info: &PanicInfo) -> ! { - println!("Kernel Panic: {:?}", info); - halt() + // Disable interrupts to prevent interrupt handlers from interfering + cli(); + // Print panic message with LAPIC ID to identify which CPU panicked + println!("lapicid {}:\n{:#?}", lapicid(), info); + unsafe { PANICKED = true; } + // Halt the system + loop {} } \ No newline at end of file diff --git a/src/mp.rs b/src/mp.rs index 9684f51..f291c43 100644 --- a/src/mp.rs +++ b/src/mp.rs @@ -4,7 +4,8 @@ use crate::x86::{outb, inb}; use crate::proc::Cpu; use core::cell::OnceCell; -pub static mut IOAPICID: u8 = 0; +// Removed: replaced by MP_ONCE.ioapic_id OnceCell pattern +// pub static mut IOAPICID: u8 = 0; #[derive(Debug, Clone, Copy)] #[repr(C)] @@ -194,7 +195,8 @@ pub fn mpinit() { let conf = unsafe { *(mp.physaddr as *mut MpConf) }; let mut ismp = true; - MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32); + MP_ONCE.lapic_base.set(conf.lapicaddr as *mut u32) + .expect("lapic_base already initialized"); let mut p = (mp.physaddr as usize + mem::size_of::()) as *const u8; let e = (mp.physaddr as usize + conf.length as usize) as *const u8; @@ -218,7 +220,8 @@ pub fn mpinit() { MPIOAPIC => { let ioapic = p as *const MpIoApic; let ioapicid = unsafe { (*ioapic).apicno }; - MP_ONCE.ioapic_id.set(ioapicid); + MP_ONCE.ioapic_id.set(ioapicid) + .expect("ioapic_id already initialized"); // p = unsafe{ p.add(mem::size_of::()) }; p = p.wrapping_add(mem::size_of::()); } @@ -236,7 +239,8 @@ pub fn mpinit() { if !ismp { panic!("Didn't find a suitable machine"); } - MP_ONCE.cpus.set(cpus); + MP_ONCE.cpus.set(cpus) + .expect("cpus array already initialized"); if mp.imcrp != 0 { // Bochs doesn't support IMCR, so this doesn't run on Bochs. diff --git a/src/traps.rs b/src/traps.rs index 4010605..4974746 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -6,13 +6,9 @@ use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt,rcr2}; use crate::lapic; -use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0, SEG_KCODE, STS_IG32, STS_TG32}; use crate::uart::uartintr; -const SEG_KCODE: u16 = 1; -const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate -const STS_TG32: u8 = 0xF; // 32-bit Trap Gate - extern "C" { static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } From 7a888675b5a669bdc61c7188f00f9b0c468ff294 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 05:15:11 +0000 Subject: [PATCH 26/40] Fixed static mutable warnings --- src/console.rs | 43 ++++++++++++++++++++++--------------------- src/ioapic.rs | 4 ++-- src/lib.rs | 2 ++ src/proc.rs | 2 +- src/traps.rs | 5 +++-- 5 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/console.rs b/src/console.rs index 59f186a..61f0aa3 100644 --- a/src/console.rs +++ b/src/console.rs @@ -52,29 +52,30 @@ pub fn consoleintr(getc: fn() -> i32) { break; } - let input = unsafe { &mut INPUT }; - - match c { - x if x == C('U') => { - while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { - input.e -= 1; - consputc(BACKSPACE); + unsafe { + let input = &raw mut INPUT; + match c { + x if x == C('U') => { + while (*input).e != (*input).w && (*input).buf[((*input).e - 1) % INPUT_BUF] != b'\n' { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - x if x == C('H') || x == 0x7f => { - if input.e != input.w { - input.e -= 1; - consputc(BACKSPACE); + x if x == C('H') || x == 0x7f => { + if (*input).e != (*input).w { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - _ => { - if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { - let c = if c == '\r' as i32 { '\n' as i32 } else { c }; - input.buf[input.e % INPUT_BUF] = c as u8; - input.e += 1; - consputc(c); - if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { - input.w = input.e; + _ => { + if c != 0 && (*input).e.wrapping_sub((*input).r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + (*input).buf[(*input).e % INPUT_BUF] = c as u8; + (*input).e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || (*input).e == (*input).r + INPUT_BUF { + (*input).w = (*input).e; + } } } } diff --git a/src/ioapic.rs b/src/ioapic.rs index 15cf837..979cfd0 100644 --- a/src/ioapic.rs +++ b/src/ioapic.rs @@ -1,7 +1,7 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::console::Console; -use core::fmt::Write; +// use crate::console::Console; +// use core::fmt::Write; use crate::println; // I/O APIC default physical address diff --git a/src/lib.rs b/src/lib.rs index b8c2f0a..9727da0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ #![no_std] // No standard library #![no_main] // No main function +#![allow(dead_code)] use core::panic::PanicInfo; use crate::x86::cli; @@ -59,6 +60,7 @@ fn welcome() { bio::brelse(b1); } +// alltraps is an assembly label not a static function pointer in Rust extern "C" { pub fn alltraps(); } diff --git a/src/proc.rs b/src/proc.rs index 279364c..713ad58 100644 --- a/src/proc.rs +++ b/src/proc.rs @@ -1,5 +1,5 @@ use crate::mp::MP_ONCE; // Import the MP_ONCE static from mp.rs -use core::ptr; +// use core::ptr; use crate::x86::readeflags; use crate::constants::{FL_IF,NCPU}; use crate::lapic; diff --git a/src/traps.rs b/src/traps.rs index 4974746..4806d32 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,6 +1,7 @@ use modular_bitfield::prelude::*; use core::cell::OnceCell; use core::sync::atomic::{AtomicU32, Ordering}; +use core::ptr::addr_of_mut; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; @@ -86,12 +87,12 @@ pub fn tvinit() { ); } unsafe { - let _ = IDT.set(arr); + let _ = (*addr_of_mut!(IDT)).set(arr); } } pub fn idtinit() { - let idt = unsafe { IDT.get().expect("IDT not initialized") }; + let idt = unsafe { (*addr_of_mut!(IDT)).get().expect("IDT not initialized") }; lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } From a8bbbd7c8f5cda7aa80985b4935dcb161cb3029c Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 16:25:12 +0000 Subject: [PATCH 27/40] p6: Fixed iderw to use interrupt-driven design --- Makefile | 1 - src/ide.rs | 40 +++++++++++++++++++++++++--------------- src/lib.rs | 4 ++-- src/x86.rs | 27 ++++++++++++++------------- 4 files changed, 41 insertions(+), 31 deletions(-) diff --git a/Makefile b/Makefile index 884fb32..4054bdc 100644 --- a/Makefile +++ b/Makefile @@ -101,7 +101,6 @@ vectors.S: vectors.pl .PRECIOUS: %.o -include *.d -clean: clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.a *.o *.d *.asm *.sym bootblock kernel xv6.img fs.img mkfs .gdbinit vectors.S diff --git a/src/ide.rs b/src/ide.rs index 4ae4ee2..180b78e 100644 --- a/src/ide.rs +++ b/src/ide.rs @@ -133,7 +133,9 @@ pub fn ideintr() { } } -// ide.rs +// Sync buf with disk. +// If B_DIRTY is set, write buf to disk, clear B_DIRTY, set B_VALID. +// Else if B_VALID is not set, read buf from disk, set B_VALID. pub fn iderw(idx: usize) { let b = crate::bio::buf_mut(idx); @@ -148,23 +150,31 @@ pub fn iderw(idx: usize) { } } - // PURE POLLING: issue the command directly (no IDEQUEUE). - idestart(idx); - - // Wait for completion. - if idewait(true) < 0 { - panic!("iderw: ide error"); + // Append b to idequeue. + b.qnext = None; + unsafe { + let mut pp: *mut Option = &raw mut IDEQUEUE; + while let Some(next_idx) = *pp { + pp = &raw mut crate::bio::buf_mut(next_idx).qnext; + } + *pp = Some(idx); } - // 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); + // Start disk if necessary. + unsafe { + if IDEQUEUE == Some(idx) { + idestart(idx); } } - // 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); + // Wait for request to finish. + // The interrupt handler will set B_VALID when done. + loop { + let flags = b.flags.load(Ordering::Acquire); + if (flags & (B_VALID | B_DIRTY)) == B_VALID { + break; + } + // Force compiler to re-read b->flags which is modified by ideintr() + x86::noop(); + } } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 9727da0..21209db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,8 +35,8 @@ macro_rules! println { fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { - x86::outw(0x604, 0x2000); - x86::outw(0xB004, 0x2000); + x86::outw(0x602, 0x2000); // QEMU isa-debug-exit device + x86::outw(0xB002, 0x2000); // VirtualBox shutdown port } } diff --git a/src/x86.rs b/src/x86.rs index fb341ef..ba0db57 100644 --- a/src/x86.rs +++ b/src/x86.rs @@ -129,22 +129,23 @@ pub unsafe fn insl(port: u16, addr: *mut u32, cnt: usize) { } - +// Output string of dwords to port using rep outsd instruction. +// Matches the C implementation: outsl(port, addr, cnt) +// Note: ESI must be saved/restored as LLVM restricts its use in 32-bit mode 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); - } + let addr_val = addr as u32; + core::arch::asm!( + "push esi", + "mov esi, {addr}", + "cld", + "rep outsd", + "pop esi", + addr = in(reg) addr_val, + in("dx") port, + inout("ecx") cnt => _, + ); } - /// Halts the CPU until the next interrupt occurs. /// The `hlt` instruction: /// 1. Stops instruction execution and places the processor in a HALT state From e51630d8ea1220e265f891d50e1fbb059092ddcd Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 16:39:04 +0000 Subject: [PATCH 28/40] Updated port exit status --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 21209db..b714a15 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,8 +35,8 @@ macro_rules! println { fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { - x86::outw(0x602, 0x2000); // QEMU isa-debug-exit device - x86::outw(0xB002, 0x2000); // VirtualBox shutdown port + x86::outw(0x604, 0x2000); // QEMU isa-debug-exit device + x86::outw(0xB004, 0x2000); // VirtualBox shutdown port } } From fff2425f85fabd24bfa161bfa7e8f6324f2de47f Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 04:52:12 +0000 Subject: [PATCH 29/40] Added constants and fixed welcome() bug --- .gdbinit.tmpl | 1 + Makefile | 9 +---- src/buf.rs | 6 ++- src/constants.rs | 45 +++++++++++++++++++++- src/fs.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++++ src/ide.rs | 3 +- src/lib.rs | 16 +++----- src/mkfs.rs | 61 +++++++++++++++++++++-------- 8 files changed, 202 insertions(+), 38 deletions(-) create mode 100644 src/fs.rs diff --git a/.gdbinit.tmpl b/.gdbinit.tmpl index f71681a..1dfd173 100644 --- a/.gdbinit.tmpl +++ b/.gdbinit.tmpl @@ -25,3 +25,4 @@ target remote localhost:1234 echo + symbol-file kernel\n symbol-file kernel +layout split \ No newline at end of file diff --git a/Makefile b/Makefile index 4054bdc..c8eb197 100644 --- a/Makefile +++ b/Makefile @@ -54,12 +54,7 @@ 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 *.txt - ./mkfs fs.img *.txt - +# Build mkfs utility and create filesystem image mkfs: src/mkfs.rs rustc -W warnings -o mkfs src/mkfs.rs @@ -127,6 +122,6 @@ qemu: xv6.img fs.img .gdbinit: .gdbinit.tmpl sed "s/localhost:1234/localhost:$(GDBPORT)/" < $^ > $@ -qemu-gdb: xv6.img fs .gdbinit +qemu-gdb: xv6.img .gdbinit fs.img @echo "*** Now run 'gdb'." 1>&2 $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) diff --git a/src/buf.rs b/src/buf.rs index 2c4cfb2..95a5faa 100644 --- a/src/buf.rs +++ b/src/buf.rs @@ -1,8 +1,10 @@ use core::sync::atomic::AtomicU32; -pub const BSIZE: usize = 512; // block size -pub const NBUF: usize = 30; // same as xv6 default; can tune later +// Re-export filesystem constants from constants.rs for convenience +// (other modules currently import BSIZE and NBUF from buf) +pub use crate::constants::{BSIZE, NBUF}; +// Buffer flags 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 diff --git a/src/constants.rs b/src/constants.rs index b36418c..40ea01c 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -113,4 +113,47 @@ pub const X1: u32 = 0x0000000B; // divide counts by 1 pub const PERIODIC: u32 = 0x00020000; // Periodic // Error handling -pub const MASKED: u32 = 0x00010000; // Interrupt masked \ No newline at end of file +pub const MASKED: u32 = 0x00010000; // Interrupt masked + +// ------------------------------------------------------ FILE SYSTEM (fs.h) ---------------------------------------------- +// On-disk file system format constants +// Both the kernel and user programs (mkfs) use these definitions + +pub const ROOTINO: u32 = 1; // root i-number +pub const BSIZE: usize = 512; // block size + +// File structure +pub const NDIRECT: usize = 12; // number of direct block pointers +pub const NINDIRECT: usize = BSIZE / core::mem::size_of::(); // number of indirect block pointers (BSIZE / sizeof(uint)) +pub const MAXFILE: usize = NDIRECT + NINDIRECT; // max file size in blocks + +// Directory entry +pub const DIRSIZ: usize = 14; // directory name length + +// Inode calculations +// Note: In C these are macros. IPB = (BSIZE / sizeof(struct dinode)) +// For Rust: sizeof(dinode) = 2+2+2+2+4+(13*4) = 64 bytes +// So IPB = 512/64 = 8 inodes per block +pub const DINODE_SIZE: usize = 64; // sizeof(struct dinode) +pub const IPB: usize = BSIZE / DINODE_SIZE; // inodes per block + +// Bitmap calculations +pub const BPB: usize = BSIZE * 8; // bitmap bits per block + +// ------------------------------------------------------ SYSTEM PARAMETERS (param.h) ---------------------------------------------- +// System-wide parameters + +pub const MAXOPBLOCKS: usize = 10; // max # of blocks any FS op writes +pub const NINODE: usize = 50; // maximum number of active i-nodes +pub const ROOTDEV: u32 = 1; // device number of file system root disk +pub const LOGSIZE: u32 = 30; // max data blocks in on-disk log (C version: 0, extended version: 30) +pub const NBUF: usize = MAXOPBLOCKS * 3; // size of disk block cache +pub const FSSIZE: u32 = 10000; // size of file system in blocks (C version: 1000, extended: 10000) +pub const NINODES: u32 = 200; // number of inodes in file system + +// ------------------------------------------------------ FILE TYPES (stat.h) ---------------------------------------------- +// File type constants for inode.type field + +pub const T_DIR: u16 = 1; // Directory +pub const T_FILE: u16 = 2; // File +pub const T_DEV: u16 = 3; // Device \ No newline at end of file diff --git a/src/fs.rs b/src/fs.rs new file mode 100644 index 0000000..730757b --- /dev/null +++ b/src/fs.rs @@ -0,0 +1,99 @@ +// On-disk file system format. +// Both the kernel and user programs use this header file (in C version). +// This is the Rust equivalent of fs.h + +use crate::constants::*; + +// Disk layout: +// [ boot block | super block | log | inode blocks | +// free bit map | data blocks] +// +// mkfs computes the super block and builds an initial file system. The +// super block describes the disk layout: + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Superblock { + pub size: u32, // Size of file system image (blocks) + pub nblocks: u32, // Number of data blocks + pub ninodes: u32, // Number of inodes + pub nlog: u32, // Number of log blocks + pub logstart: u32, // Block number of first log block + pub inodestart: u32, // Block number of first inode block + pub bmapstart: u32, // Block number of first free map block +} + +// On-disk inode structure +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Dinode { + pub typ: u16, // File type (use 'typ' as 'type' is a Rust keyword) + pub major: u16, // Major device number (T_DEV only) + pub minor: u16, // Minor device number (T_DEV only) + pub nlink: u16, // Number of links to inode in file system + pub size: u32, // Size of file (bytes) + pub addrs: [u32; NDIRECT + 1], // Data block addresses +} + +// Directory entry structure +// A directory is a file containing a sequence of dirent structures. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Dirent { + pub inum: u16, // Inode number + pub name: [u8; DIRSIZ], // Directory name (max DIRSIZ chars) +} + +// Helper functions that match C macros from fs.h + +/// Inodes per block: IPB = (BSIZE / sizeof(struct dinode)) +pub const fn inodes_per_block() -> usize { + BSIZE / core::mem::size_of::() +} + +/// Block containing inode i: IBLOCK(i, sb) = ((i) / IPB + sb.inodestart) +pub fn iblock(inum: u32, sb: &Superblock) -> u32 { + (inum / inodes_per_block() as u32) + u32::from_le(sb.inodestart) +} + +/// Block of free map containing bit for block b: BBLOCK(b, sb) = (b/BPB + sb.bmapstart) +pub fn bblock(blockno: u32, sb: &Superblock) -> u32 { + (blockno / BPB as u32) + u32::from_le(sb.bmapstart) +} + +// Default implementations for convenience +impl Default for Superblock { + fn default() -> Self { + Self { + size: 0, + nblocks: 0, + ninodes: 0, + nlog: 0, + logstart: 0, + inodestart: 0, + bmapstart: 0, + } + } +} + +impl Default for Dinode { + fn default() -> Self { + Self { + typ: 0, + major: 0, + minor: 0, + nlink: 0, + size: 0, + addrs: [0; NDIRECT + 1], + } + } +} + +impl Default for Dirent { + fn default() -> Self { + Self { + inum: 0, + name: [0; DIRSIZ], + } + } +} diff --git a/src/ide.rs b/src/ide.rs index 180b78e..99619f2 100644 --- a/src/ide.rs +++ b/src/ide.rs @@ -1,5 +1,6 @@ use core::sync::atomic::Ordering; -use crate::buf::{BSIZE, B_DIRTY, B_VALID}; +use crate::constants::BSIZE; +use crate::buf::{B_DIRTY, B_VALID}; use crate::x86; const SECTOR_SIZE: usize = 512; diff --git a/src/lib.rs b/src/lib.rs index b714a15..4bb252f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,8 @@ mod picirq; mod mp; mod proc; mod traps; -mod constants; +mod constants; // Internal use only - no external crates +mod fs; // Internal use only - filesystem structures mod buf; mod bio; mod ide; @@ -41,16 +42,9 @@ fn halt() -> ! { } fn welcome() { - let b0 = bio::bread(1, 0); - let data0 = bio::buf_mut(b0).data; - - for &byte in data0.iter() { - if byte == 0 { break; } - console::consputc(byte as i32); - } - bio::brelse(b0); - - let b1 = bio::bread(1, 1); + // Read boot counter from block 0 of device 1 (fs.img) + // Changed from block 1 to block 0 to match C version (p7-mkfs) + let b1 = bio::bread(1, 0); let count = bio::buf_mut(b1).data[0]; println!("\nAfter preparing fs.img, we have rebooted {} times\n", count); diff --git a/src/mkfs.rs b/src/mkfs.rs index 9bfb77b..53fb795 100644 --- a/src/mkfs.rs +++ b/src/mkfs.rs @@ -5,22 +5,51 @@ use std::mem::size_of; use std::path::Path; -// constants to be included in constants.rs under "FILE SYSTEM" section, -// declared here for now to avoid merge conflicts - -const BSIZE: usize = 512; -const FSSIZE: u32 = 10_000; -const NINODES: u32 = 200; -const LOGSIZE: u32 = 30; - -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; +// ============================================================================ +// FILE SYSTEM CONSTANTS AND STRUCTURES +// ============================================================================ +// NOTE: These definitions are duplicated from the kernel codebase. +// +// WHY STANDALONE? +// In the C version, mkfs.c is compiled standalone with `gcc -o mkfs mkfs.c` +// and shares definitions via header files (fs.h, param.h, stat.h). +// +// Rust cannot use header files, so we duplicate the definitions here. +// This matches C's semantic model: mkfs is a host-side utility that runs +// on Linux/Mac (with std) to create fs.img BEFORE the kernel boots. +// +// The kernel (src/*) runs bare-metal x86 (no_std) and cannot share compiled +// code with host programs. +// +// MAINTENANCE: Keep synchronized with: +// - src/constants.rs (constants) +// - src/fs.rs (structs) - once created +// ============================================================================ + +// From fs.h (On-disk file system format) +const ROOTINO: u32 = 1; // root i-number +const BSIZE: usize = 512; // block size +const NDIRECT: usize = 12; // number of direct block pointers +const NINDIRECT: usize = BSIZE / size_of::(); // indirect pointers +const MAXFILE: usize = NDIRECT + NINDIRECT; // max file size in blocks +const DIRSIZ: usize = 14; // directory name length + +// From param.h (System parameters) +const FSSIZE: u32 = 10_000; // size of file system in blocks +const NINODES: u32 = 200; // number of inodes +const LOGSIZE: u32 = 30; // max data blocks in on-disk log + +// From stat.h (File types) +const T_DIR: u16 = 1; // Directory +const T_FILE: u16 = 2; // File + +// ============================================================================ +// FILESYSTEM STRUCTURES (Duplicated from src/fs.rs) +// ============================================================================ +// In C: These are defined in fs.h and included by both kernel and mkfs.c +// In Rust: Canonical definitions are in src/fs.rs (for kernel) +// Duplicated here because mkfs is a standalone host binary +// ============================================================================ #[repr(C)] #[derive(Clone, Copy, Default)] From 30e13e2d42684b7c81bc3d9d65b4fd60dcedec4c Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 06:21:52 +0000 Subject: [PATCH 30/40] Updated bootblock.ld --- Makefile | 9 ++++----- linkers/bootblock.ld | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 linkers/bootblock.ld diff --git a/Makefile b/Makefile index 56e0958..4084a68 100644 --- a/Makefile +++ b/Makefile @@ -69,13 +69,12 @@ xv6.img: bootblock kernel dd if=bootblock of=xv6.img conv=notrunc dd if=kernel of=xv6.img seek=1 conv=notrunc -bootblock: bootasm.S bootmain.c +bootblock: bootasm.S bootmain.c linkers/bootblock.ld $(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 + $(LD) $(LDFLAGS) -T linkers/bootblock.ld -o bootblock.o bootasm.o bootmain.o + $(OBJDUMP) -S bootblock.o > bootblock.asm + $(OBJCOPY) -S -O binary bootblock.o 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 diff --git a/linkers/bootblock.ld b/linkers/bootblock.ld new file mode 100644 index 0000000..6ac5c34 --- /dev/null +++ b/linkers/bootblock.ld @@ -0,0 +1,29 @@ +OUTPUT_FORMAT("elf32-i386", "elf32-i386", "elf32-i386") +OUTPUT_ARCH(i386) +ENTRY(start) + +SECTIONS +{ + . = 0x7c00; + + .text : { + *(.text .text.*) + } + + .rodata : { + *(.rodata .rodata.*) + } + + .data : { + *(.data .data.*) + } + + /DISCARD/ : { + *(.eh_frame .note.GNU-stack .comment) + } + + . = 0x7c00 + 510; + .signature : { + SHORT(0xaa55) + } +} From f8ccfd5aabd836866819bc27306d083e28333e80 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 06:28:43 +0000 Subject: [PATCH 31/40] Updated bootblock.ld --- Makefile | 9 ++++----- bootasm.S | 4 +++- linkers/bootblock.ld | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 linkers/bootblock.ld diff --git a/Makefile b/Makefile index 6e9abeb..23f31c8 100644 --- a/Makefile +++ b/Makefile @@ -61,13 +61,12 @@ fs.img: welcome.txt dd if=/dev/zero of=fs.img count=2 dd if=welcome.txt of=fs.img conv=notrunc -bootblock: bootasm.S bootmain.c +bootblock: bootasm.S bootmain.c linkers/bootblock.ld $(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 + $(LD) $(LDFLAGS) -T linkers/bootblock.ld -o bootblock.o bootasm.o bootmain.o + $(OBJDUMP) -S bootblock.o > bootblock.asm + $(OBJCOPY) -S -O binary bootblock.o bootblock kernel.a: $(RS) cargo build -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec \ diff --git a/bootasm.S b/bootasm.S index 81c0d52..26f81d0 100644 --- a/bootasm.S +++ b/bootasm.S @@ -83,4 +83,6 @@ gdt: gdtdesc: .word (gdtdesc - gdt - 1) # sizeof(gdt) - 1 - .long gdt # address gdt \ No newline at end of file + .long gdt # address gdt + +.section .note.GNU-stack,"",@progbits \ No newline at end of file diff --git a/linkers/bootblock.ld b/linkers/bootblock.ld new file mode 100644 index 0000000..6ac5c34 --- /dev/null +++ b/linkers/bootblock.ld @@ -0,0 +1,29 @@ +OUTPUT_FORMAT("elf32-i386", "elf32-i386", "elf32-i386") +OUTPUT_ARCH(i386) +ENTRY(start) + +SECTIONS +{ + . = 0x7c00; + + .text : { + *(.text .text.*) + } + + .rodata : { + *(.rodata .rodata.*) + } + + .data : { + *(.data .data.*) + } + + /DISCARD/ : { + *(.eh_frame .note.GNU-stack .comment) + } + + . = 0x7c00 + 510; + .signature : { + SHORT(0xaa55) + } +} From 92f17690e3b660231f45de418b03508f97f3178b Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 06:31:29 +0000 Subject: [PATCH 32/40] Updated bootblock.ld --- Makefile | 9 ++++----- bootasm.S | 4 +++- linkers/bootblock.ld | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 linkers/bootblock.ld diff --git a/Makefile b/Makefile index c8eb197..36c7cb5 100644 --- a/Makefile +++ b/Makefile @@ -61,13 +61,12 @@ mkfs: src/mkfs.rs fs.img: mkfs *.txt ./mkfs fs.img *.txt -bootblock: bootasm.S bootmain.c +bootblock: bootasm.S bootmain.c linkers/bootblock.ld $(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 + $(LD) $(LDFLAGS) -T linkers/bootblock.ld -o bootblock.o bootasm.o bootmain.o + $(OBJDUMP) -S bootblock.o > bootblock.asm + $(OBJCOPY) -S -O binary bootblock.o bootblock kernel.a: $(RS) cargo build -Z build-std=core -Z build-std-features=compiler-builtins-mem -Z json-target-spec \ diff --git a/bootasm.S b/bootasm.S index 81c0d52..26f81d0 100644 --- a/bootasm.S +++ b/bootasm.S @@ -83,4 +83,6 @@ gdt: gdtdesc: .word (gdtdesc - gdt - 1) # sizeof(gdt) - 1 - .long gdt # address gdt \ No newline at end of file + .long gdt # address gdt + +.section .note.GNU-stack,"",@progbits \ No newline at end of file diff --git a/linkers/bootblock.ld b/linkers/bootblock.ld new file mode 100644 index 0000000..6ac5c34 --- /dev/null +++ b/linkers/bootblock.ld @@ -0,0 +1,29 @@ +OUTPUT_FORMAT("elf32-i386", "elf32-i386", "elf32-i386") +OUTPUT_ARCH(i386) +ENTRY(start) + +SECTIONS +{ + . = 0x7c00; + + .text : { + *(.text .text.*) + } + + .rodata : { + *(.rodata .rodata.*) + } + + .data : { + *(.data .data.*) + } + + /DISCARD/ : { + *(.eh_frame .note.GNU-stack .comment) + } + + . = 0x7c00 + 510; + .signature : { + SHORT(0xaa55) + } +} From 375bdf6860e863666b4ff96269d3abf023ff4fcd Mon Sep 17 00:00:00 2001 From: Arinjay Singhal <137890548+ArinjaySinghal19@users.noreply.github.com> Date: Mon, 16 Feb 2026 17:19:34 +0530 Subject: [PATCH 33/40] p5: add UART interrupt and console input support --- Makefile | 65 +++++++------------------ src/console.rs | 71 ++++++++++++++++++++++++--- src/lapic.rs | 2 +- src/lib.rs | 9 +++- src/traps.rs | 128 ++++++++++++++++++++++++++++++------------------- src/uart.rs | 31 ++++++++++-- 6 files changed, 198 insertions(+), 108 deletions(-) diff --git a/Makefile b/Makefile index 4084a68..883e6e8 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,6 @@ 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-'; \ @@ -16,18 +8,9 @@ TOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/d 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) + 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; \ @@ -35,14 +18,7 @@ QEMU = $(shell if which qemu > /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) + else echo "*** Error: Couldn't find QEMU." 1>&2; exit 1; fi) endif CC = $(TOOLPREFIX)gcc @@ -50,13 +26,13 @@ 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 -# FreeBSD ld wants ``elf_i386_fbsd'' 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 @@ -77,45 +53,40 @@ bootblock: bootasm.S bootmain.c linkers/bootblock.ld $(OBJCOPY) -S -O binary bootblock.o 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 + cargo +nightly 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 vectors.S: vectors.pl ./vectors.pl > vectors.S -# $(LD) $(LDFLAGS) -T kernel.ld -o kernel entry.o kernel.a -b binary -# ld -m elf_i386 -T kernel.ld -o kernel entry.o kernel.a -b binary -# Prevent deletion of intermediate files, e.g. cat.o, after first build, so -# that disk image changes after first build are persistent until clean. More -# details: -# http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html .PRECIOUS: %.o - -include *.d -clean: +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 + rm -rf target -# run in emulators -# try to generate a unique GDB port GDBPORT = $(shell expr `id -u` % 5000 + 25000) -# QEMU's gdb stub command line changed in 0.11 QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ then echo "-gdb tcp::$(GDBPORT)"; \ else echo "-s -p $(GDBPORT)"; fi) + ifndef CPUS - CPUS := 1 +CPUS := 1 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 -smp $(CPUS) -m 512 qemu: xv6.img $(QEMU) -nographic $(QEMUOPTS) @@ -125,4 +96,4 @@ qemu: xv6.img qemu-gdb: xv6.img .gdbinit @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/console.rs b/src/console.rs index 0f62712..25bde2f 100644 --- a/src/console.rs +++ b/src/console.rs @@ -5,20 +5,79 @@ pub struct Console {} impl Write for Console { fn write_str(&mut self, s: &str) -> Result { for c in s.chars() { - consputc(c); + consputc(c as i32); } Ok(()) } } -const BACKSPACE: char = '\x08'; +const BACKSPACE: i32 = 0x100; +const INPUT_BUF: usize = 128; +const CTRL_D: i32 = C('D'); -fn consputc(c: char) { +#[allow(non_snake_case)] +const fn C(c: char) -> i32 { + (c as i32) - ('@' as i32) +} + +#[derive(Clone, Copy)] +struct Input { + buf: [u8; INPUT_BUF], + r: usize, + w: usize, + e: usize, +} + +static mut INPUT: Input = Input { + buf: [0; INPUT_BUF], + r: 0, + w: 0, + e: 0, +}; + +fn consputc(c: i32) { if c == BACKSPACE { - uartputc(BACKSPACE); - uartputc(' '); - uartputc(BACKSPACE); + uartputc('\x08' as i32); + uartputc(' ' as i32); + uartputc('\x08' as i32); } else { uartputc(c); } +} + +pub fn consoleintr(getc: fn() -> i32) { + loop { + let c = getc(); + if c < 0 { + break; + } + + let input = unsafe { &mut INPUT }; + + match c { + x if x == C('U') => { + while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { + input.e -= 1; + consputc(BACKSPACE); + } + } + x if x == C('H') || x == 0x7f => { + if input.e != input.w { + input.e -= 1; + consputc(BACKSPACE); + } + } + _ => { + if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + input.buf[input.e % INPUT_BUF] = c as u8; + input.e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { + input.w = input.e; + } + } + } + } + } } \ No newline at end of file diff --git a/src/lapic.rs b/src/lapic.rs index 3a1aa17..4f6306d 100644 --- a/src/lapic.rs +++ b/src/lapic.rs @@ -70,7 +70,7 @@ pub fn lapicinit() { // TICR would be calibrated using an external time source. lapicw(TDCR, X1); lapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); - lapicw(TICR, 1000000000); + lapicw(TICR, 10000000); // Disable logical interrupt lines. diff --git a/src/lib.rs b/src/lib.rs index 7808508..51de53c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,8 +45,8 @@ fn panic(info: &PanicInfo) -> ! { fn halt() -> ! { println!("Bye COL{}\n\0", 331); loop { - x86::outw(0x604, 0x2000); - x86::outw(0xB004, 0x2000); + x86::outw(0x602, 0x2000); + x86::outw(0xB002, 0x2000); } } @@ -69,3 +69,8 @@ pub extern "C" fn entryofrust() -> ! { } } +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + println!("Kernel Panic: {:?}", info); + halt() +} \ No newline at end of file diff --git a/src/traps.rs b/src/traps.rs index aa1c1a3..a640548 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,19 +1,25 @@ use modular_bitfield::prelude::*; -use core::cell::{OnceCell, RefCell}; +use core::cell::OnceCell; +use core::sync::atomic::{AtomicU32, Ordering}; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt, rcr2, TrapFrame}; use crate::lapic; -use crate::constants::{SEG_KCODE, STS_IG32, STS_TG32, T_IRQ0, IRQ_TIMER, IRQ_ERROR, IRQ_SPURIOUS}; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::uart::uartintr; + +const SEG_KCODE: u16 = 1; +const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate +const STS_TG32: u8 = 0xF; // 32-bit Trap Gate extern "C" { - static vectors: [usize; 256]; // remove assembly. + static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } #[bitfield] #[repr(C, packed)] -#[derive(Clone, Copy, Default)] // debug can be removed ? do we need to ? +#[derive(Clone, Copy, Default)] pub struct GateDesc { off_15_0: B16, // low 16 bits of offset in segment cs: B16, // code segment selector @@ -32,7 +38,7 @@ impl GateDesc { self.set_args(0); self.set_rsv1(0); let typ = if is_trap { STS_TG32 } else { STS_IG32 }; - self.set_r_type(typ); // for an interrupt gate, for example. + self.set_r_type(typ); self.set_s(0); self.set_dpl(dpl); self.set_p(1); @@ -41,35 +47,56 @@ impl GateDesc { } +static mut IDT: OnceCell<[GateDesc; 256]> = OnceCell::new(); +pub static TICKS: AtomicU32 = AtomicU32::new(0); + + #[repr(C)] -pub struct IDTOnce { - pub idt: OnceCell<[GateDesc; 256]>, -} -unsafe impl Sync for IDTOnce {} -pub static IDT: IDTOnce = IDTOnce { idt: OnceCell::new() }; - -pub struct TickCounter { - ticks: RefCell +pub struct TrapFrame { + // registers as pushed by pusha + pub edi: u32, + pub esi: u32, + pub ebp: u32, + pub oesp: u32, // useless & ignored + pub ebx: u32, + pub edx: u32, + pub ecx: u32, + pub eax: u32, + + pub trapno: u32, + + // below here defined by x86 hardware + pub err: u32, + pub eip: u32, + pub cs: u16, + pub padding5: u16, + pub eflags: u32, + + // below here only when crossing rings, such as from user to kernel + pub esp: u32, + pub ss: u16, + pub padding6: u16, } -unsafe impl Sync for TickCounter {} -static TICKS: TickCounter = TickCounter { ticks: RefCell::new(0) }; pub fn tvinit() { let mut arr = [GateDesc::default(); 256]; for i in 0..256 { arr[i].set_gate( - false, // Use an interrupt gate. - SEG_KCODE << 3, // Code segment selector (shifted as in the C code). - unsafe { vectors[i] }, // Offset from the external vector table. - 0 // Descriptor privilege level. + false, + SEG_KCODE << 3, + unsafe { vectors[i] }, + 0 ); } - IDT.idt.set(arr); + unsafe { + let _ = IDT.set(arr); + } } pub fn idtinit() { - lidt(IDT.idt.get().unwrap() , core::mem::size_of::<[GateDesc; 256]>() as usize); + let idt = unsafe { IDT.get().expect("IDT not initialized") }; + lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } @@ -82,34 +109,37 @@ pub extern "C" fn trap(orig_tf: *mut TrapFrame) { let tf = unsafe { &mut *orig_tf }; - const TIMER: u32 = T_IRQ0 + IRQ_TIMER; - const SPURIOUS: u32 = T_IRQ0 + IRQ_SPURIOUS; - const SEVEN: u32 = T_IRQ0 + 7; - + const TIMER: u32 = T_IRQ0 + IRQ_TIMER; + const SPURIOUS: u32 = T_IRQ0 + IRQ_SPURIOUS; + const SEVEN: u32 = T_IRQ0 + 7; + match tf.trapno { - TIMER => { - *TICKS.ticks.borrow_mut() += 1; - println!("Tick {}!", TICKS.ticks.borrow()); - lapic::lapiceoi(); - } - SEVEN | SPURIOUS => { - println!( - "cpu{}: spurious interrupt at {}:{}\n", - cpuid() , - tf.cs, - tf.eip - ); + TIMER => { + TICKS.fetch_add(1, Ordering::Relaxed); + lapic::lapiceoi(); + } + x if x == T_IRQ0 + IRQ_COM1 => { + uartintr(); lapiceoi(); - } - _ => { - println!( - "unexpected trap {} from cpu {} eip {} (cr2=0x{:x})\n", - tf.trapno, - cpuid(), - tf.eip, - rcr2() - ); - panic!("trap happened"); - } - } + } + SEVEN | SPURIOUS => { + println!( + "cpu{}: spurious interrupt at {:x}:{:x}\n", + cpuid(), + tf.cs, + tf.eip + ); + lapiceoi(); + } + _ => { + println!( + "unexpected trap {} from cpu {} eip {:x} (cr2=0x{:x})\n", + tf.trapno, + cpuid(), + tf.eip, + rcr2() + ); + panic!("trap"); + } + } } \ No newline at end of file diff --git a/src/uart.rs b/src/uart.rs index 9888088..aaf3137 100644 --- a/src/uart.rs +++ b/src/uart.rs @@ -1,7 +1,13 @@ -use crate::x86::{outb, inb}; +use crate::console::consoleintr; +use crate::x86::{inb, outb}; 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_READY: AtomicBool = AtomicBool::new(false); + pub fn uartinit() { // Turn off the FIFO. outb(COM1 + 2, 0); @@ -19,6 +25,7 @@ pub fn uartinit() { if inb(COM1 + 5) == 0xFF { return; } + UART_READY.store(true, Ordering::SeqCst); // Acknowledge pre-existing interrupt conditions; // enable interrupts. @@ -28,15 +35,33 @@ pub fn uartinit() { // Announce that the UART is active. for p in "xv6...\n".chars() { - uartputc(p); + uartputc(p as i32); } } -pub fn uartputc(c: char) { +pub fn uartputc(c: i32) { + if !UART_READY.load(Ordering::SeqCst) { + return; + } + for _ in 0..128 { if inb(COM1 + 5) & 0x20 != 0 { break; } } outb(COM1 + 0, c as u8); +} + +fn uartgetc() -> i32 { + if !UART_READY.load(Ordering::SeqCst) { + return -1; + } + if (inb(COM1 + 5) & 0x01) == 0 { + return -1; + } + inb(COM1) as i32 +} + +pub fn uartintr() { + consoleintr(uartgetc); } \ No newline at end of file From f84251805bdf97ac1ae4f7fb462ab379ba7360e6 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 04:47:41 +0000 Subject: [PATCH 34/40] Accumulated older changes --- src/lib.rs | 11 +++++++++-- src/mp.rs | 1 + src/traps.rs | 6 +----- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 51de53c..3800c4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,8 +69,15 @@ pub extern "C" fn entryofrust() -> ! { } } +static mut PANICKED: bool = false; + #[panic_handler] fn panic(info: &PanicInfo) -> ! { - println!("Kernel Panic: {:?}", info); - halt() + // Disable interrupts to prevent interrupt handlers from interfering + cli(); + // Print panic message with LAPIC ID to identify which CPU panicked + println!("lapicid {}:\n{:#?}", lapicid(), info); + unsafe { PANICKED = true; } + // Halt the system + loop {} } \ No newline at end of file diff --git a/src/mp.rs b/src/mp.rs index 3eecf6a..1b5117e 100644 --- a/src/mp.rs +++ b/src/mp.rs @@ -222,6 +222,7 @@ pub fn mpinit() { let ioapicid = unsafe { (*ioapic).apicno }; MP_ONCE.ioapic_id.set(ioapicid) .expect("ioapic_id already initialized"); + // p = unsafe{ p.add(mem::size_of::()) }; p = p.wrapping_add(mem::size_of::()); } MPBUS | MPIOINTR | MPLINTR => { diff --git a/src/traps.rs b/src/traps.rs index a640548..c1a0f1e 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -6,13 +6,9 @@ use crate::println; use crate::lapic::lapiceoi; use crate::x86::{lidt, rcr2, TrapFrame}; use crate::lapic; -use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0}; +use crate::constants::{IRQ_COM1, IRQ_SPURIOUS, IRQ_TIMER, T_IRQ0, SEG_KCODE, STS_IG32, STS_TG32}; use crate::uart::uartintr; -const SEG_KCODE: u16 = 1; -const STS_IG32: u8 = 0xE; // 32-bit Interrupt Gate -const STS_TG32: u8 = 0xF; // 32-bit Trap Gate - extern "C" { static vectors: [usize; 256]; // in vectors.S: array of 256 entry pointers } From 8ad812bd5c673394d2ecd3107ad9c48c96f31e07 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Mon, 2 Mar 2026 05:15:11 +0000 Subject: [PATCH 35/40] Fixed static mutable warnings --- src/console.rs | 43 ++++++++++++++++++++++--------------------- src/ioapic.rs | 4 ++-- src/lib.rs | 4 +++- src/proc.rs | 2 +- src/traps.rs | 5 +++-- 5 files changed, 31 insertions(+), 27 deletions(-) diff --git a/src/console.rs b/src/console.rs index 25bde2f..507152b 100644 --- a/src/console.rs +++ b/src/console.rs @@ -52,29 +52,30 @@ pub fn consoleintr(getc: fn() -> i32) { break; } - let input = unsafe { &mut INPUT }; - - match c { - x if x == C('U') => { - while input.e != input.w && input.buf[(input.e - 1) % INPUT_BUF] != b'\n' { - input.e -= 1; - consputc(BACKSPACE); + unsafe { + let input = &raw mut INPUT; + match c { + x if x == C('U') => { + while (*input).e != (*input).w && (*input).buf[((*input).e - 1) % INPUT_BUF] != b'\n' { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - x if x == C('H') || x == 0x7f => { - if input.e != input.w { - input.e -= 1; - consputc(BACKSPACE); + x if x == C('H') || x == 0x7f => { + if (*input).e != (*input).w { + (*input).e -= 1; + consputc(BACKSPACE); + } } - } - _ => { - if c != 0 && input.e.wrapping_sub(input.r) < INPUT_BUF { - let c = if c == '\r' as i32 { '\n' as i32 } else { c }; - input.buf[input.e % INPUT_BUF] = c as u8; - input.e += 1; - consputc(c); - if c == '\n' as i32 || c == CTRL_D || input.e == input.r + INPUT_BUF { - input.w = input.e; + _ => { + if c != 0 && (*input).e.wrapping_sub((*input).r) < INPUT_BUF { + let c = if c == '\r' as i32 { '\n' as i32 } else { c }; + (*input).buf[(*input).e % INPUT_BUF] = c as u8; + (*input).e += 1; + consputc(c); + if c == '\n' as i32 || c == CTRL_D || (*input).e == (*input).r + INPUT_BUF { + (*input).w = (*input).e; + } } } } diff --git a/src/ioapic.rs b/src/ioapic.rs index 1196087..eaf9d70 100644 --- a/src/ioapic.rs +++ b/src/ioapic.rs @@ -1,7 +1,7 @@ use core::ptr::{read_volatile, write_volatile}; use crate::mp::MP_ONCE; -use crate::console::Console; -use core::fmt::Write; +// use crate::console::Console; +// use core::fmt::Write; use crate::println; // I/O APIC default physical address diff --git a/src/lib.rs b/src/lib.rs index 3800c4b..2e70ea4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ #![no_std] // No standard library #![no_main] // No main function +#![allow(dead_code)] use core::panic::PanicInfo; use crate::x86::cli; @@ -50,8 +51,9 @@ fn halt() -> ! { } } +// alltraps is an assembly label not a static function pointer extern "C" { - pub static alltraps: fn(); + fn alltraps(); } #[no_mangle] diff --git a/src/proc.rs b/src/proc.rs index 279364c..713ad58 100644 --- a/src/proc.rs +++ b/src/proc.rs @@ -1,5 +1,5 @@ use crate::mp::MP_ONCE; // Import the MP_ONCE static from mp.rs -use core::ptr; +// use core::ptr; use crate::x86::readeflags; use crate::constants::{FL_IF,NCPU}; use crate::lapic; diff --git a/src/traps.rs b/src/traps.rs index c1a0f1e..274e301 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -1,6 +1,7 @@ use modular_bitfield::prelude::*; use core::cell::OnceCell; use core::sync::atomic::{AtomicU32, Ordering}; +use core::ptr::addr_of_mut; use crate::proc::cpuid; use crate::println; use crate::lapic::lapiceoi; @@ -86,12 +87,12 @@ pub fn tvinit() { ); } unsafe { - let _ = IDT.set(arr); + let _ = (*addr_of_mut!(IDT)).set(arr); } } pub fn idtinit() { - let idt = unsafe { IDT.get().expect("IDT not initialized") }; + let idt = unsafe { (*addr_of_mut!(IDT)).get().expect("IDT not initialized") }; lidt(idt, core::mem::size_of::<[GateDesc; 256]>() as usize); } From dc7eb6e4e1f38b5d1c072a70c1ff033cf6f8a620 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 07:54:00 +0000 Subject: [PATCH 36/40] Fixed rebase duplication bugs --- src/lib.rs | 13 ------------- src/traps.rs | 29 ----------------------------- 2 files changed, 42 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2e70ea4..b521783 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -70,16 +70,3 @@ pub extern "C" fn entryofrust() -> ! { x86::wfi(); } } - -static mut PANICKED: bool = false; - -#[panic_handler] -fn panic(info: &PanicInfo) -> ! { - // Disable interrupts to prevent interrupt handlers from interfering - cli(); - // Print panic message with LAPIC ID to identify which CPU panicked - println!("lapicid {}:\n{:#?}", lapicid(), info); - unsafe { PANICKED = true; } - // Halt the system - loop {} -} \ No newline at end of file diff --git a/src/traps.rs b/src/traps.rs index 274e301..646b1ea 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -47,35 +47,6 @@ impl GateDesc { static mut IDT: OnceCell<[GateDesc; 256]> = OnceCell::new(); pub static TICKS: AtomicU32 = AtomicU32::new(0); - -#[repr(C)] -pub struct TrapFrame { - // registers as pushed by pusha - pub edi: u32, - pub esi: u32, - pub ebp: u32, - pub oesp: u32, // useless & ignored - pub ebx: u32, - pub edx: u32, - pub ecx: u32, - pub eax: u32, - - pub trapno: u32, - - // below here defined by x86 hardware - pub err: u32, - pub eip: u32, - pub cs: u16, - pub padding5: u16, - pub eflags: u32, - - // below here only when crossing rings, such as from user to kernel - pub esp: u32, - pub ss: u16, - pub padding6: u16, -} - - pub fn tvinit() { let mut arr = [GateDesc::default(); 256]; for i in 0..256 { From 7d3d6dc18506144a8692c44ab56271c445d88c43 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 08:10:36 +0000 Subject: [PATCH 37/40] Minor bug fixes in traps --- src/console.rs | 2 +- src/traps.rs | 29 ----------------------------- 2 files changed, 1 insertion(+), 30 deletions(-) diff --git a/src/console.rs b/src/console.rs index 507152b..61f0aa3 100644 --- a/src/console.rs +++ b/src/console.rs @@ -35,7 +35,7 @@ static mut INPUT: Input = Input { e: 0, }; -fn consputc(c: i32) { +pub fn consputc(c: i32) { if c == BACKSPACE { uartputc('\x08' as i32); uartputc(' ' as i32); diff --git a/src/traps.rs b/src/traps.rs index a1a2ee9..bce99fc 100644 --- a/src/traps.rs +++ b/src/traps.rs @@ -47,35 +47,6 @@ impl GateDesc { static mut IDT: OnceCell<[GateDesc; 256]> = OnceCell::new(); pub static TICKS: AtomicU32 = AtomicU32::new(0); - -#[repr(C)] -pub struct TrapFrame { - // registers as pushed by pusha - pub edi: u32, - pub esi: u32, - pub ebp: u32, - pub oesp: u32, // useless & ignored - pub ebx: u32, - pub edx: u32, - pub ecx: u32, - pub eax: u32, - - pub trapno: u32, - - // below here defined by x86 hardware - pub err: u32, - pub eip: u32, - pub cs: u16, - pub padding5: u16, - pub eflags: u32, - - // below here only when crossing rings, such as from user to kernel - pub esp: u32, - pub ss: u16, - pub padding6: u16, -} - - pub fn tvinit() { let mut arr = [GateDesc::default(); 256]; for i in 0..256 { From bf8b5266159abd9631ff5ae681e813b686214054 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 08:16:01 +0000 Subject: [PATCH 38/40] Makefile changes --- Makefile | 9 --------- 1 file changed, 9 deletions(-) diff --git a/Makefile b/Makefile index a384fe0..36c7cb5 100644 --- a/Makefile +++ b/Makefile @@ -54,21 +54,12 @@ xv6.img: bootblock kernel dd if=bootblock of=xv6.img conv=notrunc dd if=kernel of=xv6.img seek=1 conv=notrunc -<<<<<<< HEAD # Build mkfs utility and create filesystem image mkfs: src/mkfs.rs rustc -W warnings -o mkfs src/mkfs.rs fs.img: mkfs *.txt ./mkfs fs.img *.txt -======= -# Second disk (fs.img) with welcome text (2 sectors, like C version) -fs: fs.img - -fs.img: welcome.txt - dd if=/dev/zero of=fs.img count=2 - dd if=welcome.txt of=fs.img conv=notrunc ->>>>>>> p6-ide bootblock: bootasm.S bootmain.c linkers/bootblock.ld $(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c From 4f160cad0cfb825f99fc3649026e897e4b14d027 Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 14:55:22 +0000 Subject: [PATCH 39/40] Updated LOGSIZE FSSIZE --- src/constants.rs | 4 ++-- src/mkfs.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/constants.rs b/src/constants.rs index 40ea01c..927cbbd 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -146,9 +146,9 @@ pub const BPB: usize = BSIZE * 8; // bitmap bits per block pub const MAXOPBLOCKS: usize = 10; // max # of blocks any FS op writes pub const NINODE: usize = 50; // maximum number of active i-nodes pub const ROOTDEV: u32 = 1; // device number of file system root disk -pub const LOGSIZE: u32 = 30; // max data blocks in on-disk log (C version: 0, extended version: 30) +pub const LOGSIZE: u32 = 0; // max data blocks in on-disk log (C version: 0, extended version: 30) pub const NBUF: usize = MAXOPBLOCKS * 3; // size of disk block cache -pub const FSSIZE: u32 = 10000; // size of file system in blocks (C version: 1000, extended: 10000) +pub const FSSIZE: u32 = 1000; // size of file system in blocks (Match C Version : 1000) pub const NINODES: u32 = 200; // number of inodes in file system // ------------------------------------------------------ FILE TYPES (stat.h) ---------------------------------------------- diff --git a/src/mkfs.rs b/src/mkfs.rs index 53fb795..f40ae26 100644 --- a/src/mkfs.rs +++ b/src/mkfs.rs @@ -35,9 +35,9 @@ const MAXFILE: usize = NDIRECT + NINDIRECT; // max file size in blocks const DIRSIZ: usize = 14; // directory name length // From param.h (System parameters) -const FSSIZE: u32 = 10_000; // size of file system in blocks +const FSSIZE: u32 = 1_000; // size of file system in blocks const NINODES: u32 = 200; // number of inodes -const LOGSIZE: u32 = 30; // max data blocks in on-disk log +const LOGSIZE: u32 = 0; // max data blocks in on-disk log // From stat.h (File types) const T_DIR: u16 = 1; // Directory From c16e5aca762c5ff599840ddb80304c922be12e1c Mon Sep 17 00:00:00 2001 From: Yash-Rawat-IIT-D Date: Tue, 3 Mar 2026 15:41:59 +0000 Subject: [PATCH 40/40] Updated .S to remove ld GNU-stack warnings --- trapasm.S | 2 ++ vectors.pl | 1 + 2 files changed, 3 insertions(+) diff --git a/trapasm.S b/trapasm.S index 414dc20..477a5ee 100644 --- a/trapasm.S +++ b/trapasm.S @@ -17,3 +17,5 @@ trapret: popal addl $0x8, %esp # trapno and errcode iret + +.section .note.GNU-stack,"",@progbits \ No newline at end of file diff --git a/vectors.pl b/vectors.pl index 57b49dd..0d75a7a 100755 --- a/vectors.pl +++ b/vectors.pl @@ -26,6 +26,7 @@ print " .long vector$i\n"; } +print ".section .note.GNU-stack,\"\",%progbits\n"; # sample output: # # handlers # .globl alltraps