ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(os::test_runner)]
#![reexport_test_harness_main = "test_main"]

use core::arch::global_asm;
use core::panic::PanicInfo;
use os::event_log;
use os::println;

// ── Assembly entry point ─────────────────────────────────────────

global_asm!(
    ".section .text.entry",
    ".globl _start",
    "_start:",
    "   la sp, stack_end",
    "   la t0, bss_start",
    "   la t1, bss_end",
    "1:",
    "   bgeu t0, t1, 2f",
    "   sd zero, (t0)",
    "   addi t0, t0, 8",
    "   j 1b",
    "2:",
    "   call kernel_main",
    "3:",
    "   wfi",
    "   j 3b",
);

// ── Panic handlers ───────────────────────────────────────────────

#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    println!("{}", info);
    println!("[EventLog] Draining kernel events...");
    event_log::drain_to_serial();
    println!("[EventLog] Events drained successfully");
    os::hlt_loop();
}

#[cfg(test)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    os::test_panic_handler(info)
}

// ── Subsystem initialisation ─────────────────────────────────────

extern crate alloc;
use alloc::sync::Arc;
use alloc::{boxed::Box, rc::Rc, vec, vec::Vec};
use spin::Mutex;

/// One-shot kernel init: interrupt vector, memory manager, heap.
fn init_kernel() {
    use os::allocator;
    use os::memory;

    os::init();

    extern "C" {
        static kernel_end: u8;
    }
    let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };
    let mut memory_manager = memory::init(kernel_end_addr);
    allocator::init_heap(&mut memory_manager.frame_allocator).expect("heap initialization failed");
    os::fs::init_filesystem();
}

// ── PTA experiment 0: visualization sandbox ─────────────────────

fn run_pta_lab0_visualization_demo() {
    use event_log::KernelEventField as Field;

    event_log::emit_structured(
        event_log::EventKind::Boot,
        "realtime demo started",
        vec![
            Field::u64("seq", 1),
            Field::str("module", "boot"),
            Field::str("phase", "start"),
            Field::str("source_step", "boot.start"),
        ],
    );
    event_log::emit_structured(
        event_log::EventKind::MemoryAlloc,
        "demo frame allocated",
        vec![
            Field::u64("seq", 2),
            Field::str("module", "memory"),
            Field::str("phase", "frame_allocate"),
            Field::u64("addr", 2149789696),
            Field::u64("size", 4096),
            Field::str("name", "kernel_frame"),
            Field::str("source_step", "memory.frame_allocate"),
        ],
    );
    event_log::emit_structured(
        event_log::EventKind::ProcessCreate,
        "demo init process created",
        vec![
            Field::u64("seq", 3),
            Field::str("module", "process"),
            Field::str("phase", "create"),
            Field::u64("pid", 1),
            Field::str("name", "init"),
            Field::str("source_step", "process.create"),
        ],
    );
    event_log::emit_structured(
        event_log::EventKind::ProcessStateChange,
        "demo init scheduled",
        vec![
            Field::u64("seq", 4),
            Field::str("module", "process"),
            Field::str("phase", "schedule"),
            Field::u64("pid", 1),
            Field::str("name", "init"),
            Field::str("state", "Running"),
            Field::str("source_step", "process.schedule"),
        ],
    );
    event_log::emit_structured(
        event_log::EventKind::FsMount,
        "demo ramfs mounted",
        vec![
            Field::u64("seq", 5),
            Field::str("module", "fs"),
            Field::str("phase", "mount"),
            Field::str("path", "/"),
            Field::str("fs", "ramfs"),
            Field::str("source_step", "fs.mount"),
        ],
    );
    event_log::emit_structured(
        event_log::EventKind::FsWrite,
        "demo file write",
        vec![
            Field::u64("seq", 6),
            Field::str("module", "fs"),
            Field::str("phase", "write"),
            Field::str("path", "/hello.txt"),
            Field::u64("size", 13),
            Field::str("source_step", "fs.write"),
        ],
    );
}

// ── Chapter 3: heap tests ────────────────────────────────────────

