summaryrefslogtreecommitdiffstats
path: root/rsdos/src/main.rs
blob: e40098d84b8461659661ed4ef613939d9fe7a913 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#![no_std]
#![no_main]
#![allow(unsafe_code)]

use core::panic::PanicInfo;
use rsnix::uefi::*;

extern crate alloc;

// ---------------------------------------------------------------------------
// Panic handler
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Panic handler
// ---------------------------------------------------------------------------

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    use core::fmt::Write;

    // A background task (id >= 2) panicked: die gracefully — log it,
    // mark the task done, switch away.  The shell keeps running and
    // `jobs` shows the corpse.  Panics in the shell, idle, ISR context,
    // or before the scheduler exists still halt the whole system.
    if rsnix::sched::is_ready() && !rsnix::sched::in_isr() && rsnix::sched::current() >= 2 {
        let mut buf = [0u8; 192];
        let n = {
            let mut w = rsnix::strbuf::FmtBuf::new(&mut buf);
            let _ = write!(&mut w, "{}", info.message());
            if let Some(loc) = info.location() {
                let _ = write!(&mut w, " at {}:{}", loc.file(), loc.line());
            }
            w.len()
        };
        let msg = core::str::from_utf8(&buf[..n]).unwrap_or("task panic");
        rsnix::sched::abort_current(msg);
    }

    rsnix::serial::write_str("\r\n*** PANIC ***\r\n");
    let _ = write!(&mut rsnix::serial::SerialWriter, "{}\r\n", info.message());
    if let Some(loc) = info.location() {
        let _ = write!(
            &mut rsnix::serial::SerialWriter,
            "  at {}:{}\r\n",
            loc.file(),
            loc.line()
        );
    }
    // Real hardware has no serial console — put the panic on the screen
    // too (white-on-red band), so a pre-shell panic is not a silent
    // blank screen.  The last boot stage is appended so the user can
    // see how far boot got before the crash.
    let mut loc_buf = [0u8; 96];
    let mut msg_buf = [0u8; 128];
    let mut stage_buf = [0u8; 96];
    let loc_n = {
        let mut w = rsnix::strbuf::FmtBuf::new(&mut loc_buf);
        if let Some(loc) = info.location() {
            let _ = write!(&mut w, "at {}:{}", loc.file(), loc.line());
        } else {
            let _ = write!(&mut w, "(no location)");
        }
        w.len()
    };
    let msg_n = {
        let mut w = rsnix::strbuf::FmtBuf::new(&mut msg_buf);
        let _ = write!(&mut w, "{}", info.message());
        w.len()
    };
    let stage_n = {
        let s = rsnix::gop::last_boot_stage();
        let n = s.len().min(stage_buf.len());
        stage_buf[..n].copy_from_slice(&s.as_bytes()[..n]);
        n
    };
    let lines = [
        "*** PANIC ***",
        core::str::from_utf8(&msg_buf[..msg_n]).unwrap_or("?"),
        core::str::from_utf8(&loc_buf[..loc_n]).unwrap_or("?"),
        core::str::from_utf8(&stage_buf[..stage_n]).unwrap_or(""),
    ];
    rsnix::gop::dump_lines(&lines);
    // Persist to the disk so the report survives the reboot on real
    // hardware (no serial console).  Best-effort; heap-free lines.
    rsnix::fs::write_crash_log(&lines);
    loop {
        unsafe {
            core::arch::asm!("cli; hlt");
        }
    }
}

