Core Kernel

Orchestrator, syscalls, IPC, interrupts, self-heal, hot-reload, and panic handler.

Documentation

Module Map

The helix-core crate is the central nervous system of the kernel. It contains 21 source files organized into 10 modules totaling approximately 2,800 lines of Rust code.

core/src/ — Module Map16N · 15E
core/src/21 source files, 10 …15lib.rsRe-exports, KernelSt…1config.rsBootConfiguration — …1component.rsKernelComponent trai…1orchestrator.rsKernelOrchestrator —…1subsystem.rsSubsystem trait — in…1lifecycle.rsLifecycleManager, Sh…1capability.rsCapabilityBroker — g…1resource.rsResourceBroker — all…1ipc/IPC module — 4 files1syscall/Syscall module — 4 f…1interrupts.rsInterruptDispatcher,…1hot_reload.rsHotReloadRegistry, H…1self_heal.rsSelfHealingManager —…1debug.rsConsoleWriter, kprin…1panic.rsPanicHandler trait, …1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

Kernel Types

The root lib.rs defines the fundamental types that every other module depends on:

KernelState

The kernel state machine governs what operations are valid at any given time:

Kernel State Machine6N · 7E
suspendresumefatalfatalBootFirmware handoff1InitializingSubsystems starting …3RunningNormal operation — s…4ShuttingDownGraceful shutdown1PanicUnrecoverable fault …2SuspendedLow-power state (fut…1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node
core/src/lib.rs
rust
1
#[repr(u32)]
pub enum KernelState {
3
EarlyBoot = 0, // Firmware just handed control
4
Initializing = 1, // Subsystems starting up
5
Running = 2, // Normal operation — syscalls active
6
ShuttingDown = 3, // Graceful shutdown in progress
7
Panic = 4, // Unrecoverable fault — halt or reboot
8
Suspended = 5, // Low-power state (future)
9
}
Index

State transitions are managed exclusively by KernelOrchestrator. Invalid transitions (e.g., Panic → Running) are rejected at runtime.

KernelVersion

core/src/lib.rs
rust
2 refs
pub struct KernelVersion {
2
pub major: u16,
3
pub minor: u16,
4
pub patch: u16,
5
pub suffix: &'static str, // "alpha" for 0.1.0-alpha
6
}
7
pub const KERNEL_VERSION: KernelVersion = KernelVersion {
9
major: 0, minor: 1, patch: 0, suffix: "alpha",
10
};
Index

KernelError

A unified error type for all core operations:

core/src/lib.rs
rust
pub enum KernelError {
2
NotPermitted,
3
NotFound,
4
AlreadyExists,
5
InvalidArgument,
6
WouldBlock,
7
Busy,
8
OutOfMemory,
9
Timeout,
10
Interrupted,
11
IoError,
12
NotImplemented,
13
Internal,
14
CapabilityError(CapabilityError),
15
SubsystemError(&'static str),
16
}
Index

KernelEvent

Events emitted during kernel lifecycle changes:

core/src/lib.rs
rust
pub enum KernelEvent {
2
ModuleLoaded { name: String },
3
ModuleUnloaded { name: String },
4
StateChanged { old: KernelState, new: KernelState },
5
MemoryPressure { level: MemoryPressureLevel },
6
CpuHotplug { cpu: usize, online: bool },
7
TimerTick { timestamp: u64 },
8
Custom { id: u64, data: Vec<u8> },
9
}
Index

KernelComponent Trait

Every major kernel component implements this trait to participate in the lifecycle:

core/src/lib.rs
rust
pub trait KernelComponent: Send + Sync {
2
/// Unique name for logging and debugging
2 refs
fn name(&self) -> &'static str;
4
5
/// Semantic version of this component
2 refs
fn version(&self) -> &'static str;
7
8
/// Initialize the component. Called once during boot.
fn init(&mut self) -> KernelResult<()>;
10
11
/// Shut down the component gracefully.
fn shutdown(&mut self) -> KernelResult<()>;
13
14
/// Check if the component is healthy.
fn health_check(&self) -> bool { true }
16
17
/// Get component statistics.
fn stats(&self) -> Option<ComponentStats> { None }
19
}
Index

ComponentStats

core/src/lib.rs
rust
pub struct ComponentStats {
2
pub operations: u64,
3
pub errors: u64,
4
pub load: u8, // 0-100
5
pub memory_usage: usize,
6
}
Index

The self-healing system periodically calls health_check() on every registered component and triggers recovery actions for Unhealthy components.


Orchestrator

The KernelOrchestrator is the kernel's central coordinator. It manages subsystem registration, initialization ordering, and lifecycle transitions.

Registration

core/src/orchestrator.rs
rust
impl KernelOrchestrator {
2
/// Register a subsystem with its metadata.
3
/// Dependencies are declared as subsystem names.
pub fn register(&mut self, subsystem: Box<dyn Subsystem>) -> Result<SubsystemId>;
5
6
/// Initialize all registered subsystems in dependency order.
7
/// Uses topological sort to resolve initialization sequence.
pub fn init_all(&mut self) -> Result<()>;
9
10
/// Shut down all subsystems in reverse initialization order.
pub fn shutdown_all(&mut self) -> Result<()>;
12
}
Index

Initialization Algorithm

  1. Build a dependency graph from all registered subsystems
  2. Perform topological sort to determine initialization order
  3. Detect cycles — if found, return KernelError::DependencyCycle
  4. Initialize subsystems in sorted order, passing the BootConfiguration
  5. If any subsystem fails, attempt recovery via self-heal
  6. If recovery fails, shut down already-initialized subsystems in reverse order

Subsystem Trait

Every subsystem implements this trait:

core/src/orchestrator.rs
rust
pub trait Subsystem: Send + Sync {
fn name(&self) -> &'static str;
fn version(&self) -> &'static str;
fn dependencies(&self) -> &[&'static str] { &[] }
5
fn init(&self) -> KernelResult<()>;
fn shutdown(&self) -> KernelResult<()>;
8
9
/// Suspend/resume for power management.
fn suspend(&self) -> KernelResult<()> { Ok(()) }
2 refs
fn resume(&self) -> KernelResult<()> { Ok(()) }
12
13
/// Health monitoring — called periodically by self-heal.
fn is_healthy(&self) -> bool { true }
15
}
Index

BootConfiguration

The boot configuration is built from bootloader-provided data and passed to every subsystem during init:

core/src/orchestrator.rs
rust
pub struct BootConfiguration {
2
pub command_line: String,
3
pub memory_map: Vec<MemoryMapEntry>,
4
pub boot_modules: Vec<BootModule>,
5
pub debug_mode: bool,
6
pub verbose: bool,
7
pub cpu_count: usize,
8
}
Index

Syscall Framework

The syscall framework provides a structured path from userspace into kernel services.

Architecture

Syscall Architecture — Pipeline6N · 5E
int 0x80validateddispatchResult<usize>sysretqUser Processsyscall instruction1SyscallGatewayhelix_syscall_entry(…2SyscallDispatcherdispatch(number, arg…2SyscallHandlerhandle(args) → Resul…2Return PathPost-hooks + result2User Resumessysretq1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

SyscallRegistry

The registry holds up to 512 syscall handlers:

core/src/syscall.rs
rust
2 refs
pub struct SyscallRegistry {
2
handlers: [Option<Box<dyn SyscallHandler>>; 512],
3
names: [Option<&'static str>; 512],
4
}
5
2 refs
impl SyscallRegistry {
pub fn register(&mut self, number: u16, name: &'static str,
8
handler: Box<dyn SyscallHandler>) -> Result<()>;
pub fn unregister(&mut self, number: u16) -> Result<()>;
pub fn lookup(&self, number: u16) -> Option<&dyn SyscallHandler>;
11
}
Index

SyscallHandler Trait

core/src/syscall.rs
rust
pub trait SyscallHandler: Send + Sync {
fn handle(&self, args: &SyscallArgs) -> SyscallReturn;
fn name(&self) -> &'static str;
fn arg_count(&self) -> usize;
fn validate(&self, _args: &SyscallArgs) -> Result<(), SyscallError> {
6
Ok(())
7
}
8
}
9
3 refs
pub struct SyscallArgs {
11
pub args: [u64; MAX_SYSCALL_ARGS], // up to 6 register args
12
pub count: usize,
13
}
Index

SyscallError

POSIX-compatible error codes:

core/src/syscall.rs
rust
1
#[repr(u64)]
pub enum SyscallError {
3
NotPermitted = 1,
4
NoEntry = 2,
5
NoProcess = 3,
6
Interrupted = 4,
7
IoError = 5,
8
BadFd = 9,
9
TryAgain = 11,
10
OutOfMemory = 12,
11
PermissionDenied = 13,
12
BadAddress = 14,
13
InvalidArgument = 22,
14
WouldBlock = 35,
15
NotImplemented = 38,
16
TimedOut = 110,
17
}
Index

Dispatcher Hooks

The dispatcher supports pre-hooks and post-hooks for cross-cutting concerns:

core/src/syscall.rs
rust
impl SyscallDispatcher {
pub fn add_pre_hook(&mut self, hook: Box<dyn SyscallHook>);
pub fn add_post_hook(&mut self, hook: Box<dyn SyscallHook>);
4
}
Index

Typical hooks include:

  • SecurityHook — checks caller capabilities before dispatch
  • AuditHook — logs all syscall invocations for debugging
  • MetricsHook — collects timing and frequency statistics

IPC

The Inter-Process Communication module provides four complementary communication primitives:

IPC Primitives5N · 4E
IPC Module4 communication prim…4ChannelsMPSC ring buffer1OneShotSingle-use channel1EventBusPub/Sub broadcasting1MessageRouterPoint-to-Point RPC1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

Channels — MPSC Ring Buffer

The primary IPC mechanism is a lock-free multi-producer, single-consumer channel built on a ring buffer:

core/src/ipc.rs
rust
pub fn channel<T: Send>(capacity: usize) -> (Sender<T>, Receiver<T>);
2
2 refs
impl<T: Send> Sender<T> {
pub fn send(&self, item: T) -> IpcResult<()>;
pub fn try_send(&self, item: T) -> IpcResult<()>;
pub fn is_closed(&self) -> bool;
7
}
8
2 refs
impl<T: Send> Receiver<T> {
pub fn try_recv(&self) -> IpcResult<T>;
pub fn drain(&self) -> Vec<T>;
pub fn is_empty(&self) -> bool;
13
}
Index

The Sender<T> is cloneable (multi-producer). The Receiver<T> is not (single-consumer). When the last sender drops, the channel closes automatically.

OneShot — Single-Use Channel

For request-response patterns where exactly one value is exchanged:

core/src/ipc.rs
rust
pub fn oneshot<T: Send>() -> (OneShotSender<T>, OneShotReceiver<T>);
Index

The sender can only send() once. The receiver can only recv() once. Both types are !Clone.

EventBus — Pub/Sub

A topic-based publish-subscribe system for broadcasting events to multiple subscribers:

core/src/ipc.rs
rust
2 refs
pub struct EventBus { /* ... */ }
2
2 refs
impl EventBus {
pub fn subscribe(&mut self, sub: EventSubscription) -> SubscriptionId;
pub fn publish(&self, event: Event) -> EventDispatchResult;
pub fn unsubscribe(&mut self, id: SubscriptionId);
7
}
8
2 refs
pub struct EventSubscription {
10
pub name: &'static str,
11
pub topics: Vec<EventTopic>,
12
pub callback: Box<dyn Fn(&Event) -> EventResponse + Send + Sync>,
13
}
14
2 refs
pub enum EventTopic {
16
Tick, Shutdown, MemoryPressure, CpuHotplug,
17
Process, Interrupt, Custom(String), All,
18
}
Index

Common topics:

  • "kernel.state" — kernel state transitions
  • "subsystem.health" — health status changes
  • "module.lifecycle" — module load/unload/reload
  • "syscall.audit" — syscall invocation log

MessageRouter — Point-to-Point

For direct inter-subsystem communication with named mailboxes:

core/src/ipc.rs
rust
2 refs
pub struct MessageRouter { /* ... */ }
2
2 refs
impl MessageRouter {
pub fn register(&mut self, addr: ModuleAddress,
5
handler: Box<dyn MessageHandler>) -> IpcResult<()>;
pub fn send(&self, to: &ModuleAddress, req: Request) -> IpcResult<Response>;
pub fn send_to(&self, to: &ModuleAddress, msg: MessageEnvelope) -> IpcResult<()>;
8
}
9
4 refs
pub enum ModuleAddress {
11
Id(u64),
12
Name(String),
13
Broadcast,
14
}
Index

Each module registers its address during init and receives messages directly. Requests carry a MessagePriority (Low, Normal, High, Critical).


Self-Heal

The SelfHealingManager provides automatic fault detection and recovery for kernel subsystems.

Architecture

Self-Heal — Recovery Architecture4N · 4E
Unhealthyunder limitover limitretry cycleHealth MonitorPeriodic timer callb…2Recovery DecisionCheck restart count3Factory-Based RecoveryCreate fresh instanc…2EscalationCritical failure1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

API

core/src/self_heal.rs
rust
1
#[repr(u8)]
2 refs
pub enum HealthStatus {
3
Healthy = 0,
4
Degraded = 1,
5
Unresponsive = 2,
6
Crashed = 3,
7
Recovering = 4,
8
Unknown = 255,
9
}
10
2 refs
pub enum RecoveryAction {
12
None, // Healthy — no action
13
Restart, // Restart the module
14
Failover, // Replace with backup module
15
Panic, // Unrecoverable — escalate
16
}
17
2 refs
pub struct SelfHealingManager { /* ... */ }
19
2 refs
impl SelfHealingManager {
pub fn register_module(&self, slot_id: SlotId, name: &str,
22
factory: Option<ModuleFactory>) -> Result<()>;
pub fn check_health(&self, slot_id: SlotId) -> HealthStatus;
pub fn trigger_recovery(&self, slot_id: SlotId) -> RecoveryAction;
pub fn stats(&self) -> RecoveryStats;
26
}
Index

Configuration

ParameterDefaultDescription
Max restart attempts3Restarts before permanent failure
Health check interval1000 ticksHow often to poll health
Recovery timeout5000 ticksMax time for recovery to complete
Cooldown period2000 ticksMin time between restart attempts

Hot-Reload

The hot-reload system enables replacing module binaries at runtime without losing state.

Reload State Machine

Hot-Reload — State Machine8N · 7E
failureIdleWaiting for reload t…1PreparingValidate module, che…2SavingStatemodule.get_state()2UnloadingRemove old binary2LoadingLoad new binary, ver…3RestoringStatemodule.restore_state…2CompletedModule resumes1RollbackFailedRecovery failed1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

HotReloadableModule Trait

core/src/hot_reload.rs
rust
pub trait HotReloadableModule: Send + Sync {
fn name(&self) -> &'static str;
fn version(&self) -> ModuleVersion;
fn category(&self) -> ModuleCategory;
5
fn init(&mut self) -> Result<(), HotReloadError>;
fn prepare_unload(&mut self) -> Result<(), HotReloadError>;
8
9
/// Export current state for migration
fn export_state(&self) -> Option<Box<dyn ModuleState>>;
11
12
/// Import state from previous module
fn import_state(&mut self, state: &dyn ModuleState) -> Result<(), HotReloadError>;
14
15
/// Check if module can be safely unloaded now
fn can_unload(&self) -> bool;
17
}
Index

Reload Process

  1. Preparing — Notify dependents, quiesce in-flight operations
  2. SavingState — Call get_state() on the old module instance
  3. Unloading — Remove old binary from memory, update registry
  4. Loading — Load new binary, verify ABI compatibility via AbiChecker
  5. RestoringState — Call restore_state() on the new module instance
  6. Completed — Resume normal operation, notify dependents

ABI Compatibility

The AbiChecker validates that the new module binary is compatible:

core/src/hot_reload.rs
rust
2 refs
pub struct ModuleVersion {
2
pub major: u16, // Breaking changes
3
pub minor: u16, // New features
4
pub patch: u16, // Bug fixes
5
}
6
2 refs
impl ModuleVersion {
8
/// Same major version = compatible
pub fn compatible_with(&self, other: &Self) -> bool {
10
self.major == other.major
11
}
12
}
13
14
#[repr(u8)]
pub enum SlotStatus {
16
Empty, Loading, Active, Unloading, Swapping, Failed,
17
}
Index

Built-in Hot-Reloadable Modules

ModulePurposeState Preserved
RoundRobinSchedulerThread schedulingRun queue, thread priorities
PrioritySchedulerPriority-based schedulingPriority queues, statistics

Interrupts

The interrupt subsystem provides a unified interface for hardware and software interrupts across all architectures.

InterruptDispatcher

core/src/interrupts.rs
rust
2 refs
pub type InterruptHandlerFn = dyn Fn(InterruptVector) + Send + Sync;
2
2 refs
pub struct InterruptDispatcher {
4
handlers: RwLock<[Vec<InterruptHandler>; 256]>,
5
}
6
2 refs
impl InterruptDispatcher {
8
/// Register a handler for a specific vector.
9
/// If shared=false, no other handlers can be registered.
pub fn register(&self, vector: InterruptVector, name: &'static str,
11
handler: Arc<InterruptHandlerFn>, shared: bool) -> Result<(), &'static str>;
12
13
/// Unregister a handler by name.
pub fn unregister(&self, vector: InterruptVector, name: &'static str);
15
16
/// Dispatch an interrupt — calls all registered handlers for the vector.
pub fn dispatch(&self, vector: InterruptVector);
18
}
Index

ExceptionDispatcher

Handles CPU exceptions (divide-by-zero, page fault, general protection fault, etc.):

core/src/interrupts.rs
rust
pub struct ExceptionDispatcher {
pub fn register(&mut self, exception: ExceptionType,
3
handler: Box<dyn ExceptionHandler>) -> Result<()>;
pub fn dispatch(&self, exception: ExceptionType, frame: &ExceptionFrame);
5
}
Index

InterruptRouter

Provides different routing strategies for interrupt distribution across CPUs:

core/src/interrupts.rs
rust
pub enum RoutingStrategy {
2
FixedCpu(CpuId), // Always route to specific CPU
3
RoundRobin, // Distribute evenly
4
LowestPriority, // Route to least-busy CPU
5
Broadcast, // Send to all CPUs
6
}
Index

Interrupt Flow

Interrupt Flow7N · 6E
acknowledgedvector lookupHandledReschedulePanicHardware InterruptIDT / GIC / PLIC1HAL HandlerSave CPU state, ackn…2InterruptDispatcherdispatch(vector, fra…2InterruptHandlerhandle(frame) → Acti…4HandledReturn to interrupte…1RescheduleTrigger context swit…1PanicInvoke panic handler1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node

Debug Console

The debug module provides kernel-wide logging and diagnostic output.

ConsoleWriter Trait

core/src/debug.rs
rust
pub trait ConsoleWriter: Send + Sync {
fn write_byte(&mut self, byte: u8);
fn write_string(&mut self, s: &str);
fn flush(&mut self);
5
}
Index

Implementations include:

  • SerialConsoleWriter — outputs to COM1 (0x3F8) on x86_64
  • FramebufferConsoleWriter — renders text to the framebuffer
  • NullConsoleWriter — discards all output (for benchmarks)

Logging Macros

core/src/debug.rs
rust
1
// Standard output (always enabled)
2
kprint!("value: {}", x);
3
kprintln!("boot complete");
4
5
// Level-gated logging
6
kdebug!("allocator: free frames = {}", count);
7
kinfo!("scheduler: thread {} started", tid);
8
kwarn!("memory: low watermark reached");
9
kerror!("syscall: invalid number {}", num);

Each macro includes the source file and line number in debug builds. In release builds, kdebug! is compiled out entirely.

DebugInterface

core/src/debug.rs
rust
pub struct DebugInterface {
pub fn register_writer(&mut self, writer: Box<dyn ConsoleWriter>);
pub fn set_log_level(&mut self, level: LogLevel);
pub fn dump_state(&self); // Print all registered component states
5
}
Index

Panic Handler

When the kernel encounters an unrecoverable error, the panic handler provides structured crash reporting.

PanicHandler Trait

core/src/panic.rs
rust
pub trait PanicHandler: Send + Sync {
fn handle_panic(&self, ctx: &PanicContext) -> PanicAction;
3
}
Index

PanicContext

core/src/panic.rs
rust
pub struct PanicContext {
2
pub message: &'static str,
3
pub location: Option<PanicLocation>, // file, line, column
4
pub backtrace: Option<Backtrace>,
5
pub cpu_state: Option<CpuState>,
6
pub thread_id: Option<ThreadId>,
7
pub kernel_state: KernelState,
8
}
Index

PanicAction

core/src/panic.rs
rust
pub enum PanicAction {
2
Halt, // HLT loop — stop the CPU entirely
3
Reboot, // Triple fault or ACPI reboot
4
DebugBreak, // int3 — break into GDB if attached
5
Continue, // Attempt to continue (dangerous, debug only)
6
}
Index

Panic Output

When a panic occurs, the handler:

Panic Handler Flow6N · 5E
step 1step 2step 3step 4step 5Panic TriggeredUnrecoverable fault1Disable InterruptsPrevent re-entrant p…2Print MessageLocation, thread, ke…2Dump RegistersCPU register snapsho…2Stack TraceWalk stack frames if…2PanicActionHalt / Reboot / Debu…1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node
  1. Disables interrupts (prevent re-entrant panics)
  2. Prints the panic message and location to serial console
  3. Dumps CPU register state if available
  4. Prints a stack trace if symbols are available
  5. Executes the chosen PanicAction

Example output:

=== KERNEL PANIC ===
Message: index out of bounds: the len is 5 but the index is 10
Location: core/src/orchestrator.rs:142:25
Thread: kernel_init (tid=1)
State: Initializing

Register Dump:
  RAX=0x0000000000000005  RBX=0x000000000000000A
  RCX=0xFFFFFFFF80012345  RDX=0x0000000000000000
  ...

Stack Trace:
  #0  core::panicking::panic_bounds_check
  #1  helix_core::orchestrator::init_all
  #2  helix_minimal_os::kernel_main
  #3  _start

Action: Halt

Capability Broker

The CapabilityBroker implements capability-based access control for all kernel resources.

Capabilities

Capabilities are fine-grained permissions represented as bitflags:

Capability Broker Flow7N · 6E
request accesslookuphas permissionno permissiontransferremoveSubjectProcess / module req…1CapabilityBrokerPermission managemen…4check()Verify permission3Granted ✓Access allowed1Denied ✗Access refused1delegate()Transfer permissions…1revoke()Remove permissions1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node
core/src/capabilities.rs
rust
1
bitflags! {
pub struct Permissions: u64 {
3
const READ = 1 << 0;
4
const WRITE = 1 << 1;
5
const EXECUTE = 1 << 2;
6
const CREATE = 1 << 3;
7
const DELETE = 1 << 4;
8
const ADMIN = 1 << 5;
9
// ... up to 64 distinct permissions
10
}
11
}
12
pub enum ResourceType {
14
Memory,
15
File,
16
Device,
17
Process,
18
Network,
19
Module,
20
Syscall,
21
}
Index

Operations

core/src/capabilities.rs
rust
impl CapabilityBroker {
2
/// Grant permissions on a resource to a subject.
pub fn grant(&mut self, subject: SubjectId, resource: ResourceId,
4
permissions: Permissions) -> Result<()>;
5
6
/// Delegate (subset of) permissions to another subject.
pub fn delegate(&mut self, from: SubjectId, to: SubjectId,
8
resource: ResourceId, permissions: Permissions) -> Result<()>;
9
10
/// Revoke permissions.
pub fn revoke(&mut self, subject: SubjectId, resource: ResourceId) -> Result<()>;
12
13
/// Check if a subject has the required permissions.
pub fn check(&self, subject: SubjectId, resource: ResourceId,
15
required: Permissions) -> bool;
16
}
Index

Resource Broker

The ResourceBroker manages kernel resource allocation and limits.

Resource Classes

core/src/resource_broker.rs
rust
pub enum ResourceClass {
2
Memory, // Physical/virtual memory pages
3
CpuTime, // Scheduler time slices
4
FileHandles, // Open file descriptors
5
Threads, // Thread count per process
6
NetworkPorts, // Bound network ports
7
Modules, // Loaded module count
8
}
Index

API

core/src/resource_broker.rs
rust
impl ResourceBroker {
2
/// Register a resource provider for a class.
pub fn register_provider(&mut self, class: ResourceClass,
4
provider: Box<dyn ResourceProvider>) -> Result<()>;
5
6
/// Allocate resources within limits.
pub fn allocate(&mut self, owner: OwnerId, class: ResourceClass,
8
amount: usize) -> Result<ResourceHandle>;
9
10
/// Release allocated resources.
pub fn release(&mut self, handle: ResourceHandle) -> Result<()>;
12
13
/// Set resource limits for an owner.
pub fn set_limit(&mut self, owner: OwnerId, class: ResourceClass,
15
limit: ResourceLimit) -> Result<()>;
16
}
17
2 refs
pub struct ResourceLimit {
19
pub soft: usize, // Warning threshold
20
pub hard: usize, // Absolute maximum
21
}
Index

Lifecycle Manager

The LifecycleManager tracks kernel lifecycle phases and notifies registered callbacks on transitions.

Lifecycle Phases

Lifecycle Phases7N · 6E
BootFirmware handoff1EarlyInitPre-heap: GDT, IDT, …2CoreInitOrchestrator, interr…2LateInitDrivers, filesystem,…2RunningFull system operatio…2ShuttingDownGraceful teardown2HaltedSystem stopped1
100%
☝ Drag to pan·🤏 Pinch to zoom·Tap a node
core/src/lifecycle.rs
rust
pub enum LifecyclePhase {
2
Boot,
3
EarlyInit,
4
CoreInit,
5
LateInit,
6
Running,
7
ShuttingDown,
8
Halted,
9
}
10
pub enum ShutdownReason {
12
UserRequest,
13
AdminCommand,
14
CriticalFailure,
15
PowerOff,
16
Reboot,
17
Panic,
18
}
Index

Callbacks

core/src/lifecycle.rs
rust
2 refs
pub trait LifecycleCallback: Send + Sync {
fn on_phase_enter(&self, phase: LifecyclePhase);
fn on_phase_exit(&self, phase: LifecyclePhase);
fn on_shutdown(&self, reason: ShutdownReason);
5
}
6
impl LifecycleManager {
pub fn register_callback(&mut self, callback: Box<dyn LifecycleCallback>);
pub fn transition_to(&mut self, phase: LifecyclePhase) -> Result<()>;
pub fn current_phase(&self) -> LifecyclePhase;
pub fn request_shutdown(&mut self, reason: ShutdownReason);
12
}
Index