fn test_heap_allocations() {
    println!("[Memory] Memory and heap initialized");

    event_log::emit(event_log::EventKind::Boot, "AhRightOS kernel started");
    event_log::emit(
        event_log::EventKind::MemoryAlloc,
        "heap_initialized size=1MB",
    );

    let heap_value = Box::new(41);
    event_log::emit(event_log::EventKind::MemoryAlloc, "heap_box_test value=41");
    println!("[Memory] Heap allocation test: value at {:p}", heap_value);

    let mut vec = Vec::new();
    for i in 0..100 {
        vec.push(i);
    }
    event_log::emit(event_log::EventKind::MemoryAlloc, "heap_vec_test count=100");
    println!(
        "[Memory] Vec allocation test: {} elements at {:p}",
        vec.len(),
        vec.as_slice()
    );

    let reference_counted = Rc::new(vec![1, 2, 3]);
    let cloned_reference = reference_counted.clone();
    println!(
        "[Memory] Rc test: reference count = {}",
        Rc::strong_count(&cloned_reference)
    );
    core::mem::drop(reference_counted);
    println!(
        "[Memory] After drop: reference count = {}",
        Rc::strong_count(&cloned_reference)
    );
}

// ── Chapter 6: process management tests ──────────────────────────

fn test_process_management() {
    println!("\n[Chapter 6] Process Management");

    use os::process::ProcessId;
    let pid1 = ProcessId::new();
    let pid2 = ProcessId::new();
    let pid3 = ProcessId::new();
    event_log::emit(event_log::EventKind::ProcessCreate, "pid_allocator_init");
    println!(
        "  PID Allocator: allocated PIDs {}, {}, {}",
        pid1, pid2, pid3
    );

    use os::process::ProcessState;
    let ready = ProcessState::Ready;
    let running = ProcessState::Running;
    println!(
        "  Process State: Ready can schedule = {}",
        ready.can_schedule()
    );
    println!(
        "  Process State: Ready -> Running valid = {}",
        ready.can_transition_to(running)
    );

    use os::process::ProcessContext;
    let mut ctx = ProcessContext::new();
    ctx.set_ra(0x80200000);
    ctx.set_sp(0x80300000);
    println!("  Process Context: RA={:#x}, SP={:#x}", ctx.ra(), ctx.sp());

    use os::process::ProcessControlBlock;
    let mut pcb1 = ProcessControlBlock::new(pid1, "init", None);
    let _pcb2 = ProcessControlBlock::new(pid2, "shell", Some(pid1));
    pcb1.add_child(pid2);
    pcb1.set_state(ProcessState::Running)
        .expect("ready process can enter running state");
    event_log::emit(
        event_log::EventKind::ProcessCreate,
        "pcb_init_pid1 name=init",
    );
    event_log::emit(
        event_log::EventKind::ProcessCreate,
        "pcb_shell_pid2 parent=init",
    );
    println!(
        "  PCB: process '{}' (PID {}) with {} children",
        pcb1.name(),
        pcb1.pid(),
        pcb1.children().len()
    );

    use os::process::RoundRobinScheduler;
    let mut scheduler = RoundRobinScheduler::new(10);
    let p1 = ProcessId::new();
    let p2 = ProcessId::new();
    let proc1 = alloc::boxed::Box::new(ProcessControlBlock::new(p1, "proc1", None));
    let proc2 = alloc::boxed::Box::new(ProcessControlBlock::new(p2, "proc2", None));
    let _ = scheduler.add_process(proc1);
    let _ = scheduler.add_process(proc2);
    scheduler.schedule();
    println!("  Scheduler: initialized with 2 processes, round-robin scheduling");
}

// ── Chapter 7: VFS + RamFS tests ─────────────────────────────────

fn test_vfs_and_ramfs() {
    println!("\n[Chapter 7] File System");

    use os::fs::*;

    let _seek_start = SeekFrom::Start(0);
    println!("  VFS: SeekFrom created");
    println!("  VFS: Permission S_IRUSR = {:#o}", permissions::S_IRUSR);

    let inode = MemInode::new_file(1);
    println!("  VFS: MemInode created with ino = {}", inode.ino());
    println!("  VFS: FileDescriptorTable created");

    let _stdout = Stdout::new();
    println!("  VFS: Stdout created");

    // RamInode read/write
    let mut ram_inode = RamInode::new_file(1);
    let write_data = b"Hello, RamFS!";
    match ram_inode.write_at(0, write_data) {
        Ok(n) => {
            println!("  RamFS: Written {} bytes to inode #{}", n, ram_inode.ino());
            let mut read_buf = [0u8; 13];
            if let Ok(n) = ram_inode.read_at(0, &mut read_buf) {
                println!(
                    "  RamFS: Read {} bytes, data verified = {}",
                    n,
                    &read_buf == write_data
                );
            }
        }
        Err(e) => println!("  RamFS: Write failed: {:?}", e),
    }

    // Directory operations
    let mut dir = RamInode::new_directory(2);
    let file1 = Arc::new(Mutex::new(RamInode::new_file(3)));
    let file2 = Arc::new(Mutex::new(RamInode::new_file(4)));
    dir.add_entry("readme.txt".into(), file1.clone())
        .map(|_| println!("  RamFS: Added 'readme.txt' to directory"))
        .unwrap_or_else(|e| println!("  RamFS: Failed: {:?}", e));
    dir.add_entry("test.txt".into(), file2)
        .map(|_| println!("  RamFS: Added 'test.txt' to directory"))
        .unwrap_or_else(|e| println!("  RamFS: Failed: {:?}", e));

    // RamFile seek
    let file_inode = Arc::new(Mutex::new(RamInode::new_file(5)));
    let mut file = RamFile::new(file_inode.clone());
    println!(
        "  RamFS: RamFile created with inode #{}",
        file_inode.lock().ino()
    );
    if let Ok(n) = file.write(b"Test data") {
        println!("  RamFS: RamFile wrote {} bytes", n);
    }
    if let Ok(new_pos) = file.seek(SeekFrom::Start(0)) {
        println!("  RamFS: Seeked to position {}", new_pos);
    }

    // Full RamFS workflow
    let fs = RamFS::new();
    println!("  RamFS: File system created");
    let root = fs.root();

    if let Ok(file_inode) = fs.create_file(root.clone(), "hello.txt".into()) {
        let mut locked = file_inode.lock();
        locked
            .write_at(0, b"Hello, World!")
            .map(|_| println!("  RamFS: Created and wrote to 'hello.txt'"))
            .ok();
    }

    if let Ok(dir_inode) = fs.create_directory(root.clone(), "docs".into()) {
        println!("  RamFS: Created directory 'docs'");
        if let Ok(sub_file) = fs.create_file(dir_inode.clone(), "readme.md".into()) {
            let mut locked = sub_file.lock();
            locked
                .write_at(0, b"# Documentation")
                .map(|_| println!("  RamFS: Created 'docs/readme.md'"))
                .ok();
        }
    }
}

// ── Chapter 7+: BlkFS with BlockCache & syscall integration ──────

fn test_blkfs_with_syscalls() {
    println!("\n========================================");
    println!("  All system components initialized!");
    println!("========================================\n");

    println!("[Chapter 7+] Persistent Block File System (BlkFS) with BlockCache & Syscalls");
    use alloc::sync::Arc;
    use os::fs::{BlkFsMountOptions, BlockCache, BlockDevice, DummyBlockDev};

    // Disable timer interrupts during VirtIO polling
    unsafe {
        riscv::register::sie::clear_stimer();
    }

    // Probe VirtIO, but never implicitly format a real disk for the demo.  If
    // the image already contains AhRightOS BlkFS we mount it open-only; otherwise
    // fall back to a RAM-backed teaching device so the syscall write/read demo
    // remains deterministic.
    let cached_dev: Arc<BlockCache>;
    if let Some(virtio) = os::block::VirtioBlkDev::probe() {
        println!(
            "  BlkFS: Found VirtIO block device ({} blocks x {} bytes = {} MB)",
            virtio.block_count(),
            512,
            virtio.block_count() * 512 / (1024 * 1024)
        );
        event_log::emit(event_log::EventKind::FsMount, "virtio_blk found");
        let candidate = Arc::new(BlockCache::new(Arc::new(virtio) as Arc<dyn BlockDevice>));
        let mounted = os::fs::FS_MANAGER
            .lock()
            .mount_blkfs_with_options(
                "/mnt",
                Arc::clone(&candidate) as Arc<dyn BlockDevice>,
                BlkFsMountOptions::open_only(),
            )
            .is_ok();
        if mounted {
            cached_dev = candidate;
            println!("  BlkFS: Mounted existing VirtIO AhRightOS BlkFS at /mnt (open-only)");
        } else {
            println!(
                "  BlkFS: VirtIO image has no existing AhRightOS BlkFS; using DummyBlockDev for writable demo"
            );
            println!("  BlkFS: Initialize real images explicitly with sys_mount(\"/mnt?device=virtio&mode=format\")");
            let dummy = Arc::new(DummyBlockDev::new(512)) as Arc<dyn BlockDevice>;
            cached_dev = Arc::new(BlockCache::new(dummy));
            os::fs::FS_MANAGER
                .lock()
                .mount_blkfs(
                    "/mnt",
                    Arc::clone(&cached_dev) as Arc<dyn os::fs::BlockDevice>,
                )
                .expect("BlkFS: Failed to mount dummy device at /mnt");
            println!("  BlkFS: Mounted DummyBlockDev at /mnt");
        }
    } else {
        println!(
            "  BlkFS: No VirtIO device, using DummyBlockDev (512 blocks x 512 bytes = 256 KB)"
        );
        let dummy = Arc::new(DummyBlockDev::new(512)) as Arc<dyn BlockDevice>;
        cached_dev = Arc::new(BlockCache::new(dummy));
        os::fs::FS_MANAGER
            .lock()
            .mount_blkfs(
                "/mnt",
                Arc::clone(&cached_dev) as Arc<dyn os::fs::BlockDevice>,
            )
            .expect("BlkFS: Failed to mount dummy device at /mnt");
        println!("  BlkFS: Mounted DummyBlockDev at /mnt");
    }
    println!("  BlkFS: BlockCache enabled (64-block LRU write-back)");

    // ── Syscall-path tests ───────────────────────────────────

    use os::syscall::syscall_impl::open_flags;
    use os::syscall::syscall_impl::*;

    // 1. Create file
    let path_str = "/mnt/hello.txt\0";
    let fd = sys_open(
        path_str.as_ptr() as usize,
        open_flags::O_RDWR | open_flags::O_CREAT,
    );
    assert!(fd >= 0, "sys_open CREATE failed");
    println!("  Syscall: open('/mnt/hello.txt', O_CREAT) → fd={}", fd);

    // 2. Write
    let write_data = b"Hello from syscall path!\n";
    let nw = sys_write(fd as usize, write_data.as_ptr(), write_data.len());
    assert_eq!(nw, write_data.len() as isize);
    event_log::emit(
        event_log::EventKind::FsWrite,
        "syscall_write file=hello.txt",
    );
    println!(
        "  Syscall: write(fd={}, len={}) → {} bytes",
        fd,
        write_data.len(),
        nw
    );

    // 3. Close
    assert_eq!(sys_close(fd as usize), 0);
    println!("  Syscall: close(fd={}) → OK", fd);

    // 4. Re-open and read back
    let fd2 = sys_open(path_str.as_ptr() as usize, open_flags::O_RDONLY);
    assert!(fd2 >= 0, "sys_open READ failed");
    let mut read_buf = [0u8; 64];
    let nr = sys_read(fd2 as usize, read_buf.as_mut_ptr() as usize, read_buf.len());
    assert!(nr > 0, "sys_read empty");
    let content = core::str::from_utf8(&read_buf[..nr as usize]).unwrap_or("<utf8 err>");
    println!(
        "  Syscall: read(fd={}) → {} bytes: {}",
        fd2,
        nr,
        content.trim()
    );
    assert_eq!(sys_close(fd2 as usize), 0);

    // 5. Create directory via syscall
    let dir_path = "/mnt/subdir\0";
    assert_eq!(sys_mkdir(dir_path.as_ptr() as usize), 0);
    println!("  Syscall: mkdir('/mnt/subdir') → OK");

    // 6. Persistence check (simulate reboot)
    {
        let blkfs = os::fs::BlkFS::open(Arc::clone(&cached_dev) as Arc<dyn os::fs::BlockDevice>)
            .expect("BlkFS: persistence check failed");
        let root = blkfs.root_inode().expect("root inode");
        let entries = root.list_entries().expect("list entries");
        println!("  BlkFS: Root entries after re-open: {:?}", entries);
        assert!(
            entries.iter().any(|e| e == "hello.txt"),
            "hello.txt should persist"
        );
        assert!(
            entries.iter().any(|e| e == "subdir"),
            "subdir should persist"
        );
    }
    println!("  BlkFS: Persistence verified (data survived re-open)");

    // 7. Cache statistics
    let cache_stats = cached_dev.stats_snapshot();
    let total = cache_stats.total_reads();
    if total > 0 {
        println!(
            "  BlockCache: {} hits / {} total ({}% hit rate, cached={}, dirty={})",
            cache_stats.hits,
            total,
            cache_stats.hit_rate_percent(),
            cache_stats.cached_blocks,
            cache_stats.dirty_blocks,
        );
    }

    println!("  BlkFS: All syscall-integrated tests passed!");

    unsafe {
        riscv::register::sie::clear_stimer();
    }
}

// ── G5: Extended system call tests ───────────────────────────────