// ---------------------------------------------------------------------------
// EFI entry point
// ---------------------------------------------------------------------------
/// EFI entry point.
///
/// # Safety
///
/// The firmware hands us raw pointers (image handle, system table) that
/// must remain valid for the lifetime of the call — a contract guaranteed
/// by the UEFI loader.
#[unsafe(no_mangle)]
pub unsafe extern "efiapi" fn efi_main(image_handle: Handle, system_table: *mut SystemTable) -> ! {
    let st = unsafe { &mut *system_table };
    let bs = unsafe { &mut *st.boot_services };
    let con_out = unsafe { &mut *st.con_out };

    // Keep the runtime-services table for later (ResetSystem → poweroff).
    rsnix::power::init(st.runtime_services);

    // Capture the kernel's own image range BEFORE ExitBootServices: the
    // heap and page allocators must never hand out the running kernel's
    // code/data/bss pages (a heap allocation landing on the .bss corrupts
    // statics like the FAT ACTIVE_VOL — observed as a dead filesystem in
    // the fault path).
    unsafe {
        let mut li: *mut core::ffi::c_void = core::ptr::null_mut();
        let li_guid = rsnix::uefi::EFI_LOADED_IMAGE_PROTOCOL_GUID;
        if (bs.handle_protocol)(image_handle, &li_guid as *const rsnix::uefi::Guid, &mut li)
            == rsnix::uefi::EFI_SUCCESS
            && !li.is_null()
        {
            let p = &*(li as *const rsnix::uefi::LoadedImageProtocol);
            rsnix::memory::set_kernel_image_range(p.image_base as usize, p.image_size as usize);
            rsnix::serial_println!(
                "mem: kernel image 0x{:x}..0x{:x} ({} KiB) reserved",
                p.image_base as usize,
                p.image_base as usize + p.image_size as usize,
                p.image_size as usize / 1024
            );
        } else {
            rsnix::serial_println!("mem: WARNING — kernel image range unknown");
        }
    }

    // ---- Phase 1: UEFI boot services alive ----

    // Print banner via UEFI console
    unsafe {
        let s = concat!("rsnix v", env!("CARGO_PKG_VERSION"), " booting..\n");
        let bytes = s.as_bytes();
        let mut buf: [u16; 48] = [0; 48];
        for (i, &b) in bytes.iter().enumerate().take(47) {
            buf[i] = b as u16;
        }
        (con_out.output_string)(con_out, buf.as_ptr());
    }

    rsnix::serial::init();
    rsnix::serial_println!("=== rsnix boot ===");

    // Locate GOP (Graphics Output Protocol) *before* the memory map is
    // captured: the heap/page allocators need to know the framebuffer
    // region so they never hand out its pages (some real firmware lists
    // it as conventional memory).
    let mut gop_interface: *mut core::ffi::c_void = core::ptr::null_mut();
    let gop_guid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
    let gop_result = unsafe {
        (bs.locate_protocol)(
            &gop_guid as *const Guid,
            core::ptr::null_mut(),
            &mut gop_interface,
        )
    };
    if gop_result == EFI_SUCCESS {
        let gop = unsafe { &mut *(gop_interface as *mut GraphicsOutputProtocol) };
        rsnix::gop::peek_fb_region(gop);
    }

    // Stash the memory map
    let map_key = match rsnix::memory::capture_memory_map(bs) {
        Ok(k) => k,
        Err(e) => {
            rsnix::serial_println!("mem: capture_memory_map failed 0x{:x}", e);
            0
        }
    };

    if gop_result == EFI_SUCCESS {
        let gop = unsafe { &mut *(gop_interface as *mut GraphicsOutputProtocol) };
        rsnix::serial_println!("gop: framebuffer found");
        rsnix::gop::init(gop);
    } else {
        rsnix::serial_println!("gop: not found (0x{:x})", gop_result);
    }
    rsnix::gop::boot_marker("rsnix v0.5.9 booting..");
    rsnix::vt::init();
    let (rows, cols) = rsnix::vt::size();
    rsnix::serial_println!("vt: terminal ready ({}x{})", rows, cols);
    let (fw, fh) = rsnix::gop::pixel_dims();
    rsnix::gop::boot_marker(&alloc::format!(
        "rsnix: gop {}x{} vt {}x{} ok",
        fw,
        fh,
        cols,
        rows
    ));
    if let Some((ib, ie)) = rsnix::memory::kernel_image_range() {
        rsnix::gop::boot_marker(&alloc::format!(
            "rsnix: img 0x{:x}-0x{:x} ({} KiB)",
            ib,
            ie,
            (ie - ib) / 1024
        ));
    }

    // ExitBootServices — we now own the machine
    // DEBUG (OptiPlex sim): corrupt the first key so EBS fails once and
    // the retry path (capture_memory_map -> init_heap rebuild) runs — the
    // exact condition that wiped the pre-EBS shadow on real hardware.
    let ebs_first_key = if rsnix::memory::simulate_ebs_failure() {
        map_key ^ 1
    } else {
        map_key
    };
    if unsafe { (bs.exit_boot_services)(image_handle, ebs_first_key) } != EFI_SUCCESS {
        rsnix::serial_println!("WARN: ExitBootServices failed, retrying...");
        match unsafe { rsnix::memory::refresh_and_exit(bs, image_handle) } {
            Ok(_) => {}
            Err(e) => {
                rsnix::serial_println!("FATAL: cannot ExitBootServices (0x{:x})", e);
                loop {
                    unsafe {
                        core::arch::asm!("cli; hlt");
                    }
                }
            }
        }
    }

    // ---- Phase 2: Native mode ----
    rsnix::serial::init();
    rsnix::serial_println!("serial: COM1 115200 8N1");
    rsnix::ps2::init();
    rsnix::serial_println!("ps2: keyboard initialized");
    if rsnix::ps2::mouse_init() {
        rsnix::serial_println!("ps2: mouse ready (IRQ12, stream mode)");
    } else {
        rsnix::serial_println!("ps2: mouse not present");
    }
    if rsnix::gdt::init() {
        rsnix::serial_println!("gdt: own GDT + TSS (IST: page-fault/double-fault)");
    } else {
        rsnix::serial_println!("gdt: kept UEFI GDT (IST fault stacks off)");
    }
    rsnix::interrupts::init();
    rsnix::serial_println!("intr: IDT loaded, PIC remapped, timer ~100 Hz");
    rsnix::gop::boot_marker("rsnix: serial+ps2+gdt+intr ok");

    dump_memory_summary();

    if rsnix::memory::self_test() {
        let hs = rsnix::memory::heap_stats();
        rsnix::gop::boot_marker(&alloc::format!(
            "rsnix: heap 0x{:x}-0x{:x} ({} MiB) ok",
            hs.heap_start,
            hs.heap_end,
            hs.heap_size / 1024 / 1024
        ));
        rsnix::serial_println!(
            "heap: self-test OK (0x{:x}..0x{:x} {} KiB free={} KiB)",
            hs.heap_start,
            hs.heap_end,
            hs.heap_size / 1024,
            hs.free_bytes / 1024
        );
    } else {
        rsnix::serial_println!("heap: self-test FAILED");
    }

    if rsnix::memory::init_page_allocator() {
        rsnix::serial_println!("pages: bitmap allocator ready");
    } else {
        rsnix::serial_println!("pages: init FAILED");
    }
    rsnix::gop::boot_marker("rsnix: shadow ok");
    if rsnix::memory::page_self_test() {
        rsnix::serial_println!("pages: self-test OK (alloc/free/runs)");
    } else {
        rsnix::serial_println!("pages: self-test FAILED");
    }

    if rsnix::paging::adopt_tables() {
        rsnix::serial_println!(
            "pg: adopted own page tables (cr3={:#x})",
            rsnix::paging::cr3()
        );
    } else {
        rsnix::serial_println!("pg: adopt_tables FAILED");
    }

    if rsnix::paging::self_test() {
        rsnix::serial_println!("pg: self-test OK (map/unmap/split)");
    } else {
        rsnix::serial_println!("pg: self-test FAILED");
    }

    // Scheduler init needs the page allocator (idle task's stack + guard
    // page) and the adopted page tables, so it runs after the memory
    // subsystem is fully up.  The tick (interrupts::init) is already
    // live, which is what `sleep`/wake scheduling depends on.
    rsnix::sched::init();

    let t = rsnix::rtc::now();
    rsnix::serial_println!(
        "rtc: {}-{:02}-{:02} {:02}:{:02}:{:02}",
        t.year,
        t.month,
        t.day,
        t.hour,
        t.minute,
        t.second
    );
    let devices = rsnix::pci::probe();
    rsnix::serial_println!("pci: {} device(s) on all buses", devices.len());

    // Disk: AHCI SATA driver, then mount every FAT32 volume under /disk/<UID>/.
    if !rsnix::ahci::init() {
        rsnix::serial_println!("ahci: no disk attached");
    }
    rsnix::gop::boot_marker(&alloc::format!(
        "rsnix: ahci {} disk(s)",
        rsnix::ahci::disk_count()
    ));
    rsnix::fat::init(); // prints one line per mounted volume
    rsnix::gop::boot_marker(&alloc::format!(
        "rsnix: fat {} volume(s) mounted",
        rsnix::fat::volume_count()
    ));

    let (dirs, files) = rsnix::fs::init();
    rsnix::serial_println!("fs: vfs ready — {} dirs, {} files", dirs, files);
    let fstest = rsnix::fs::self_test();
    if fstest {
        rsnix::serial_println!("fs: self-test OK (create/read/write/remove)");
    } else {
        rsnix::serial_println!("fs: self-test FAILED");
    }
    rsnix::gop::boot_marker(&alloc::format!(
        "rsnix: fs ok {} dirs/{} files self-test {}",
        dirs,
        files,
        if fstest { "ok" } else { "FAILED" }
    ));

    rsnix::serial_println!("boot: entering shell");
    rsnix::gop::boot_marker("rsnix: boot done — shell");
    if rsnix::ps2::mouse_present() {
        rsnix::cursor::spawn();
    } else {
        rsnix::serial_println!("cursor: no mouse — overlay disabled");
    }
    // Shell-entry self-check: verify the vt grid structs are sane right
    // before the shell's first print.  The OptiPlex crashes in the first
    // banner write when the cells VecData (or the shadow) holds the
    // firmware's 0xAA fill instead of real values — this line shows
    // whether the corruption is already present at shell entry or lands
    // later, and prints the exact field values when it is.
    rsnix::vt::debug_verify();

    shell::run();
}

// ---------------------------------------------------------------------------
// Print a memory summary from the stashed memory map
// ---------------------------------------------------------------------------
fn dump_memory_summary() {
    let (map, key) = rsnix::memory::get_map();
    let mut conventional_4k = 0u64;
    let mut addr_space_4k = 0u64;
    for desc in map.iter() {
        let pages = desc.number_of_pages;
        addr_space_4k += pages;
        if desc.kind == 7 {
            conventional_4k += pages;
        }
    }
    rsnix::serial_println!(
        "mem: {} entries, key=0x{:x}, usable: {} KB ({} MB)",
        map.len(),
        key,
        conventional_4k * 4,
        (conventional_4k * 4) / 1024,
    );
    rsnix::serial_println!(
        "mem: address space: {} MB (incl. PCIe MMIO)",
        (addr_space_4k * 4) / 1024,
    );
}