Skip to content

Hal refactor#240

Merged
miiyakumo merged 12 commits into
mainfrom
hal-refactor
May 14, 2026
Merged

Hal refactor#240
miiyakumo merged 12 commits into
mainfrom
hal-refactor

Conversation

@miiyakumo

Copy link
Copy Markdown
Contributor

This pull request introduces a significant refactor and modularization of the architecture abstraction layer in the kernel. It establishes a more type-safe, extensible, and portable foundation for supporting multiple CPU architectures. The changes include the introduction of new traits for CPU operations and address management, a macro for implementing architecture-specific methods, and a more modular dependency and feature structure.

The most important changes are:

Architecture Abstraction and Address Safety:

  • Added a new arch/address.rs module that introduces a type-safe, generic address abstraction (Address<K, T>) with sealed traits for memory kinds (Physical, Virtual, User), preventing address space confusion at compile time and providing safe/unsafe access methods tailored to each address type. Also introduces an AddressTranslator trait for controlled address space conversions.
  • Introduced the arch/arch.rs trait, which unifies CPU operations, virtual memory, process management, user/kernel memory copying, system information, and power management into a single, extensible interface for architecture-specific logic.
  • Added the arch/cpu_ops.rs trait, abstracting the minimal set of CPU operations (interrupt control, halt, core ID) to maximize portability and testability of core modules.
  • Provided a macro (arch/arch_impl.rs) to generate common implementations of VirtualMemory and Arch for different architectures, reducing code duplication and simplifying the process of adding new architectures.

Build System and Dependency Management:

  • Refactored os/Cargo.toml to make most dependencies optional and feature-gated, enabling a layered, modular build. The default feature set now includes common kernel subsystems, and dependencies are grouped by functionality (e.g., device, filesystem, networking).
  • Updated build scripts (build.rs) to only build user programs and runtime images for supported target architectures, improving cross-compilation support and clarity of build warnings. [1] [2] [3]
  • Added x86_64 mock test build settings to .cargo/config.toml, clarifying known issues and proper usage for developers running tests on x86_64 hosts.
  • Enforced abort-on-panic for both dev and test profiles in Cargo.toml, aligning panic strategy across build modes.

Miscellaneous:

  • Minor code quality and style improvements, such as updating allow attributes and removing unused constants in architecture-specific files. [1] [2]

These changes collectively lay a robust foundation for multi-architecture support, safer memory management, and a more maintainable kernel codebase.

miiyakumo added 12 commits May 13, 2026 16:46
…and RISC-V

- Added `cpu_ops.rs` for LoongArch64 architecture, implementing `hal::CpuOps` trait with methods for CPU ID retrieval, interrupt management, and CPU halting.
- Added `cpu_ops.rs` for RISC-V architecture, implementing `hal::CpuOps` trait with similar functionalities.
- Introduced `address.rs` for type-safe address abstraction, supporting physical, virtual, and user addresses with associated methods.
- Created `arch.rs` to define the top-level architecture abstraction, combining CPU operations and virtual memory management.
- Established `cpu_ops.rs` as the foundational trait for CPU operations, ensuring minimal dependencies for architecture portability.
- Developed `mock.rs` to provide mock implementations for testing, facilitating architecture-agnostic code testing.
- Added `virtual_memory.rs` to define traits for virtual memory management, including user and kernel address space operations.
- Introduced a new module `inner.rs` defining the `PageTableInner` trait for page table operations.
- Updated `mod.rs` to use the new `inner` module instead of a self-referential structure.

fix(sync): specify types for PerCpu, RwLock, and TicketLock

- Explicitly defined types for `PerCpu`, `RwLock`, and `TicketLock` instances in test cases to improve type safety and clarity.
… LoongArch architectures

- Added `SyscallFrame` trait to unify syscall argument access across architectures.
- Implemented `dispatch_syscall` function to handle syscall dispatching in an architecture-agnostic manner.
- Updated `TrapFrame` to implement `SyscallFrame` for RISC-V.
- Created a new module for syscall dispatching and updated syscall handling in the kernel.
- Introduced early printing functions and macros for kernel initialization.
- Added LoongArch platform support with MMIO for console I/O and power management.
- Implemented pure Rust versions of `memcpy`, `memmove`, and `memset` for LoongArch due to incomplete compiler support.
- Updated various syscall handling functions to utilize the new dispatch mechanism.
…ory access

- Removed reliance on SumGuard for user space access in syscalls, replacing it with Arch trait methods for copying data to and from user space.
- Updated syslog implementation to utilize `copy_to_user` and `copy_from_user` for safer memory operations.
- Refactored task management syscalls to eliminate SumGuard usage, enhancing clarity and safety.
- Improved user buffer handling in utility functions, ensuring proper memory access without architecture-specific guards.
- Adjusted socket and ioctl implementations to follow the new user space access patterns, ensuring consistency across the codebase.
- Added error handling for user space memory operations to prevent potential crashes or undefined behavior.
- Updated `exec_loader.rs` to conditionally set `value` for non-RISC-V architectures.
- Modified `space.rs` and `mod.rs` to import `MEMORY_END` from the new mock platform module.
- Enhanced `intr_guard.rs` to utilize CPU-specific interrupt status checks.
- Updated synchronization module to conditionally compile mutex features.
- Removed unused test module `test.rs`.
- Introduced `mock_stubs.rs` to provide mock implementations for architecture-specific functions, enabling compilation and testing on non-RISC-V platforms.
…t methods