fn test_extended_syscalls() {
    println!("\n[G5] Extended System Calls");

    use os::syscall::syscall_impl::open_flags;
    use os::syscall::syscall_impl::*;

    // --- lseek ---
    let path = "/mnt/lseek_test\0";
    let fd = sys_open(
        path.as_ptr() as usize,
        open_flags::O_RDWR | open_flags::O_CREAT,
    );
    assert!(fd >= 0, "lseek: open failed");
    let data = b"ABCDEFGHIJKLMNOP";
    sys_write(fd as usize, data.as_ptr(), data.len());
    let pos = sys_lseek(fd as usize, 0, 0); // SEEK_SET
    assert_eq!(pos, 0);
    println!("  Syscall: lseek(fd={}, SEEK_SET) -> {}", fd, pos);
    let pos2 = sys_lseek(fd as usize, 0, 2); // SEEK_END
    assert_eq!(pos2, data.len() as isize);
    println!("  Syscall: lseek(fd={}, SEEK_END) -> {}", fd, pos2);
    sys_close(fd as usize);

    // --- stat ---
    let stat_ret = sys_stat(path.as_ptr() as usize, 0); // null buf should fail
    assert_eq!(stat_ret, -1);
    // stat with valid buffer
    let mut stat_buf = [0u8; 128];
    let r = sys_stat(path.as_ptr() as usize, stat_buf.as_mut_ptr() as usize);
    assert_eq!(r, 0, "stat should succeed");
    println!("  Syscall: stat('{}') -> OK", path.trim_end_matches('\0'));

    // --- getdents / readdir ---
    let dir_buf = [0u8; 512];
    let nr = sys_getdents(
        c"/mnt".as_ptr() as usize,
        dir_buf.as_ptr() as usize,
        dir_buf.len(),
    );
    assert!(nr > 0, "getdents should return entries");
    let listing = core::str::from_utf8(&dir_buf[..nr as usize]).unwrap_or("<err>");
    println!(
        "  Syscall: getdents('/mnt') -> {} bytes\n    {}",
        nr,
        listing.replace('\n', ", ")
    );

    // --- unlink ---
    let unlink_path = "/mnt/unlink_me\0";
    let fd_u = sys_open(
        unlink_path.as_ptr() as usize,
        open_flags::O_RDWR | open_flags::O_CREAT,
    );
    assert!(fd_u >= 0, "unlink: create failed");
    sys_close(fd_u as usize);
    let r = sys_unlink(unlink_path.as_ptr() as usize);
    assert_eq!(r, 0, "unlink should succeed");
    println!(
        "  Syscall: unlink('{}') -> OK",
        unlink_path.trim_end_matches('\0')
    );
    // Verify it's gone by trying to open it
    let fd_gone = sys_open(unlink_path.as_ptr() as usize, open_flags::O_RDONLY);
    assert!(fd_gone < 0, "unlinked file should not exist");
    println!(
        "  Syscall: open(unlinked file) -> {} (expected error)",
        fd_gone
    );

    // --- dup2 ---
    let path_dup = "/mnt/dup_test\0";
    let fd_d = sys_open(
        path_dup.as_ptr() as usize,
        open_flags::O_RDWR | open_flags::O_CREAT,
    );
    assert!(fd_d >= 0);
    sys_write(fd_d as usize, b"hello dup2\n".as_ptr(), 10);
    let new_fd = sys_dup2(fd_d as usize, 10);
    assert_eq!(new_fd, 10);
    println!("  Syscall: dup2(fd={}, 10) -> {}", fd_d, new_fd);
    // Read from dup'd fd — should seek to 0 first via lseek
    sys_lseek(10, 0, 0);
    let mut dup_buf = [0u8; 32];
    let nr_dup = sys_read(10, dup_buf.as_mut_ptr() as usize, 10);
    assert_eq!(nr_dup, 10);
    let content = core::str::from_utf8(&dup_buf[..10]).unwrap_or("<err>");
    println!("  Syscall: read(dup_fd=10) -> '{}'", content.trim());
    sys_close(fd_d as usize);
    // dup'd fd should remain valid until closed
    sys_close(10);

    println!("  G5: All extended syscall tests passed!");
}

// ── Multi-tasking test (kernel + user) ───────────────────────────

/// Task stack (16-byte aligned per RISC-V ABI)
#[repr(align(16))]
struct TaskStack([u8; 4096]);

static mut SHELL_STACK: TaskStack = TaskStack([0u8; 4096]);
static mut TASK_B_STACK: TaskStack = TaskStack([0u8; 4096]);

extern "C" fn shell_entry() -> ! {
    os::shell::shell_main();
}

extern "C" fn task_b() -> ! {
    let mut count = 0u64;
    loop {
        count = count.wrapping_add(1);
        if count.is_multiple_of(500_000) {
            os::serial_print!("B");
        }
    }
}

fn start_multitasking_with_user() {
    println!("\n========================================");
    println!("  Chapter 8: User Mode + Fork Test");
    println!("========================================\n");

    unsafe {
        riscv::register::sstatus::clear_sie();
        riscv::register::sie::clear_stimer();
    }

    use os::process::{self, ProcessId};

    extern "C" {
        static kernel_end: u8;
    }
    let kernel_end_addr = unsafe { &kernel_end as *const u8 as usize };

    // Single allocator for all page-table work (boot + fork/exec at runtime)
    process::init_frame_allocator_from(kernel_end_addr);

    // --- Create kernel address space ---
    println!("[KERNEL] Creating kernel address space (Sv39)...");
    let kernel_page_table_paddr = process::with_frame_allocator(|a| {
        let space =
            os::memory::create_kernel_address_space(a).expect("create kernel address space");
        let paddr = space.page_table_paddr();
        space.activate();
        paddr
    });
    println!(
        "[KERNEL] Kernel page table at {:#x}, Sv39 active",
        kernel_page_table_paddr.as_usize()
    );
    process::set_kernel_page_table_paddr(kernel_page_table_paddr);

    // --- Build fork-test user ELF ---
    println!("[USER] Building fork-test user ELF...");
    let (elf_bytes, entry) = process::user_elf::build_fork_test_elf();
    let elf = process::elf::Elf::parse(&elf_bytes).expect("parse fork-test ELF");

    // --- Create user address space ---
    let user_satp = process::with_frame_allocator(|a| {
        let space =
            process::user::create_user_address_space(&elf, &elf_bytes, a, kernel_page_table_paddr)
                .expect("create user address space");
        (8usize << 60) | (space.page_table_paddr().as_usize() >> 12)
    });

    println!("[USER] User address space created, satp={:#x}", user_satp);

    // --- Step 5: Create user task ---
    let user_stack_top = 0x7FFF_F000usize;
    let user_task = process::user::create_user_task(
        ProcessId::new(),
        "user_init",
        entry,
        user_stack_top,
        user_satp,
    );
    println!("[USER] User task 'user_init' created, entry={:#x}", entry);

    // let current_frontier = allocator.next_frame();
    // process::init_frame_allocator_at(current_frontier);
    // println!("[KERNEL] Global frame allocator synced at frame {}", current_frontier);

    let shell_pcb = unsafe {
        process::create_kernel_task(
            ProcessId::new(),
            "shell",
            shell_entry,
            &raw mut SHELL_STACK.0,
        )
    };
    let task_b_pcb = unsafe {
        process::create_kernel_task(ProcessId::new(), "task_b", task_b, &raw mut TASK_B_STACK.0)
    };

    // --- Step 6: Register with scheduler and bootstrap ---
    {
        let mut sched = process::SCHEDULER.lock();
        sched.add_process(shell_pcb).expect("add shell");
        sched.add_process(task_b_pcb).expect("add task_b");
        sched.add_process(user_task).expect("add user_init");
        sched.schedule();
    }

    // Re-enable timer interrupts
    unsafe {
        riscv::register::sie::set_stimer();
    }

    println!("  Scheduler: 3 tasks (2 kernel + 1 user). Starting round-robin...");

    // Bootstrap — this NEVER returns
    let first_ctx = {
        let sched = process::SCHEDULER.lock();
        let current = sched.current().expect("no current task");
        current.context() as *const process::ProcessContext
    };

    unsafe { process::start_first_task(first_ctx) };
}

// ── Main entry ───────────────────────────────────────────────────

#[no_mangle]
pub extern "C" fn kernel_main() -> ! {
    println!("Welcome to AhRightOS!");

    init_kernel();
    // PTA_EX0_VISUAL_CODE_HERE
    run_pta_lab0_visualization_demo();
    event_log::drain_to_serial();
    test_heap_allocations();
    test_process_management();
    test_vfs_and_ramfs();
    test_blkfs_with_syscalls();
    test_extended_syscalls();

    start_multitasking_with_user();

    println!("Press Ctrl+A then X to exit QEMU\n");
    println!("[EventLog] Draining kernel events...");
    event_log::drain_to_serial();
    println!("[EventLog] Events drained successfully");
    os::hlt_loop();
}