diff options
| -rw-r--r-- | boot/idt.zig | 61 | ||||
| -rw-r--r-- | boot/pmm.zig | 43 | ||||
| -rw-r--r-- | boot/sched.zig | 215 | ||||
| -rw-r--r-- | boot/user.zig | 96 | ||||
| -rw-r--r-- | boot/vmm.zig | 117 | ||||
| -rw-r--r-- | kernel/vfs.rv | 9 | ||||
| -rw-r--r-- | sysroot/usr/include/sys/syscall.h | 15 | ||||
| -rw-r--r-- | sysroot/usr/include/unistd.h | 5 | ||||
| -rw-r--r-- | sysroot/usr/lib/libc/syscalls.c | 20 | ||||
| -rw-r--r-- | user/forktest.c | 28 |
10 files changed, 562 insertions, 47 deletions
diff --git a/boot/idt.zig b/boot/idt.zig index 50b5c6f..79a8974 100644 --- a/boot/idt.zig +++ b/boot/idt.zig @@ -10,6 +10,7 @@ const pic = @import("pic.zig"); const keyboard = @import("keyboard.zig"); const timer = @import("timer.zig"); const sched = @import("sched.zig"); +const vmm = @import("vmm.zig"); const regs = @import("regs.zig"); const Frame = regs.Frame; @@ -86,7 +87,13 @@ export fn isrCommon() callconv(.naked) void { ); } -export fn exceptionHandler(frame: *Frame) callconv(.c) noreturn { +fn readCr2() u64 { + return asm volatile ("mov %%cr2, %[out]" + : [out] "=r" (-> u64), + ); +} + +fn dumpFrame(frame: *Frame) void { serial.write("\r\n!!! CPU DID AN OOPSIE: "); serial.write(name(frame.vector)); serial.write("\r\n vector="); @@ -101,14 +108,45 @@ export fn exceptionHandler(frame: *Frame) callconv(.c) noreturn { serial.writeHex(frame.rflags); serial.write(" rsp="); serial.writeHex(frame.rsp); - // page faults stash the offending address in cr2 - if (frame.vector == VEC_PAGE_FAULT) { - const cr2 = asm volatile ("mov %%cr2, %[out]" - : [out] "=r" (-> u64), - ); - serial.write("\r\n cr2="); - serial.writeHex(cr2); - } + serial.write("\r\n"); +} + +export fn exceptionHandler(frame: *Frame) callconv(.c) noreturn { + dumpFrame(frame); + while (true) asm volatile ("hlt"); +} + +// #pf gets its own return path so a write to a copy on write page is fixed by vmm +// and we i retq to retry the faulting instruction, anything else just kills itself +fn pfStub() callconv(.naked) void { + // the cpu already pushed the error code for #pf + asm volatile ("pushq %[v]\n jmp pfCommon" + : + : [v] "i" (@as(u32, VEC_PAGE_FAULT)), + ); +} + +export fn pfCommon() callconv(.naked) void { + asm volatile (regs.PUSH_GPRS ++ + \\ + \\ mov %rsp, %rdi + \\ call pfHandler + \\ + ++ regs.POP_GPRS ++ + \\ + \\ add $16, %rsp + \\ iretq + ); +} + +export fn pfHandler(frame: *Frame) callconv(.c) void { + const fault_addr = readCr2(); + // bit 1 of the error code = the fault was a write + if (frame.error_code & 0b10 != 0 and vmm.handleCow(fault_addr)) return; + + dumpFrame(frame); + serial.write(" cr2="); + serial.writeHex(fault_addr); serial.write("\r\n"); while (true) asm volatile ("hlt"); } @@ -175,11 +213,12 @@ pub fn setGate(vector: u8, handler: u64, dpl: u2, ist: u3) void { // fill the exception vectors and load the idt pub fn init() void { inline for (0..32) |vector| setGate(vector, @intFromPtr(&stub(vector)), 0, 0); // vectors 0..31 are exceptions - // #df (8) and #pf (14) land on ist2s fault stack, so a kernel stack overflow + // #df (8) and #pf (14) land on ist2s fault stack so a kernel stack overflow // produces a real exception dump instead of a silent triple fault const ist_fault = 2; setGate(VEC_DOUBLE_FAULT, @intFromPtr(&stub(VEC_DOUBLE_FAULT)), 0, ist_fault); - setGate(VEC_PAGE_FAULT, @intFromPtr(&stub(VEC_PAGE_FAULT)), 0, ist_fault); + // #pf uses the returning path so copy on write faults can be fixed up + setGate(VEC_PAGE_FAULT, @intFromPtr(&pfStub), 0, ist_fault); // irq0 (pit) -> vector 0x20, irq1 (keyboard) -> vector 0x21 // the pic is remapped separately in boot setGate(pic.MASTER_OFFSET + 0, @intFromPtr(&irqStub(pic.MASTER_OFFSET + 0)), 0, 0); diff --git a/boot/pmm.zig b/boot/pmm.zig index 1112134..3e580df 100644 --- a/boot/pmm.zig +++ b/boot/pmm.zig @@ -20,6 +20,9 @@ var hhdm_offset: u64 = 0; // reached through the hhdm, so its just a normal slice we write through var bitmap: []u8 = &[_]u8{}; +// one reference count per frame +var refcounts: []u8 = &[_]u8{}; + var total_frames: usize = 0; // frames the bitmap can index (up to highest usable end) var usable_frames: usize = 0; // frames that started free var free_frames: usize = 0; // frames currently free @@ -67,20 +70,23 @@ pub fn init(hhdm: *const limine.HhdmResponse, memmap: *const limine.MemoryMapRes } total_frames = highest / PAGE_SIZE; const bitmap_bytes = (total_frames + 7) / 8; + const refcount_bytes = total_frames; // one u8 per frame + const storage_bytes = bitmap_bytes + refcount_bytes; - // park the bitmap in the first usable region big enough to hold it var storage_base: u64 = 0; for (entries) |entry| { - if (entry.type == .usable and entry.length >= bitmap_bytes) { + if (entry.type == .usable and entry.length >= storage_bytes) { storage_base = entry.base; break; } } - if (storage_base == 0 and bitmap_bytes > 0) @panic("pmm: no room for the frame bitmap"); + if (storage_base == 0 and storage_bytes > 0) @panic("pmm: no room for the frame bookkeeping"); const ptr: [*]u8 = @ptrFromInt(physToVirt(storage_base)); bitmap = ptr[0..bitmap_bytes]; + refcounts = ptr[bitmap_bytes..storage_bytes]; + @memset(refcounts, 0); - // start with everything used, then punch out the usable regions + // start with everything used then punch out the usable regions @memset(bitmap, 0xFF); for (entries) |entry| { if (entry.type == .usable) { @@ -99,7 +105,7 @@ pub fn init(hhdm: *const limine.HhdmResponse, memmap: *const limine.MemoryMapRes // last frame the bitmap spills into still gets reserved { const start = storage_base / PAGE_SIZE; - const end = (storage_base + bitmap_bytes + PAGE_SIZE - 1) / PAGE_SIZE; + const end = (storage_base + storage_bytes + PAGE_SIZE - 1) / PAGE_SIZE; var i = start; while (i < end) : (i += 1) { if (i < total_frames) reserve(i); @@ -109,9 +115,11 @@ pub fn init(hhdm: *const limine.HhdmResponse, memmap: *const limine.MemoryMapRes } // reserve = mark used +// thatsa it fn reserve(i: usize) void { if (!frameUsed(i)) { markUsed(i); + refcounts[i] = 1; free_frames -= 1; } } @@ -125,6 +133,7 @@ pub fn alloc() ?u64 { if (i >= total_frames) i = 0; if (!frameUsed(i)) { markUsed(i); + refcounts[i] = 1; free_frames -= 1; next_hint = i + 1; return @as(u64, i) * PAGE_SIZE; @@ -134,6 +143,16 @@ pub fn alloc() ?u64 { return null; } +pub fn incref(phys: u64) void { + const i = phys / PAGE_SIZE; + if (i < total_frames) refcounts[i] += 1; +} + +pub fn refcount(phys: u64) u8 { + const i = phys / PAGE_SIZE; + return if (i < total_frames) refcounts[i] else 0; +} + // hand out count contiguous physical frames cause the heap needs one flat buffer and a // single usable region is contiguous in physical space, so this just finds a run of count free bits // note: returns the base physical address of the run @@ -147,6 +166,7 @@ pub fn allocContig(count: usize) ?u64 { var j: usize = 0; while (j < count) : (j += 1) { markUsed(i + j); + refcounts[i + j] = 1; free_frames -= 1; } return @as(u64, i) * PAGE_SIZE; @@ -157,13 +177,18 @@ pub fn allocContig(count: usize) ?u64 { return null; } +// drop one reference pub fn free(phys: u64) void { const i = phys / PAGE_SIZE; - if (i < total_frames and frameUsed(i)) { - markFree(i); - free_frames += 1; - if (i < next_hint) next_hint = i; + if (i >= total_frames or !frameUsed(i)) return; + if (refcounts[i] > 1) { + refcounts[i] -= 1; + return; } + refcounts[i] = 0; + markFree(i); + free_frames += 1; + if (i < next_hint) next_hint = i; } pub fn freeBytes() u64 { diff --git a/boot/sched.zig b/boot/sched.zig index e267edd..6b79ba8 100644 --- a/boot/sched.zig +++ b/boot/sched.zig @@ -15,7 +15,17 @@ const MAX_PATH = 128; // user heap lives here in the gap between the program and the arg/stack const HEAP_BASE: u64 = 0x1000_0000; -const State = enum { free, ready, dead, blocked }; +const State = enum { + free, // slot unused + ready, // runable + dead, // exited orphan + blocked, // parked in read + zombie, // exited and kept + waiting, // parked in wait +}; + +// where the arg string is mapped in a freshly loaded program +const ARG_VADDR: u64 = 0x5000_0000; // file descriptor not "foid decimator" pub const FdKind = enum { closed, keyboard, console, file }; @@ -33,6 +43,8 @@ const Task = struct { state: State = .free, brk_cur: u64 = 0, // the program break, top of the user heap brk_top: u64 = 0, // first page above the break thats actually mapped + parent: usize = 0, // pid of the task that forked this one, 0 = kernel spawned + exit_code: i32 = 0, // left behind for a waiting parent to collect }; var tasks: [MAX_TASKS]Task = @splat(.{}); @@ -132,6 +144,148 @@ pub fn sbrk(increment: i64) i64 { return @intCast(old); } +pub fn getpid() u64 { + return current; +} + +pub fn fork(child_frame: Frame) i64 { + if (current == 0) return -1; // the kernel task cant fork + + var slot: usize = 1; + while (slot < MAX_TASKS and tasks[slot].state != .free) slot += 1; + if (slot == MAX_TASKS) return -1; + + const child_cr3 = vmm.forkAddressSpace(tasks[current].cr3) orelse return -1; + + tasks[slot] = .{ + .frame = child_frame, + .cr3 = child_cr3, + .kstack_top = @intFromPtr(&kstacks[slot]) + KSTACK_SIZE, + .state = .ready, + .brk_cur = tasks[current].brk_cur, + .brk_top = tasks[current].brk_top, + .parent = current, + }; + fdtabs[slot] = fdtabs[current]; // the child inherits the open fds + return @intCast(slot); +} + +pub const ExecImage = struct { + cr3: u64, + entry: u64, + stack: u64, + arg_ptr: u64, + arg_len: u64, +}; + +var exec_scratch: u64 = 0; // phys base of a staging buffer for the elf image +const EXEC_SCRATCH_PAGES = 64; + +fn readInt(comptime T: type, addr: u64) T { + return @as(*align(1) const T, @ptrFromInt(addr)).*; +} + +pub fn loadExec(path: []const u8, arg: []const u8) ?ExecImage { + const size = bridge.fsSize(path); + if (size < 0) return null; + const bytes: usize = @intCast(size); + if (bytes > EXEC_SCRATCH_PAGES * pmm.PAGE_SIZE) return null; + + if (exec_scratch == 0) exec_scratch = pmm.allocContig(EXEC_SCRATCH_PAGES) orelse return null; + const base = pmm.physToVirt(exec_scratch); + const staging: [*]u8 = @ptrFromInt(base); + _ = bridge.fsReadInto(path, 0, staging[0..bytes]); + + if (readInt(u32, base) != 0x464c_457f) return null; // elf magic + + const space = vmm.createAddressSpace() orelse return null; + const entry = readInt(u64, base + 24); + const ph_off = readInt(u64, base + 32); + const ph_count = readInt(u16, base + 56); + const ph_size = readInt(u16, base + 54); + + var i: usize = 0; + while (i < ph_count) : (i += 1) { + const ph = base + ph_off + i * ph_size; + if (readInt(u32, ph) != 1) continue; // PT_LOAD + const file_off = readInt(u64, ph + 8); + const vaddr = readInt(u64, ph + 16); + const file_size = readInt(u64, ph + 32); + const mem_size = readInt(u64, ph + 40); + + var off: u64 = 0; + while (off < mem_size) : (off += pmm.PAGE_SIZE) { + const frame = pmm.alloc() orelse return null; + const page: [*]u8 = @ptrFromInt(pmm.physToVirt(frame)); + @memset(page[0..pmm.PAGE_SIZE], 0); + if (off < file_size) { + const n = @min(file_size - off, pmm.PAGE_SIZE); + const src: [*]const u8 = @ptrFromInt(base + file_off + off); + @memcpy(page[0..n], src[0..n]); + } + _ = vmm.map(space, vaddr + off, frame, USER_PAGE); + } + } + + const stack_top: u64 = 0x7fff_0000; + var p: usize = 0; + while (p < 4) : (p += 1) { + const frame = pmm.alloc() orelse return null; + const page: [*]u8 = @ptrFromInt(pmm.physToVirt(frame)); + @memset(page[0..pmm.PAGE_SIZE], 0); + _ = vmm.map(space, stack_top - (p + 1) * pmm.PAGE_SIZE, frame, USER_PAGE); + } + + var arg_ptr: u64 = 0; + if (arg.len > 0) { + const frame = pmm.alloc() orelse return null; + const page: [*]u8 = @ptrFromInt(pmm.physToVirt(frame)); + @memset(page[0..pmm.PAGE_SIZE], 0); + const n = @min(arg.len, pmm.PAGE_SIZE); + @memcpy(page[0..n], arg[0..n]); + _ = vmm.map(space, ARG_VADDR, frame, USER_PAGE); + arg_ptr = ARG_VADDR; + } + + return .{ .cr3 = space, .entry = entry, .stack = stack_top, .arg_ptr = arg_ptr, .arg_len = arg.len }; +} + +pub fn execReplace(new_cr3: u64) void { + const old = tasks[current].cr3; + tasks[current].cr3 = new_cr3; + tasks[current].brk_cur = HEAP_BASE; + tasks[current].brk_top = HEAP_BASE; + vmm.loadPml4(new_cr3); + vmm.freeAddressSpace(old); +} + +pub fn reapZombie(code_out: *i32) i64 { + var i: usize = 1; + while (i < MAX_TASKS) : (i += 1) { + if (tasks[i].state == .zombie and tasks[i].parent == current) { + code_out.* = tasks[i].exit_code; + vmm.freeAddressSpace(tasks[i].cr3); + tasks[i].state = .free; + return @intCast(i); + } + } + return -1; +} + +pub fn hasChildren() bool { + var i: usize = 1; + while (i < MAX_TASKS) : (i += 1) { + if (tasks[i].parent == current and tasks[i].state != .free) return true; + } + return false; +} + +pub fn blockCurrentOnWait(resume_frame: Frame) void { + if (current == 0) return; + tasks[current].frame = resume_frame; + tasks[current].state = .waiting; +} + // stdin at keyboard fn initFds(i: usize) void { for (&fdtabs[i]) |*slot| slot.* = .{}; @@ -176,7 +330,7 @@ pub fn procCount() u64 { var count: u64 = 0; var i: usize = 1; while (i < MAX_TASKS) : (i += 1) { - if (tasks[i].state == .ready or tasks[i].state == .blocked) count += 1; + if (tasks[i].state == .ready or tasks[i].state == .blocked or tasks[i].state == .waiting) count += 1; } return count; } @@ -193,17 +347,40 @@ pub fn taskState(i: u64) u64 { var proc_exited_flag: bool = false; -// mark the running process dead then sti+hlts -pub fn exitCurrent() void { - if (current != 0) { - tasks[current].state = .dead; - proc_exited_flag = true; - if (foreground == current) { - foreground = null; - stdin_head = 0; - stdin_tail = 0; +// record the exit code and park the task. an orphan goes .dead (tick reclaims +// it), a task with a parent goes .zombie until the parent reaps it in wait +pub fn exitCurrent(code: i32) void { + if (current == 0) return; + const me = current; + tasks[me].exit_code = code; + + // hand our children to the kernel, reaping any that already exited so a + // dead parent never strands a zombie + var i: usize = 1; + while (i < MAX_TASKS) : (i += 1) { + if (tasks[i].parent == me) { + tasks[i].parent = 0; + if (tasks[i].state == .zombie) { + vmm.freeAddressSpace(tasks[i].cr3); + tasks[i].state = .free; + } } } + + if (tasks[me].parent == 0) { + tasks[me].state = .dead; + } else { + tasks[me].state = .zombie; + if (tasks[tasks[me].parent].state == .waiting) + tasks[tasks[me].parent].state = .ready; // wake it to reap us + } + + if (foreground == me) { + foreground = null; + stdin_head = 0; + stdin_tail = 0; + } + proc_exited_flag = true; } pub fn takeProcExited() bool { @@ -241,12 +418,16 @@ pub fn deliverInput(byte: u8) bool { pub fn tick(frame: *Frame) void { if (bridge.vmBusy()) return; - if (tasks[current].state == .dead) { - tasks[current].state = .free; - } else if (tasks[current].state == .blocked) { - // dont clobber it you bitch - } else { - tasks[current].frame = frame.*; + switch (tasks[current].state) { + // an orphan that exited: now that we are about to switch away, reclaim + // its address space and free the slot + .dead => { + vmm.freeAddressSpace(tasks[current].cr3); + tasks[current].state = .free; + }, + // parked tasks keep their saved frame, dont clobber it you bitch + .blocked, .waiting, .zombie => {}, + else => tasks[current].frame = frame.*, } var next = current; diff --git a/boot/user.zig b/boot/user.zig index cff7b16..61ba0a4 100644 --- a/boot/user.zig +++ b/boot/user.zig @@ -28,6 +28,10 @@ const SYS_CLOSE: u64 = 8; const SYS_LSEEK: u64 = 9; const SYS_BRK: u64 = 10; const SYS_SBRK: u64 = 11; +const SYS_FORK: u64 = 12; +const SYS_EXEC: u64 = 13; +const SYS_WAIT: u64 = 14; +const SYS_GETPID: u64 = 15; // lseek whence const SEEK_SET: u64 = 0; @@ -50,6 +54,43 @@ fn userName(ptr: u64) []const u8 { return name_buf[0..i]; } +// a second scratch so exec can hold a path and an arg at once +var arg_buf: [MAX_NAME]u8 = undefined; +fn userArg(ptr: u64) []const u8 { + if (ptr == 0) return arg_buf[0..0]; + const p: [*]const u8 = @ptrFromInt(ptr); + var i: usize = 0; + while (i < arg_buf.len - 1 and p[i] != 0) : (i += 1) arg_buf[i] = p[i]; + return arg_buf[0..i]; +} + +fn toFrame(f: *SyscallFrame) Frame { + return .{ + .r15 = f.r15, + .r14 = f.r14, + .r13 = f.r13, + .r12 = f.r12, + .r11 = f.r11, + .r10 = f.r10, + .r9 = f.r9, + .r8 = f.r8, + .rbp = f.rbp, + .rdi = f.rdi, + .rsi = f.rsi, + .rdx = f.rdx, + .rcx = f.rcx, + .rbx = f.rbx, + .rax = f.rax, + .vector = 0, + .error_code = 0, + .rip = f.rip, + .cs = f.cs, + .rflags = f.rflags, + .rsp = f.rsp, + .ss = f.ss, + }; +} + pub const SyscallFrame = extern struct { r15: u64, r14: u64, @@ -98,8 +139,8 @@ export fn syscallHandler(frame: *SyscallFrame) callconv(.c) void { // i js reorganized half of these so if anyone wrote code in asm // for this (me), your syscalled are fucked switch (frame.rax) { - SYS_EXIT => { // exit(code): code in rdi - sched.exitCurrent(); + SYS_EXIT => { // exit(code) + sched.exitCurrent(@intCast(frame.rdi & 0xff)); asm volatile ("sti"); while (true) asm volatile ("hlt"); }, @@ -244,6 +285,57 @@ export fn syscallHandler(frame: *SyscallFrame) callconv(.c) void { SYS_SBRK => { // sbrk(increment) frame.rax = @bitCast(sched.sbrk(@bitCast(frame.rdi))); }, + SYS_FORK => { // fork() + var child = toFrame(frame); + child.rax = 0; + frame.rax = @bitCast(sched.fork(child)); + }, + SYS_EXEC => { // exec(path, arg) + const path = userName(frame.rdi); + const arg = userArg(frame.rsi); + if (sched.loadExec(path, arg)) |image| { + sched.execReplace(image.cr3); + frame.r15 = 0; + frame.r14 = 0; + frame.r13 = 0; + frame.r12 = 0; + frame.r11 = 0; + frame.r10 = 0; + frame.r9 = 0; + frame.r8 = 0; + frame.rbp = 0; + frame.rbx = 0; + frame.rcx = 0; + frame.rdx = 0; + frame.rax = 0; + frame.rdi = image.arg_ptr; + frame.rsi = image.arg_len; + frame.rip = image.entry; + frame.rsp = image.stack; + } else frame.rax = SYS_ERR; + }, + SYS_WAIT => { // wait(status_ptr) + var code: i32 = 0; + const pid = sched.reapZombie(&code); + if (pid >= 0) { + if (frame.rdi != 0) { + const status: *i32 = @ptrFromInt(frame.rdi); + status.* = code; + } + frame.rax = @bitCast(pid); + } else if (!sched.hasChildren()) { + frame.rax = SYS_ERR; + } else { + var rf = toFrame(frame); + rf.rip = frame.rip - INT80_LEN; + sched.blockCurrentOnWait(rf); + asm volatile ("sti"); + while (true) asm volatile ("hlt"); + } + }, + SYS_GETPID => { // getpid() + frame.rax = sched.getpid(); + }, else => serial.write("[syscall] unknown\r\n"), } } diff --git a/boot/vmm.zig b/boot/vmm.zig index 03d89ef..c84b624 100644 --- a/boot/vmm.zig +++ b/boot/vmm.zig @@ -1,9 +1,9 @@ -// our own 4 level (x86_64) page tables, so we can build +// our own 4 level (x86_64) page tables so we can build // per process address spaces and mark pages user accessible // -// physical frames come from the pmm, so we reach any frame through the hhdm -// (pmm.phystovirt) to read/write table entries. the privileged bits (reading -// cr3, invlpg) are the only asm here +// physical frames come from the pmm so we reach any frame through the hhdm +// to read/write table entries. the privileged bits (reading cr3, invlpg) are the +// only thing written in asm here // // see: https://wiki.osdev.org/Paging @@ -15,6 +15,10 @@ pub const WRITE: u64 = 1 << 1; pub const USER: u64 = 1 << 2; // 1 = ring 3 accessible pub const NX: u64 = 1 << 63; // WARNING: NEEDS EFER.NXE DO NOT SET UNLESS ENABLED +// a free software bit (the cpu ignores bits 9..11). we flag a page copy on write +// here: the page is mapped read only, and a write fault copies it, see handleCow +pub const COW: u64 = 1 << 9; + // bits 12..51 of an entry hold the physical frame address const ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000; @@ -58,7 +62,7 @@ fn index(virt: u64, level: u6) usize { } // return the physical base of the next level table under entry i -// if missing, create one +// if missing -> create one fn nextTable(parent_phys: u64, i: usize, create: bool) ?u64 { const entries = table(parent_phys); const entry = entries[i]; @@ -100,6 +104,109 @@ pub fn createAddressSpace() ?u64 { return pml4; } +// deeop copy one lower level table (level 0=pt, level 1=pd, level 2=pdpt) +// subtables get fresh frames but leaf data pages are shared with the parent and +// flipped to copy on write on both sides. +fn copyTable(src_phys: u64, level: u6) ?u64 { + const new = pmm.alloc() orelse return null; + zeroFrame(new); + const src = table(src_phys); + const dst = table(new); + + var i: usize = 0; + while (i < 512) : (i += 1) { + if (src[i] & PRESENT == 0) continue; + if (level == 0) { + var entry = src[i]; + if (entry & WRITE != 0) { + entry = (entry & ~WRITE) | COW; // demote: writable -> copy on write + src[i] = entry; // the parent shares the same arr + } + dst[i] = entry; + pmm.incref(entry & ADDR_MASK); + } else { + const sub = copyTable(src[i] & ADDR_MASK, level - 1) orelse { + freeTable(new, level); + return null; + }; + dst[i] = sub | (src[i] & ~ADDR_MASK); + } + } + return new; +} + +fn freeTable(phys: u64, level: u6) void { + const t = table(phys); + var i: usize = 0; + while (i < 512) : (i += 1) { + if (t[i] & PRESENT == 0) continue; + if (level == 0) { + pmm.free(t[i] & ADDR_MASK); // decref the leaf data page + } else { + freeTable(t[i] & ADDR_MASK, level - 1); + } + } + pmm.free(phys); // the table frame itself is never shared +} + +pub fn forkAddressSpace(parent_pml4: u64) ?u64 { + const child = pmm.alloc() orelse return null; + zeroFrame(child); + const src = table(parent_pml4); + const dst = table(child); + + // kernel higher half + var i: usize = 256; + while (i < 512) : (i += 1) dst[i] = src[i]; + + // user half + i = 0; + while (i < 256) : (i += 1) { + if (src[i] & PRESENT == 0) continue; + const sub = copyTable(src[i] & ADDR_MASK, 2) orelse { + freeAddressSpace(child); + return null; + }; + dst[i] = sub | (src[i] & ~ADDR_MASK); + } + + loadPml4(activePml4()); + return child; +} + +pub fn freeAddressSpace(pml4: u64) void { + const t = table(pml4); + var i: usize = 0; + while (i < 256) : (i += 1) { + if (t[i] & PRESENT != 0) freeTable(t[i] & ADDR_MASK, 2); + } + pmm.free(pml4); +} + +pub fn handleCow(virt: u64) bool { + const pml4 = activePml4(); + const pdpt = nextTable(pml4, index(virt, 3), false) orelse return false; + const pd = nextTable(pdpt, index(virt, 2), false) orelse return false; + const pt = nextTable(pd, index(virt, 1), false) orelse return false; + const pte = &table(pt)[index(virt, 0)]; + const entry = pte.*; + if (entry & PRESENT == 0 or entry & COW == 0) return false; + + const old_phys = entry & ADDR_MASK; + if (pmm.refcount(old_phys) > 1) { + const new_phys = pmm.alloc() orelse return false; + const from: [*]const u8 = @ptrFromInt(pmm.physToVirt(old_phys)); + const to: [*]u8 = @ptrFromInt(pmm.physToVirt(new_phys)); + @memcpy(to[0..pmm.PAGE_SIZE], from[0..pmm.PAGE_SIZE]); + pte.* = (new_phys & ADDR_MASK) | (entry & ~ADDR_MASK & ~COW) | WRITE; + pmm.free(old_phys); // drop our share of the old frame + } else { + pte.* = (entry & ~COW) | WRITE; // js take write back + } + invlpg(virt); + return true; +} + // walk the tables and return the physical address a virtual address maps to // (page base | offset), or null if unmapped // note: mostly for debugging diff --git a/kernel/vfs.rv b/kernel/vfs.rv index 6547595..f01d1cd 100644 --- a/kernel/vfs.rv +++ b/kernel/vfs.rv @@ -37,7 +37,14 @@ global parse_pid = fn(text) -> num do return number end -const TASK_STATES = { "free", "ready", "dead", "blocked" } +const TASK_STATES = { + "free", # slot unused + "ready", # runnable + "dead", # exited orphan + "blocked", # parked in read + "zombie", # exited and kept + "waiting" # parked in wait +} const procfs = { writable = :false, diff --git a/sysroot/usr/include/sys/syscall.h b/sysroot/usr/include/sys/syscall.h index 4a23a53..eecd257 100644 --- a/sysroot/usr/include/sys/syscall.h +++ b/sysroot/usr/include/sys/syscall.h @@ -7,8 +7,19 @@ #define SYS_open 7 #define SYS_close 8 #define SYS_lseek 9 -#define SYS_brk 10 -#define SYS_sbrk 11 +#define SYS_brk 10 +#define SYS_sbrk 11 +#define SYS_fork 12 +#define SYS_exec 13 +#define SYS_wait 14 +#define SYS_getpid 15 + +static inline long __syscall0(long number) +{ + long result; + __asm__ volatile("int $0x80" : "=a"(result) : "a"(number) : "memory"); + return result; +} static inline long __syscall1(long number, long a1) { diff --git a/sysroot/usr/include/unistd.h b/sysroot/usr/include/unistd.h index f5a67ab..65414d5 100644 --- a/sysroot/usr/include/unistd.h +++ b/sysroot/usr/include/unistd.h @@ -15,4 +15,9 @@ long lseek(int fd, long offset, int whence); void* sbrk(long increment); int brk(void* address); +int fork(void); +int exec(const char* path, const char* arg); +int wait(int* status); +int getpid(void); + #endif diff --git a/sysroot/usr/lib/libc/syscalls.c b/sysroot/usr/lib/libc/syscalls.c index ad959b9..33bbb12 100644 --- a/sysroot/usr/lib/libc/syscalls.c +++ b/sysroot/usr/lib/libc/syscalls.c @@ -36,3 +36,23 @@ int brk(void* address) { return (int)__syscall1(SYS_brk, (long)address); } + +int fork(void) +{ + return (int)__syscall0(SYS_fork); +} + +int exec(const char* path, const char* arg) +{ + return (int)__syscall2(SYS_exec, (long)path, (long)arg); +} + +int wait(int* status) +{ + return (int)__syscall1(SYS_wait, (long)status); +} + +int getpid(void) +{ + return (int)__syscall0(SYS_getpid); +} diff --git a/user/forktest.c b/user/forktest.c new file mode 100644 index 0000000..14cc91b --- /dev/null +++ b/user/forktest.c @@ -0,0 +1,28 @@ +#include <stdio.h> +#include <unistd.h> + +int main(void) +{ + printf("forktest: pid %d\n", getpid()); + + int pid = fork(); + if (pid < 0) + { + printf("fork failed\n"); + return 1; + } + + if (pid == 0) + { + printf(" child: pid %d, exec-ing membrk\n", getpid()); + exec("/usr/bin/membrk", 0); + printf(" child: exec failed\n"); + return 127; + } + + printf(" parent: forked child %d, waiting...\n", pid); + int status = -1; + int reaped = wait(&status); + printf(" parent: child %d exited with status %d\n", reaped, status); + return 0; +} |