- Implemented `on_task_switch`, `get_ticks`, `get_time`, `get_time_ms`, `clock_freq`, and `send_reschedule_ipi` methods in the Arch trait for both LoongArch and RISC-V architectures.
- Updated the architecture-specific modules to utilize the new methods, ensuring better abstraction and code reuse.
- Refactored existing code to replace direct calls to architecture-specific functions with the new trait methods, improving maintainability and readability.
- Updated `Cargo.toml` to reorganize dependencies into mandatory and optional categories, enhancing modularity.
- Modified `build.rs` to conditionally compile user programs based on target architecture (RISC-V and LoongArch).
- Enhanced console output functions to support device features conditionally.
- Cleaned up CPU task management code by removing redundant comments.
- Introduced feature gates for process-related modules in the task management system.
- Updated main module to reflect multi-architecture support and reorganized module imports.
- Moved frame allocator implementation to a new file for better organization and clarity.
- Removed the global allocator module and replaced it with a new `talc_alloc` module for dynamic heap memory allocation.
- Ensured that heap initialization is only called when the allocation feature is enabled.
… initialization, and syscall definitions

- Implement SBI calls for console I/O, timer management, and system shutdown in `lib.rs`.
- Create memory management traits for user and kernel address spaces in `memory.rs`.
- Initialize Virt platform devices in `platform.rs`.
- Define RISC-V syscall numbers in `syscall.rs` following Linux conventions.
- Removed unused imports from `mapping_area.rs`, `space.rs`, and `mod.rs`.
- Introduced a new `arch_impl.rs` file to provide common architecture implementations for `VirtualMemory` and `Arch`.
- Added `memory_impl.rs` to define `UserAddressSpace` and `KernAddressSpace` implementations for different architectures.
- Created mock architecture files under `mock/` directory to facilitate testing when not targeting RISC-V or LoongArch.
- Implemented basic mock functions for boot, interrupts, timers, and traps to support architecture-agnostic code compilation.
- Defined Linux syscall numbers in `syscall.rs` for consistent ABI across architectures.
- Introduced `Arch` trait as a top-level architecture abstraction combining `CpuOps` and `VirtualMemory`.
- Created `CpuOps` trait for low-level CPU operations, facilitating architecture portability.
- Defined `VirtualMemory`, `UserAddressSpace`, and `KernAddressSpace` traits for memory management.
- Updated all architecture implementations (RISC-V, LoongArch) to use the new trait structure.
- Implemented a mock architecture for testing purposes, ensuring compatibility with non-target architectures.
- Refactored imports across the codebase to align with the new architecture module structure.
- Removed the old HAL module structure, consolidating architecture-related traits into the `arch` module.
@miiyakumo
miiyakumo merged commit b29f386 into main May 14, 2026
1 check failed
@miiyakumo
miiyakumo deleted the hal-refactor branch May 14, 2026 15:06

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces multi-architecture support by abstracting CPU operations and memory management through new traits (Arch, CpuOps, VirtualMemory). It replaces architecture-specific SumGuard mechanisms with a unified copy_from_user/copy_to_user interface. However, the review identified critical issues where the return values of these copy operations are ignored, leading to potential undefined behavior or silent failures when accessing user-space memory. These issues must be addressed to ensure memory safety.

Comment on lines 18 to 25
unsafe {
ptr::write_volatile(user_ptr, value);
crate::arch::ArchImpl::copy_to_user(
(&value) as *const T as *const u8,
user_ptr as usize,
size,
)
.ok();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The result of copy_to_user is ignored in write_to_user. If the copy fails, the function should return an error, but it currently silently fails.

Comment on lines +36 to +44
unsafe {
crate::arch::ArchImpl::copy_from_user(
user_ptr as usize,
val.as_mut_ptr() as *mut u8,
size,
)
.ok();
val.assume_init()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The read_from_user function ignores the result of copy_from_user and calls val.assume_init() on uninitialized memory if the copy fails, which is undefined behavior. The function should return a Result<T, ()> and callers should handle the error.

Comment on lines +21 to +28
unsafe {
crate::arch::ArchImpl::copy_from_user(
buf as usize,
kernel_buf.as_mut_ptr(),
count,
)
.ok();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The result of copy_from_user is ignored in the write function. If the copy fails, the kernel proceeds with a buffer of zeros, which is incorrect. The function should return EFAULT if the copy fails.

Comment on lines +66 to +73
unsafe {
crate::arch::ArchImpl::copy_to_user(
kernel_buf.as_ptr(),
buf as usize,
n,
)
.ok();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The result of copy_to_user is ignored in the read function. If the copy fails, the kernel should return EFAULT instead of proceeding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant