Skip to main content

strat9_kernel/silo/
mod.rs

1//! Silo manager (kernel-side, minimal mechanisms only)
2//!
3//! This module provides the core kernel structures and syscalls
4//! to create and manage silos. Policy lives in userspace (silo admin).
5
6use crate::{
7    capability::{get_capability_manager, CapId, CapPermissions, Capability, ResourceType},
8    hardware::storage::{ahci, virtio_block},
9    ipc::port::{self, PortId},
10    memory::{UserSliceRead, UserSliceWrite},
11    process::{current_task_clone, task::Task, TaskId},
12    sync::{FixedQueue, SpinLock},
13    syscall::error::SyscallError,
14};
15use alloc::{
16    boxed::Box,
17    collections::BTreeMap,
18    string::{String, ToString},
19    sync::Arc,
20    vec::Vec,
21};
22use core::sync::atomic::{AtomicU64, Ordering};
23use heapless::Vec as HVec;
24
25// ============================================================================
26// Public ABI structs (repr(C) for syscall boundary)
27// ============================================================================
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
30#[repr(u8)]
31pub enum SiloTier {
32    Critical = 0,
33    System = 1,
34    User = 2,
35}
36
37#[repr(C)]
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39pub struct SiloId {
40    pub sid: u32,
41    pub tier: SiloTier,
42}
43
44impl SiloId {
45    /// Creates a new instance.
46    pub const fn new(sid: u32) -> Self {
47        let tier = match sid {
48            1..=9 => SiloTier::Critical,
49            10..=999 => SiloTier::System,
50            _ => SiloTier::User,
51        };
52        Self { sid, tier }
53    }
54
55    /// Returns this as u64.
56    pub fn as_u64(&self) -> u64 {
57        self.sid as u64
58    }
59}
60
61use bitflags::bitflags;
62
63bitflags! {
64    #[repr(transparent)]
65    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
66    pub struct ControlMode: u8 {
67        const LIST  = 0b100;
68        const STOP  = 0b010;
69        const SPAWN = 0b001;
70    }
71}
72
73bitflags! {
74    #[repr(transparent)]
75    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76    pub struct HardwareMode: u8 {
77        const INTERRUPT = 0b100;
78        const IO        = 0b010;
79        const DMA       = 0b001;
80    }
81}
82
83bitflags! {
84    #[repr(transparent)]
85    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
86    pub struct RegistryMode: u8 {
87        const LOOKUP = 0b100;
88        const BIND   = 0b010;
89        const PROXY  = 0b001;
90    }
91}
92
93#[repr(C)]
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct OctalMode {
96    pub control: ControlMode,
97    pub hardware: HardwareMode,
98    pub registry: RegistryMode,
99}
100
101impl OctalMode {
102    /// Builds this from octal.
103    pub const fn from_octal(val: u16) -> Self {
104        Self {
105            control: ControlMode::from_bits_truncate(((val >> 6) & 0o7) as u8),
106            hardware: HardwareMode::from_bits_truncate(((val >> 3) & 0o7) as u8),
107            registry: RegistryMode::from_bits_truncate((val & 0o7) as u8),
108        }
109    }
110
111    /// Returns whether subset of.
112    pub const fn is_subset_of(&self, other: &OctalMode) -> bool {
113        (self.control.bits() & !other.control.bits() == 0)
114            && (self.hardware.bits() & !other.hardware.bits() == 0)
115            && (self.registry.bits() & !other.registry.bits() == 0)
116    }
117
118    /// Performs the pledge operation.
119    pub fn pledge(&mut self, new_mode: OctalMode) -> Result<(), SyscallError> {
120        if !new_mode.is_subset_of(self) {
121            return Err(SyscallError::PermissionDenied); // Escalation attempt
122        }
123        *self = new_mode;
124        Ok(())
125    }
126}
127
128/// Performs the sys silo pledge operation.
129pub fn sys_silo_pledge(mode_val: u64) -> Result<u64, SyscallError> {
130    let new_mode = OctalMode::from_octal(mode_val as u16);
131    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
132
133    let mut mgr = SILO_MANAGER.lock();
134    if let Some(silo_id) = mgr.silo_for_task(task.id) {
135        if let Ok(silo) = mgr.get_mut(silo_id) {
136            silo.mode.pledge(new_mode)?;
137
138            mgr.push_event(SiloEvent {
139                silo_id: silo_id as u64,
140                kind: SiloEventKind::Started, // Re-using Started as "Updated" for now
141                data0: mode_val,
142                data1: 0,
143                tick: crate::process::scheduler::ticks(),
144            });
145            return Ok(0);
146        }
147    }
148    Err(SyscallError::BadHandle)
149}
150
151/// Performs the sys silo unveil operation.
152pub fn sys_silo_unveil(
153    path_ptr: u64,
154    path_len: u64,
155    rights_bits: u64,
156) -> Result<u64, SyscallError> {
157    const MAX_UNVEIL_PATH: usize = 1024;
158    const MAX_UNVEIL_RULES: usize = 128;
159
160    if path_ptr == 0 {
161        return Err(SyscallError::Fault);
162    }
163    let len = usize::try_from(path_len).map_err(|_| SyscallError::InvalidArgument)?;
164    if len == 0 || len > MAX_UNVEIL_PATH {
165        return Err(SyscallError::InvalidArgument);
166    }
167    let user = UserSliceRead::new(path_ptr, len)?;
168    let raw = user.read_to_vec();
169    let path = core::str::from_utf8(&raw).map_err(|_| SyscallError::InvalidArgument)?;
170    if path.is_empty() || !path.starts_with('/') || path.as_bytes().iter().any(|b| *b == 0) {
171        return Err(SyscallError::InvalidArgument);
172    }
173    let path = normalize_unveil_path(path)?;
174    let rights = UnveilRights::from_bits(rights_bits)?;
175
176    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
177    let mut mgr = SILO_MANAGER.lock();
178    let silo_id = mgr.silo_for_task(task.id).ok_or(SyscallError::BadHandle)?;
179    let silo = mgr.get_mut(silo_id)?;
180
181    if let Some(rule) = silo.unveil_rules.iter_mut().find(|r| r.path == path) {
182        rule.rights = rule.rights.intersect(rights);
183        return Ok(0);
184    }
185    if silo.unveil_rules.len() >= MAX_UNVEIL_RULES {
186        return Err(SyscallError::QueueFull);
187    }
188    // Pre-validated: len() < MAX_UNVEIL_RULES, push cannot fail.
189    let _ = silo.unveil_rules.push(UnveilRule { path, rights });
190    Ok(0)
191}
192
193/// Performs the sys silo enter sandbox operation.
194pub fn sys_silo_enter_sandbox() -> Result<u64, SyscallError> {
195    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
196    let mut mgr = SILO_MANAGER.lock();
197    let silo_id = mgr.silo_for_task(task.id).ok_or(SyscallError::BadHandle)?;
198    let silo = mgr.get_mut(silo_id)?;
199    if silo.sandboxed {
200        return Ok(0);
201    }
202    silo.sandboxed = true;
203    silo.mode.registry = RegistryMode::empty();
204    silo.config.mode =
205        ((silo.mode.control.bits() as u16) << 6) | ((silo.mode.hardware.bits() as u16) << 3);
206    Ok(0)
207}
208
209/// Sets the `strate_label` of a silo identified by handle.
210///
211/// Requires silo-admin capability. The label must be non-empty, at most 31
212/// bytes, and contain ONLY ASCII alphanumeric characters, `-`, `_`, or `.`.
213pub fn sys_silo_rename(handle: u64, label_ptr: u64, label_len: u64) -> Result<u64, SyscallError> {
214    require_silo_admin()?;
215    const MAX_LABEL: usize = 31;
216    let len = label_len as usize;
217    if len == 0 || len > MAX_LABEL {
218        return Err(SyscallError::InvalidArgument);
219    }
220    let user_slice = UserSliceRead::new(label_ptr, len)?;
221    let raw = user_slice.read_to_vec();
222    let label = core::str::from_utf8(&raw).map_err(|_| SyscallError::InvalidArgument)?;
223    if !is_valid_label(label) {
224        return Err(SyscallError::InvalidArgument);
225    }
226    let silo_id = resolve_silo_handle(handle, CapPermissions::read_write())?;
227    let mut mgr = SILO_MANAGER.lock();
228    // Reject if another silo already owns this label.
229    if mgr
230        .silos
231        .values()
232        .any(|s| s.id.sid != silo_id && s.strate_label.as_deref() == Some(label))
233    {
234        return Err(SyscallError::AlreadyExists);
235    }
236    let silo = mgr.get_mut(silo_id)?;
237    silo.strate_label = Some(String::from(label));
238    Ok(0)
239}
240
241/// Performs the enforce silo may grant operation.
242pub fn enforce_silo_may_grant() -> Result<(), SyscallError> {
243    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
244    if is_admin_task(&task) {
245        return Ok(());
246    }
247    let mgr = SILO_MANAGER.lock();
248    let Some(silo_id) = mgr.silo_for_task(task.id) else {
249        return Ok(());
250    };
251    let silo = mgr.get(silo_id)?;
252    if silo.sandboxed {
253        return Err(SyscallError::PermissionDenied);
254    }
255    Ok(())
256}
257
258/// Performs the normalize unveil path operation.
259fn normalize_unveil_path(path: &str) -> Result<String, SyscallError> {
260    if !path.starts_with('/') {
261        return Err(SyscallError::InvalidArgument);
262    }
263    let mut out = String::new();
264    let mut prev_slash = false;
265    for ch in path.chars() {
266        if ch == '/' {
267            if !prev_slash {
268                out.push('/');
269            }
270            prev_slash = true;
271            continue;
272        }
273        if ch == '\0' {
274            return Err(SyscallError::InvalidArgument);
275        }
276        prev_slash = false;
277        out.push(ch);
278    }
279    while out.len() > 1 && out.ends_with('/') {
280        out.pop();
281    }
282    if out.is_empty() {
283        out.push('/');
284    }
285    Ok(out)
286}
287
288/// Performs the path rule matches operation.
289fn path_rule_matches(rule: &str, path: &str) -> bool {
290    if rule == "/" {
291        return true;
292    }
293    if path == rule {
294        return true;
295    }
296    if !path.starts_with(rule) {
297        return false;
298    }
299    let bytes = path.as_bytes();
300    let idx = rule.len();
301    idx < bytes.len() && bytes[idx] == b'/'
302}
303
304/// Performs the enforce path for current task operation.
305pub fn enforce_path_for_current_task(
306    path: &str,
307    want_read: bool,
308    want_write: bool,
309    want_execute: bool,
310) -> Result<(), SyscallError> {
311    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
312    if is_admin_task(&task) {
313        return Ok(());
314    }
315    let path = normalize_unveil_path(path)?;
316    let mgr = SILO_MANAGER.lock();
317    let Some(silo_id) = mgr.silo_for_task(task.id) else {
318        return Ok(());
319    };
320    let silo = mgr.get(silo_id)?;
321    if silo.sandboxed {
322        return Err(SyscallError::PermissionDenied);
323    }
324    if silo.unveil_rules.is_empty() {
325        return Ok(());
326    }
327    for rule in &silo.unveil_rules {
328        if !path_rule_matches(&rule.path, &path) {
329            continue;
330        }
331        if (!want_read || rule.rights.read)
332            && (!want_write || rule.rights.write)
333            && (!want_execute || rule.rights.execute)
334        {
335            return Ok(());
336        }
337    }
338    Err(SyscallError::PermissionDenied)
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342#[repr(C)]
343struct UnveilRights {
344    read: bool,
345    write: bool,
346    execute: bool,
347}
348
349impl UnveilRights {
350    /// Builds this from bits.
351    fn from_bits(bits: u64) -> Result<Self, SyscallError> {
352        if bits & !0x7 != 0 {
353            return Err(SyscallError::InvalidArgument);
354        }
355        Ok(Self {
356            read: (bits & 0x1) != 0,
357            write: (bits & 0x2) != 0,
358            execute: (bits & 0x4) != 0,
359        })
360    }
361
362    /// Performs the intersect operation.
363    fn intersect(self, other: Self) -> Self {
364        Self {
365            read: self.read && other.read,
366            write: self.write && other.write,
367            execute: self.execute && other.execute,
368        }
369    }
370}
371
372#[derive(Debug, Clone)]
373struct UnveilRule {
374    path: String,
375    rights: UnveilRights,
376}
377
378#[repr(u8)]
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum StrateFamily {
381    SYS = 0,
382    DRV = 1,
383    FS = 2,
384    NET = 3,
385    WASM = 4,
386    USR = 5,
387}
388
389#[repr(u32)]
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum SiloState {
392    Created = 0,
393    Loading = 1,
394    Ready = 2,
395    Running = 3,
396    Paused = 4,
397    Stopping = 5,
398    Stopped = 6,
399    Crashed = 7,
400    Zombie = 8,
401    Destroyed = 9,
402}
403
404pub const SILO_FLAG_ADMIN: u64 = 1 << 0;
405pub const SILO_FLAG_GRAPHICS: u64 = 1 << 1;
406pub const SILO_FLAG_WEBRTC_NATIVE: u64 = 1 << 2;
407pub const SILO_FLAG_GRAPHICS_READ_ONLY: u64 = 1 << 3;
408pub const SILO_FLAG_WEBRTC_TURN_FORCE: u64 = 1 << 4;
409
410#[repr(C)]
411#[derive(Debug, Clone, Copy)]
412pub struct SiloConfig {
413    pub mem_min: u64,
414    pub mem_max: u64,
415    pub cpu_shares: u32,
416    pub cpu_quota_us: u64,
417    pub cpu_period_us: u64,
418    pub cpu_affinity_mask: u64,
419    pub max_tasks: u32,
420    pub io_bw_read: u64,
421    pub io_bw_write: u64,
422    pub caps_ptr: u64,
423    pub caps_len: u64,
424    pub flags: u64,
425    pub sid: u32,
426    pub mode: u16,
427    pub family: u8,
428    /// CPU features that this silo requires (bitflags from `CpuFeatures`).
429    pub cpu_features_required: u64,
430    /// CPU features that this silo is allowed to use.
431    pub cpu_features_allowed: u64,
432    /// Effective XCR0 mask (computed from allowed features & host capabilities).
433    pub xcr0_mask: u64,
434    /// Maximum concurrent graphics sessions for this silo (0 = disabled).
435    pub graphics_max_sessions: u16,
436    /// Graphics session time-to-live in seconds.
437    pub graphics_session_ttl_sec: u32,
438    /// Reserved for ABI expansion.
439    pub graphics_reserved: u16,
440}
441
442impl Default for SiloConfig {
443    fn default() -> Self {
444        SiloConfig {
445            mem_min: 0,
446            mem_max: 0,
447            cpu_shares: 0,
448            cpu_quota_us: 0,
449            cpu_period_us: 0,
450            cpu_affinity_mask: 0,
451            max_tasks: 0,
452            io_bw_read: 0,
453            io_bw_write: 0,
454            caps_ptr: 0,
455            caps_len: 0,
456            flags: 0,
457            sid: 42,
458            mode: 0,
459            family: StrateFamily::USR as u8,
460            cpu_features_required: 0,
461            cpu_features_allowed: u64::MAX,
462            xcr0_mask: 0,
463            graphics_max_sessions: 0,
464            graphics_session_ttl_sec: 0,
465            graphics_reserved: 0,
466        }
467    }
468}
469
470impl SiloConfig {
471    /// Performs the validate operation.
472    fn validate(&self) -> Result<(), SyscallError> {
473        if self.mem_min > self.mem_max && self.mem_max != 0 {
474            return Err(SyscallError::InvalidArgument);
475        }
476        if self.cpu_quota_us > 0 && self.cpu_period_us == 0 {
477            return Err(SyscallError::InvalidArgument);
478        }
479        if self.caps_len > MAX_SILO_CAPS as u64 {
480            return Err(SyscallError::InvalidArgument);
481        }
482        if self.caps_len > 0 && self.caps_ptr == 0 {
483            return Err(SyscallError::InvalidArgument);
484        }
485        if self.flags & SILO_FLAG_WEBRTC_NATIVE != 0 && self.flags & SILO_FLAG_GRAPHICS == 0 {
486            return Err(SyscallError::InvalidArgument);
487        }
488        if self.flags & SILO_FLAG_GRAPHICS == 0 {
489            if self.graphics_max_sessions != 0 || self.graphics_session_ttl_sec != 0 {
490                return Err(SyscallError::InvalidArgument);
491            }
492        } else {
493            if self.graphics_max_sessions == 0 {
494                return Err(SyscallError::InvalidArgument);
495            }
496            if self.graphics_session_ttl_sec == 0 {
497                return Err(SyscallError::InvalidArgument);
498            }
499        }
500        Ok(())
501    }
502}
503
504#[repr(C, packed)]
505#[derive(Clone, Copy)]
506pub struct Strat9ModuleHeader {
507    pub magic: [u8; 4], // "CMOD"
508    pub version: u16,
509    pub cpu_arch: u8, // 0 = x86_64
510    pub flags: u32,
511    pub code_offset: u64,
512    pub code_size: u64,
513    pub data_offset: u64,
514    pub data_size: u64,
515    pub bss_size: u64,
516    pub entry_point: u64,
517    pub export_table_offset: u64,
518    pub import_table_offset: u64,
519    pub relocation_table_offset: u64,
520    pub key_id: [u8; 8],
521    pub signature: [u8; 64],
522    /// CPU features required by this module (CpuFeatures bitflags). Header v2+.
523    pub cpu_features_required: u64,
524    pub reserved: [u8; 48],
525}
526
527impl core::fmt::Debug for Strat9ModuleHeader {
528    /// Performs the fmt operation.
529    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
530        // SAFETY: read fields via read_unaligned to avoid UB on packed struct.
531        let version = unsafe { core::ptr::addr_of!(self.version).read_unaligned() };
532        let flags = unsafe { core::ptr::addr_of!(self.flags).read_unaligned() };
533        let entry = unsafe { core::ptr::addr_of!(self.entry_point).read_unaligned() };
534        let code_sz = unsafe { core::ptr::addr_of!(self.code_size).read_unaligned() };
535        let data_sz = unsafe { core::ptr::addr_of!(self.data_size).read_unaligned() };
536        f.debug_struct("Strat9ModuleHeader")
537            .field("magic", &self.magic)
538            .field("version", &version)
539            .field("cpu_arch", &self.cpu_arch)
540            .field("flags", &flags)
541            .field("entry_point", &entry)
542            .field("code_size", &code_sz)
543            .field("data_size", &data_sz)
544            .finish_non_exhaustive()
545    }
546}
547
548#[repr(C)]
549#[derive(Debug, Clone, Copy)]
550pub struct ModuleInfo {
551    pub id: u64,
552    pub format: u32, // 0 = raw/ELF, 1 = CMOD
553    pub flags: u32,
554    pub version: u16,
555    pub cpu_arch: u8,
556    pub reserved: u8,
557    pub code_size: u64,
558    pub data_size: u64,
559    pub bss_size: u64,
560    pub entry_point: u64,
561    pub total_size: u64,
562}
563
564#[repr(u32)]
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566pub enum SiloEventKind {
567    Started = 1,
568    Stopped = 2,
569    Killed = 3,
570    Crashed = 4,
571    Paused = 5,
572    Resumed = 6,
573}
574
575#[repr(u64)]
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub enum SiloFaultReason {
578    PageFault = 1,
579    GeneralProtection = 2,
580    InvalidOpcode = 3,
581}
582
583#[repr(C)]
584#[derive(Debug, Clone, Copy)]
585pub struct SiloEvent {
586    pub silo_id: u64,
587    pub kind: SiloEventKind,
588    pub data0: u64,
589    pub data1: u64,
590    pub tick: u64,
591}
592
593// data0 encoding for Crashed:
594// - bits 0..15: fault reason (SiloFaultReason)
595// - bits 16..31: fault subcode (arch-specific)
596// - bits 32..63: reserved
597pub const FAULT_SUBCODE_SHIFT: u64 = 16;
598
599/// Performs the pack fault operation.
600pub fn pack_fault(reason: SiloFaultReason, subcode: u64) -> u64 {
601    (reason as u64) | (subcode << FAULT_SUBCODE_SHIFT)
602}
603
604// ============================================================================
605// Internal kernel structs
606// ============================================================================
607
608#[derive(Debug)]
609struct Silo {
610    id: SiloId,
611    name: String,
612    strate_label: Option<String>,
613    state: SiloState,
614    config: SiloConfig,
615    mode: OctalMode,
616    family: StrateFamily,
617    /// Current memory usage accounted to this silo (bytes).
618    /// This tracks user-space virtual regions reserved/mapped via AddressSpace APIs.
619    mem_usage_bytes: u64,
620    flags: u32,
621    module_id: Option<u64>,
622    tasks: HVec<TaskId, 64>,
623    granted_caps: HVec<u64, 64>,
624    granted_resources: HVec<GrantedResource, 32>,
625    unveil_rules: HVec<UnveilRule, 128>,
626    sandboxed: bool,
627    event_seq: u64,
628    /// Ring buffer capturing debug output for `silo attach`.
629    output_buf: Option<Box<SiloOutputBuf>>,
630}
631
632const SILO_OUTPUT_CAPACITY: usize = 4096;
633
634struct SiloOutputBuf {
635    buf: [u8; SILO_OUTPUT_CAPACITY],
636    head: usize,
637    count: usize,
638}
639
640impl core::fmt::Debug for SiloOutputBuf {
641    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
642        f.debug_struct("SiloOutputBuf")
643            .field("count", &self.count)
644            .finish()
645    }
646}
647
648impl SiloOutputBuf {
649    const fn new() -> Self {
650        Self {
651            buf: [0; SILO_OUTPUT_CAPACITY],
652            head: 0,
653            count: 0,
654        }
655    }
656
657    fn push(&mut self, data: &[u8]) {
658        for &b in data {
659            let tail = (self.head + self.count) % SILO_OUTPUT_CAPACITY;
660            self.buf[tail] = b;
661            if self.count < SILO_OUTPUT_CAPACITY {
662                self.count += 1;
663            } else {
664                self.head = (self.head + 1) % SILO_OUTPUT_CAPACITY;
665            }
666        }
667    }
668
669    fn drain(&mut self) -> Vec<u8> {
670        let mut out = Vec::with_capacity(self.count);
671        for i in 0..self.count {
672            out.push(self.buf[(self.head + i) % SILO_OUTPUT_CAPACITY]);
673        }
674        self.head = 0;
675        self.count = 0;
676        out
677    }
678}
679
680#[derive(Debug, Clone)]
681pub struct SiloSnapshot {
682    pub id: u32,
683    pub tier: SiloTier,
684    pub name: String,
685    pub strate_label: Option<String>,
686    pub state: SiloState,
687    pub task_count: usize,
688    pub mem_usage_bytes: u64,
689    pub mem_min_bytes: u64,
690    pub mem_max_bytes: u64,
691    pub mode: u16,
692    pub graphics_flags: u64,
693    pub graphics_max_sessions: u16,
694    pub graphics_session_ttl_sec: u32,
695}
696
697#[derive(Debug, Clone)]
698pub struct SiloDetailSnapshot {
699    pub base: SiloSnapshot,
700    pub family: StrateFamily,
701    pub sandboxed: bool,
702    pub cpu_shares: u32,
703    pub cpu_affinity_mask: u64,
704    pub max_tasks: u32,
705    pub task_ids: Vec<u64>,
706    pub unveil_rules: Vec<(String, u8)>,
707    pub granted_caps_count: usize,
708    pub cpu_features_required: u64,
709    pub cpu_features_allowed: u64,
710    pub xcr0_mask: u64,
711    pub graphics_flags: u64,
712    pub graphics_max_sessions: u16,
713    pub graphics_session_ttl_sec: u32,
714}
715
716#[derive(Debug, Clone)]
717pub struct SiloEventSnapshot {
718    pub silo_id: u64,
719    pub kind: SiloEventKind,
720    pub data0: u64,
721    pub data1: u64,
722    pub tick: u64,
723}
724
725struct SiloManager {
726    silos: BTreeMap<u32, Box<Silo>>,
727    events: FixedQueue<SiloEvent, SILO_EVENTS_CAPACITY>,
728    task_to_silo: BTreeMap<TaskId, u32>,
729}
730
731const SILO_EVENTS_CAPACITY: usize = 256;
732
733impl SiloManager {
734    /// Creates a new instance.
735    const fn new() -> Self {
736        SiloManager {
737            silos: BTreeMap::new(),
738            events: FixedQueue::new(),
739            task_to_silo: BTreeMap::new(),
740        }
741    }
742
743    /// Creates silo.
744    fn create_silo(&mut self, config: &SiloConfig) -> Result<SiloId, SyscallError> {
745        let id = SiloId::new(config.sid);
746        if self.silos.contains_key(&id.sid) {
747            return Err(SyscallError::AlreadyExists);
748        }
749
750        kernel_check_spawn_invariants(&id, &OctalMode::from_octal(config.mode))?;
751
752        let mut name = String::from("silo-");
753        name.push_str(&id.sid.to_string());
754
755        let family = decode_family(config.family)?;
756
757        let silo = Silo {
758            id,
759            name,
760            strate_label: None,
761            state: SiloState::Created,
762            config: *config,
763            mode: OctalMode::from_octal(config.mode),
764            family,
765            mem_usage_bytes: 0,
766            flags: config.flags as u32,
767            module_id: None,
768            tasks: HVec::new(),
769            granted_caps: HVec::new(),
770            granted_resources: HVec::new(),
771            unveil_rules: HVec::new(),
772            sandboxed: false,
773            event_seq: 0,
774            output_buf: None,
775        };
776
777        self.silos.insert(id.sid, Box::new(silo));
778        Ok(id)
779    }
780
781    /// Returns mut.
782    fn get_mut(&mut self, id: u32) -> Result<&mut Silo, SyscallError> {
783        self.silos
784            .get_mut(&id)
785            .map(Box::as_mut)
786            .ok_or(SyscallError::BadHandle)
787    }
788
789    /// Performs the get operation.
790    fn get(&self, id: u32) -> Result<&Silo, SyscallError> {
791        self.silos
792            .get(&id)
793            .map(Box::as_ref)
794            .ok_or(SyscallError::BadHandle)
795    }
796
797    /// Performs the push event operation.
798    fn push_event(&mut self, ev: SiloEvent) {
799        if self.events.is_full() {
800            let _ = self.events.pop_front();
801        }
802        self.events
803            .push_back(ev)
804            .expect("silo event queue push must succeed after dropping oldest entry");
805    }
806
807    /// Maps task.
808    fn map_task(&mut self, task_id: TaskId, silo_id: u32) {
809        crate::serial_println!(
810            "[trace][silo] map_task enter tid={} sid={} len={}",
811            task_id.as_u64(),
812            silo_id,
813            self.task_to_silo.len()
814        );
815        let existed = self.task_to_silo.contains_key(&task_id);
816        crate::serial_println!(
817            "[trace][silo] map_task before insert tid={} sid={} existed={}",
818            task_id.as_u64(),
819            silo_id,
820            existed
821        );
822        self.task_to_silo.insert(task_id, silo_id);
823        crate::serial_println!(
824            "[trace][silo] map_task after insert tid={} sid={} len={}",
825            task_id.as_u64(),
826            silo_id,
827            self.task_to_silo.len()
828        );
829    }
830
831    /// Unmaps task.
832    fn unmap_task(&mut self, task_id: TaskId) {
833        self.task_to_silo.remove(&task_id);
834    }
835
836    /// Performs the silo for task operation.
837    fn silo_for_task(&self, task_id: TaskId) -> Option<u32> {
838        if let Some(silo_id) = self.task_to_silo.get(&task_id).copied() {
839            return Some(silo_id);
840        }
841
842        // Critical boot fallback: boot-time registration avoids BTreeMap inserts
843        // while holding SILO_MANAGER to eliminate allocator re-entrancy risk on
844        // the fragile early-init path.
845        self.silos
846            .iter()
847            .find_map(|(sid, silo)| silo.tasks.iter().any(|tid| *tid == task_id).then_some(*sid))
848    }
849}
850
851/// Performs the kernel check spawn invariants operation.
852pub fn kernel_check_spawn_invariants(id: &SiloId, mode: &OctalMode) -> Result<(), SyscallError> {
853    if id.tier == SiloTier::User && !mode.hardware.is_empty() {
854        return Err(SyscallError::PermissionDenied);
855    }
856    if id.tier == SiloTier::User && !mode.control.is_empty() {
857        return Err(SyscallError::PermissionDenied);
858    }
859    Ok(())
860}
861
862/// Performs the decode family operation.
863fn decode_family(raw: u8) -> Result<StrateFamily, SyscallError> {
864    match raw {
865        0 => Ok(StrateFamily::SYS),
866        1 => Ok(StrateFamily::DRV),
867        2 => Ok(StrateFamily::FS),
868        3 => Ok(StrateFamily::NET),
869        4 => Ok(StrateFamily::WASM),
870        5 => Ok(StrateFamily::USR),
871        _ => Err(SyscallError::InvalidArgument),
872    }
873}
874
875static SILO_MANAGER: SpinLock<SiloManager> = SpinLock::new(SiloManager::new());
876static BOOT_REG_IN_PROGRESS: core::sync::atomic::AtomicBool =
877    core::sync::atomic::AtomicBool::new(false);
878
879const SILO_ADMIN_RESOURCE: usize = 0;
880const MAX_SILO_CAPS: usize = 64;
881const MAX_MODULE_BLOB_LEN: usize = 64 * 1024 * 1024; // 64 MiB for large preloaded user modules such as strate-wasm
882const IPC_STREAM_DATA: u32 = 0xFFFF_FFFE;
883const IPC_STREAM_EOF: u32 = 0xFFFF_FFFF;
884const MODULE_FLAG_SIGNED: u32 = 1 << 0;
885const MODULE_FLAG_KERNEL: u32 = 1 << 1;
886
887/// Reads user config.
888fn read_user_config(ptr: u64) -> Result<SiloConfig, SyscallError> {
889    if ptr == 0 {
890        return Err(SyscallError::Fault);
891    }
892    const SIZE: usize = core::mem::size_of::<SiloConfig>();
893    let user = UserSliceRead::new(ptr, SIZE)?;
894    let mut buf = [0u8; SIZE];
895    user.copy_to(&mut buf);
896    // SAFETY: We copied the exact bytes for SiloConfig from userspace.
897    let config = unsafe { core::ptr::read_unaligned(buf.as_ptr() as *const SiloConfig) };
898    Ok(config)
899}
900
901/// Reads caps list.
902fn read_caps_list(ptr: u64, len: u64) -> Result<Vec<u64>, SyscallError> {
903    if len == 0 {
904        return Ok(Vec::new());
905    }
906    if len > MAX_SILO_CAPS as u64 {
907        return Err(SyscallError::InvalidArgument);
908    }
909    let byte_len = len as usize * core::mem::size_of::<u64>();
910    let user = UserSliceRead::new(ptr, byte_len)?;
911    let bytes = user.read_to_vec();
912    let mut out = Vec::with_capacity(len as usize);
913    for chunk in bytes.chunks_exact(8) {
914        let mut arr = [0u8; 8];
915        arr.copy_from_slice(chunk);
916        out.push(u64::from_le_bytes(arr));
917    }
918    Ok(out)
919}
920
921/// Reads module stream from port.
922fn read_module_stream_from_port(
923    port: &alloc::sync::Arc<port::Port>,
924) -> Result<Vec<u8>, SyscallError> {
925    let mut out = Vec::new();
926    loop {
927        let msg = port.recv().map_err(|_| SyscallError::BadHandle)?;
928
929        if msg.msg_type == IPC_STREAM_EOF {
930            break;
931        }
932        if msg.msg_type != IPC_STREAM_DATA {
933            return Err(SyscallError::InvalidArgument);
934        }
935        if msg.flags != 0 {
936            return Err(SyscallError::InvalidArgument);
937        }
938
939        let chunk_len = u16::from_le_bytes([msg.payload[0], msg.payload[1]]) as usize;
940        if chunk_len == 0 {
941            break;
942        }
943        if chunk_len > msg.payload.len() - 2 {
944            return Err(SyscallError::InvalidArgument);
945        }
946        if out.len().saturating_add(chunk_len) > MAX_MODULE_BLOB_LEN {
947            return Err(SyscallError::InvalidArgument);
948        }
949
950        out.extend_from_slice(&msg.payload[2..2 + chunk_len]);
951    }
952    Ok(out)
953}
954
955/// Parses module header.
956fn parse_module_header(data: &[u8]) -> Result<Option<Strat9ModuleHeader>, SyscallError> {
957    const MAGIC: [u8; 4] = *b"CMOD";
958    let header_size = core::mem::size_of::<Strat9ModuleHeader>();
959
960    if data.len() < MAGIC.len() {
961        return Ok(None);
962    }
963    if data[0..4] != MAGIC {
964        return Ok(None);
965    }
966    if data.len() < header_size {
967        return Err(SyscallError::InvalidArgument);
968    }
969
970    // SAFETY: We checked length, and we read unaligned from a byte slice.
971    let header = unsafe { core::ptr::read_unaligned(data.as_ptr() as *const Strat9ModuleHeader) };
972
973    if header.version != 1 && header.version != 2 {
974        return Err(SyscallError::InvalidArgument);
975    }
976    if header.cpu_arch != 0 {
977        return Err(SyscallError::InvalidArgument);
978    }
979
980    let version = unsafe { core::ptr::addr_of!(header.version).read_unaligned() };
981    let req = if version >= 2 {
982        unsafe { core::ptr::addr_of!(header.cpu_features_required).read_unaligned() }
983    } else {
984        0
985    };
986    if req != 0 {
987        let host = crate::arch::x86_64::cpuid::host();
988        let required = crate::arch::x86_64::cpuid::CpuFeatures::from_bits_truncate(req);
989        if !host.features.contains(required) {
990            log::warn!(
991                "[cmod] module requires CPU features {:#x} but host has {:#x}",
992                req,
993                host.features.bits()
994            );
995            return Err(SyscallError::InvalidArgument);
996        }
997    }
998
999    let data_len = data.len() as u64;
1000    let code_end = header
1001        .code_offset
1002        .checked_add(header.code_size)
1003        .ok_or(SyscallError::InvalidArgument)?;
1004    let data_end = header
1005        .data_offset
1006        .checked_add(header.data_size)
1007        .ok_or(SyscallError::InvalidArgument)?;
1008    if code_end > data_len || data_end > data_len {
1009        return Err(SyscallError::InvalidArgument);
1010    }
1011    if header.entry_point >= header.code_size && header.code_size != 0 {
1012        return Err(SyscallError::InvalidArgument);
1013    }
1014    if header.export_table_offset > data_len
1015        || header.import_table_offset > data_len
1016        || header.relocation_table_offset > data_len
1017    {
1018        return Err(SyscallError::InvalidArgument);
1019    }
1020
1021    // Segmentation rules: code/data must not overlap and must be page-aligned.
1022    const PAGE_SIZE: u64 = 4096;
1023    if header.code_size > 0 {
1024        if header.code_offset % PAGE_SIZE != 0 || header.code_size % PAGE_SIZE != 0 {
1025            return Err(SyscallError::InvalidArgument);
1026        }
1027    }
1028    if header.data_size > 0 {
1029        if header.data_offset % PAGE_SIZE != 0 || header.data_size % PAGE_SIZE != 0 {
1030            return Err(SyscallError::InvalidArgument);
1031        }
1032    }
1033    let code_range = header.code_offset..code_end;
1034    let data_range = header.data_offset..data_end;
1035    if code_range.start < data_range.end && data_range.start < code_range.end {
1036        return Err(SyscallError::InvalidArgument);
1037    }
1038
1039    // Flags/signature checks (verification is TODO).
1040    if header.flags & MODULE_FLAG_SIGNED != 0 {
1041        let sig_nonzero = header.signature.iter().any(|b| *b != 0);
1042        let key_nonzero = header.key_id.iter().any(|b| *b != 0);
1043        if !sig_nonzero || !key_nonzero {
1044            return Err(SyscallError::PermissionDenied);
1045        }
1046    }
1047    if header.flags & MODULE_FLAG_KERNEL != 0 {
1048        // Kernel modules are allowed only when loaded by admin (already enforced).
1049    }
1050
1051    Ok(Some(header))
1052}
1053
1054/// Reads u32 le.
1055fn read_u32_le(data: &[u8], offset: usize) -> Result<u32, SyscallError> {
1056    if offset + 4 > data.len() {
1057        return Err(SyscallError::InvalidArgument);
1058    }
1059    let mut buf = [0u8; 4];
1060    buf.copy_from_slice(&data[offset..offset + 4]);
1061    Ok(u32::from_le_bytes(buf))
1062}
1063
1064/// Reads u64 le.
1065fn read_u64_le(data: &[u8], offset: usize) -> Result<u64, SyscallError> {
1066    if offset + 8 > data.len() {
1067        return Err(SyscallError::InvalidArgument);
1068    }
1069    let mut buf = [0u8; 8];
1070    buf.copy_from_slice(&data[offset..offset + 8]);
1071    Ok(u64::from_le_bytes(buf))
1072}
1073
1074/// Performs the resolve export offset operation.
1075fn resolve_export_offset(module: &ModuleImage, ordinal: u64) -> Result<u64, SyscallError> {
1076    let header = module.header.ok_or(SyscallError::InvalidArgument)?;
1077    if header.export_table_offset == 0 {
1078        return Err(SyscallError::NotFound);
1079    }
1080    let table_off = header.export_table_offset as usize;
1081    let count = read_u32_le(module.data.as_slice(), table_off)? as u64;
1082    if ordinal >= count {
1083        return Err(SyscallError::InvalidArgument);
1084    }
1085    // Layout: u32 count + u32 reserved, then u64 entries.
1086    let entries_off = table_off + 8;
1087    let entry_off = entries_off + (ordinal as usize * 8);
1088    let rva = read_u64_le(module.data.as_slice(), entry_off)?;
1089    Ok(rva)
1090}
1091
1092/// Performs the require silo admin operation.
1093pub fn require_silo_admin() -> Result<(), SyscallError> {
1094    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1095    // SAFETY: Current task owns its capability table during syscall execution.
1096    let caps = unsafe { &*task.process.capabilities.get() };
1097    let required = CapPermissions {
1098        read: false,
1099        write: false,
1100        execute: false,
1101        grant: true,
1102        revoke: false,
1103    };
1104
1105    if caps.has_resource_with_permissions(ResourceType::Silo, SILO_ADMIN_RESOURCE, required) {
1106        Ok(())
1107    } else {
1108        Err(SyscallError::PermissionDenied)
1109    }
1110}
1111
1112/// Performs the resolve silo handle operation.
1113fn resolve_silo_handle(handle: u64, required: CapPermissions) -> Result<u32, SyscallError> {
1114    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1115    let caps = unsafe { &*task.process.capabilities.get() };
1116    let cap_id = CapId::from_raw(handle);
1117    let cap = caps.get(cap_id).ok_or(SyscallError::BadHandle)?;
1118
1119    // Ensure this is a Silo capability and permissions are sufficient.
1120    if cap.resource_type != ResourceType::Silo {
1121        return Err(SyscallError::BadHandle);
1122    }
1123
1124    if (!required.read || cap.permissions.read)
1125        && (!required.write || cap.permissions.write)
1126        && (!required.execute || cap.permissions.execute)
1127        && (!required.grant || cap.permissions.grant)
1128        && (!required.revoke || cap.permissions.revoke)
1129    {
1130        Ok(cap.resource as u32)
1131    } else {
1132        Err(SyscallError::PermissionDenied)
1133    }
1134}
1135
1136// ============================================================================
1137// Module registry (temporary blob store for .cmod/ELF)
1138// ============================================================================
1139
1140#[derive(Debug, Clone)]
1141enum ModuleData {
1142    Owned(Arc<[u8]>),
1143    Static(&'static [u8]),
1144}
1145
1146impl ModuleData {
1147    fn as_slice(&self) -> &[u8] {
1148        match self {
1149            ModuleData::Owned(data) => data,
1150            ModuleData::Static(data) => data,
1151        }
1152    }
1153
1154    fn len(&self) -> usize {
1155        self.as_slice().len()
1156    }
1157}
1158
1159#[derive(Debug)]
1160struct ModuleImage {
1161    id: u64,
1162    data: ModuleData,
1163    header: Option<Strat9ModuleHeader>,
1164}
1165
1166struct ModuleRegistry {
1167    modules: BTreeMap<u64, ModuleImage>,
1168}
1169
1170impl ModuleRegistry {
1171    /// Creates a new instance.
1172    const fn new() -> Self {
1173        ModuleRegistry {
1174            modules: BTreeMap::new(),
1175        }
1176    }
1177
1178    /// Performs the register operation.
1179    fn register(&mut self, data: Vec<u8>) -> Result<u64, SyscallError> {
1180        let header = parse_module_header(&data)?;
1181        static NEXT_MOD: AtomicU64 = AtomicU64::new(1);
1182        let id = NEXT_MOD.fetch_add(1, Ordering::Relaxed);
1183        self.modules.insert(
1184            id,
1185            ModuleImage {
1186                id,
1187                data: ModuleData::Owned(Arc::from(data.into_boxed_slice())),
1188                header,
1189            },
1190        );
1191        Ok(id)
1192    }
1193
1194    fn register_static(&mut self, data: &'static [u8]) -> Result<u64, SyscallError> {
1195        let header = parse_module_header(data)?;
1196        static NEXT_MOD: AtomicU64 = AtomicU64::new(1);
1197        let id = NEXT_MOD.fetch_add(1, Ordering::Relaxed);
1198        self.modules.insert(
1199            id,
1200            ModuleImage {
1201                id,
1202                data: ModuleData::Static(data),
1203                header,
1204            },
1205        );
1206        Ok(id)
1207    }
1208
1209    /// Performs the get operation.
1210    fn get(&self, id: u64) -> Option<&ModuleImage> {
1211        self.modules.get(&id)
1212    }
1213
1214    /// Performs the remove operation.
1215    fn remove(&mut self, id: u64) -> Option<ModuleImage> {
1216        self.modules.remove(&id)
1217    }
1218}
1219
1220static MODULE_REGISTRY: SpinLock<ModuleRegistry> = SpinLock::new(ModuleRegistry::new());
1221
1222/// Performs the charge task silo memory operation.
1223fn charge_task_silo_memory(task_id: TaskId, bytes: u64) -> Result<(), SyscallError> {
1224    if bytes == 0 {
1225        return Ok(());
1226    }
1227    let mut mgr = SILO_MANAGER.lock();
1228    let Some(silo_id) = mgr.silo_for_task(task_id) else {
1229        return Ok(());
1230    };
1231    let silo = mgr.get_mut(silo_id)?;
1232    let next = silo
1233        .mem_usage_bytes
1234        .checked_add(bytes)
1235        .ok_or(SyscallError::OutOfMemory)?;
1236    if silo.config.mem_max != 0 && next > silo.config.mem_max {
1237        return Err(SyscallError::OutOfMemory);
1238    }
1239    silo.mem_usage_bytes = next;
1240    Ok(())
1241}
1242
1243/// Performs the release task silo memory operation.
1244fn release_task_silo_memory(task_id: TaskId, bytes: u64) {
1245    if bytes == 0 {
1246        return;
1247    }
1248    let mut mgr = SILO_MANAGER.lock();
1249    let Some(silo_id) = mgr.silo_for_task(task_id) else {
1250        return;
1251    };
1252    if let Ok(silo) = mgr.get_mut(silo_id) {
1253        silo.mem_usage_bytes = silo.mem_usage_bytes.saturating_sub(bytes);
1254    }
1255}
1256
1257/// Charge memory usage against the current task's silo quota (if any).
1258///
1259/// Returns `OutOfMemory` when charging would exceed `SiloConfig.mem_max`.
1260/// Tasks that are not part of a silo are ignored.
1261pub fn charge_current_task_memory(bytes: u64) -> Result<(), SyscallError> {
1262    let Some(task) = crate::process::scheduler::current_task_clone_try() else {
1263        // Boot-time/kernel contexts may have no current task.
1264        // Also avoid deadlock when scheduler lock is already held in cleanup paths.
1265        return Ok(());
1266    };
1267    charge_task_silo_memory(task.id, bytes)
1268}
1269
1270/// Release memory usage from the current task's silo quota (if any).
1271///
1272/// Tasks that are not part of a silo are ignored.
1273pub fn release_current_task_memory(bytes: u64) {
1274    if let Some(task) = crate::process::scheduler::current_task_clone_try() {
1275        release_task_silo_memory(task.id, bytes);
1276    }
1277}
1278
1279/// Performs the extract strate label operation.
1280fn extract_strate_label(path: &str) -> Option<String> {
1281    let prefix = "/srv/strate-fs-";
1282    let rest = path.strip_prefix(prefix)?;
1283    let mut parts = rest.split('/').filter(|p| !p.is_empty());
1284    let _strate_type = parts.next()?;
1285    let label = parts.next()?;
1286    if label.is_empty() || parts.next().is_some() {
1287        return None;
1288    }
1289    Some(String::from(label))
1290}
1291
1292/// Performs the sanitize label operation.
1293fn sanitize_label(raw: &str) -> String {
1294    let mut out = String::new();
1295    for b in raw.bytes().take(31) {
1296        let ok = (b as char).is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.';
1297        out.push(if ok { b as char } else { '_' });
1298    }
1299    if out.is_empty() {
1300        String::from("default")
1301    } else {
1302        out
1303    }
1304}
1305
1306/// Returns whether valid label.
1307fn is_valid_label(raw: &str) -> bool {
1308    if raw.is_empty() || raw.len() > 31 {
1309        return false;
1310    }
1311    raw.bytes()
1312        .all(|b| (b as char).is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')
1313}
1314
1315/// Sets current silo label from path.
1316pub fn set_current_silo_label_from_path(path: &str) -> Result<(), SyscallError> {
1317    let Some(label) = extract_strate_label(path) else {
1318        return Ok(());
1319    };
1320    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1321    let mut mgr = SILO_MANAGER.lock();
1322    let Some(silo_id) = mgr.silo_for_task(task.id) else {
1323        return Ok(());
1324    };
1325    let silo = mgr.get_mut(silo_id)?;
1326    // Do not overwrite a label that was already set (e.g. by kernel_spawn_strate).
1327    // The spawner's requested label takes precedence over the default path-derived one.
1328    if silo.strate_label.is_none() {
1329        silo.strate_label = Some(label);
1330    }
1331    Ok(())
1332}
1333
1334/// Performs the current task silo label operation.
1335pub fn current_task_silo_label() -> Option<String> {
1336    let task = current_task_clone()?;
1337    let mgr = SILO_MANAGER.lock();
1338    let silo_id = mgr.silo_for_task(task.id)?;
1339    let silo = mgr.get(silo_id).ok()?;
1340    silo.strate_label.clone()
1341}
1342
1343/// Performs the list silos snapshot operation.
1344pub fn list_silos_snapshot() -> Vec<SiloSnapshot> {
1345    let mgr = SILO_MANAGER.lock();
1346    mgr.silos
1347        .values()
1348        .map(|s| SiloSnapshot {
1349            id: s.id.sid,
1350            tier: s.id.tier,
1351            name: s.name.clone(),
1352            strate_label: s.strate_label.clone(),
1353            state: s.state,
1354            task_count: s.tasks.len(),
1355            mem_usage_bytes: s.mem_usage_bytes,
1356            mem_min_bytes: s.config.mem_min,
1357            mem_max_bytes: s.config.mem_max,
1358            mode: s.config.mode,
1359            graphics_flags: s.config.flags
1360                & (SILO_FLAG_GRAPHICS
1361                    | SILO_FLAG_WEBRTC_NATIVE
1362                    | SILO_FLAG_GRAPHICS_READ_ONLY
1363                    | SILO_FLAG_WEBRTC_TURN_FORCE),
1364            graphics_max_sessions: s.config.graphics_max_sessions,
1365            graphics_session_ttl_sec: s.config.graphics_session_ttl_sec,
1366        })
1367        .collect()
1368}
1369
1370/// Return silo identity + memory accounting for a task, if the task belongs to a silo.
1371///
1372/// Tuple layout:
1373/// - silo id (u32)
1374/// - optional label
1375/// - current usage bytes
1376/// - configured minimum bytes
1377/// - configured maximum bytes (0 = unlimited)
1378/// Best-effort, non-blocking silo lookup for allocator-internal accounting.
1379///
1380/// Uses `try_lock` so that callers running under IRQs-disabled conditions
1381/// (e.g. inside vmalloc) do not deadlock when SILO_MANAGER is already held
1382/// by an outer call on the same CPU.  Returns `None` if the lock is contended
1383/// or if the task is not registered in any silo.
1384pub fn try_silo_id_for_task(task_id: TaskId) -> Option<u32> {
1385    SILO_MANAGER.try_lock()?.silo_for_task(task_id)
1386}
1387
1388pub fn silo_info_for_task(task_id: TaskId) -> Option<(u32, Option<String>, u64, u64, u64)> {
1389    let mgr = SILO_MANAGER.lock();
1390    let silo_id = mgr.silo_for_task(task_id)?;
1391    let silo = mgr.get(silo_id).ok()?;
1392    Some((
1393        silo.id.sid,
1394        silo.strate_label.clone(),
1395        silo.mem_usage_bytes,
1396        silo.config.mem_min,
1397        silo.config.mem_max,
1398    ))
1399}
1400
1401/// Performs the resolve volume resource from dev path operation.
1402fn resolve_volume_resource_from_dev_path(dev_path: &str) -> Result<usize, SyscallError> {
1403    match dev_path {
1404        "/dev/sda" => ahci::get_device()
1405            .map(|d| d as *const _ as usize)
1406            .ok_or(SyscallError::NotFound),
1407        "/dev/vda" => virtio_block::get_device()
1408            .map(|d| d as *const _ as usize)
1409            .ok_or(SyscallError::NotFound),
1410        _ => Err(SyscallError::NotFound),
1411    }
1412}
1413
1414/// Compute the effective XCR0 mask for a silo from its allowed CPU features.
1415fn compute_silo_xcr0(config: &SiloConfig) -> u64 {
1416    use crate::arch::x86_64::cpuid::{xcr0_for_features, CpuFeatures};
1417    let allowed = CpuFeatures::from_bits_truncate(config.cpu_features_allowed);
1418    xcr0_for_features(allowed)
1419}
1420
1421/// Performs the kernel spawn strate operation.
1422pub fn kernel_spawn_strate(
1423    elf_data: &[u8],
1424    label: Option<&str>,
1425    dev_path: Option<&str>,
1426) -> Result<u32, SyscallError> {
1427    let module_id = {
1428        let mut registry = MODULE_REGISTRY.lock();
1429        registry.register(elf_data.to_vec())?
1430    };
1431
1432    let silo_id = {
1433        let mut mgr = SILO_MANAGER.lock();
1434        // For kernel_spawn_strate (manual command), we auto-assign SID > 1000.
1435        // In a production system, this would follow the "42" rule from Init.
1436        let mut sid = 1000u32;
1437        while mgr.silos.contains_key(&sid) {
1438            sid = sid.checked_add(1).ok_or(SyscallError::OutOfMemory)?;
1439        }
1440
1441        let id = SiloId::new(sid);
1442        let requested_label = label
1443            .map(sanitize_label)
1444            .unwrap_or_else(|| alloc::format!("inst-{}", id.sid));
1445
1446        if mgr
1447            .silos
1448            .values()
1449            .any(|s| s.strate_label.as_deref() == Some(requested_label.as_str()))
1450        {
1451            return Err(SyscallError::AlreadyExists);
1452        }
1453
1454        let mut cfg = SiloConfig {
1455            sid: id.sid,
1456            mode: 0o000,
1457            family: StrateFamily::USR as u8,
1458            ..SiloConfig::default()
1459        };
1460        cfg.xcr0_mask = compute_silo_xcr0(&cfg);
1461
1462        let silo = Silo {
1463            id,
1464            name: alloc::format!("silo-{}", id.sid),
1465            strate_label: Some(requested_label),
1466            state: SiloState::Ready,
1467            config: cfg,
1468            mode: OctalMode::from_octal(0),
1469            family: StrateFamily::USR,
1470            mem_usage_bytes: 0,
1471            flags: 0,
1472            module_id: Some(module_id),
1473            tasks: HVec::new(),
1474            granted_caps: HVec::new(),
1475            granted_resources: HVec::new(),
1476            unveil_rules: HVec::new(),
1477            sandboxed: false,
1478            event_seq: 0,
1479            output_buf: None,
1480        };
1481
1482        mgr.silos.insert(id.sid, Box::new(silo));
1483        id.sid
1484    };
1485
1486    let module_data = {
1487        let registry = MODULE_REGISTRY.lock();
1488        let module = registry.get(module_id).ok_or(SyscallError::BadHandle)?;
1489        module.data.clone()
1490    };
1491
1492    let mut seed_caps = Vec::new();
1493    seed_caps.push(create_silo_admin_capability());
1494    if let Some(path) = dev_path {
1495        let resource = resolve_volume_resource_from_dev_path(path)?;
1496        let cap = get_capability_manager().create_capability(
1497            ResourceType::Volume,
1498            resource,
1499            CapPermissions {
1500                read: true,
1501                write: true,
1502                execute: false,
1503                grant: true,
1504                revoke: true,
1505            },
1506        );
1507        seed_caps.push(cap);
1508    }
1509
1510    let display = {
1511        let mgr = SILO_MANAGER.lock();
1512        let silo = mgr.get(silo_id)?;
1513        silo.strate_label
1514            .clone()
1515            .unwrap_or_else(|| alloc::format!("silo-{}", silo.id.sid))
1516    };
1517    let task_name: &'static str =
1518        Box::leak(alloc::format!("silo-{}/strate-admin-{}", silo_id, display).into_boxed_str());
1519    let task =
1520        crate::process::elf::load_elf_task_with_caps(module_data.as_slice(), task_name, &seed_caps)
1521            .map_err(|_| SyscallError::InvalidArgument)?;
1522    let task_id = task.id;
1523
1524    let mut mgr = SILO_MANAGER.lock();
1525    {
1526        let silo = mgr.get_mut(silo_id)?;
1527        if let Err(task) = silo.tasks.push(task_id) {
1528            log::error!(
1529                "[silo] tasks full (capacity=64), task {} not registered",
1530                task.0
1531            );
1532        }
1533        silo.state = SiloState::Running;
1534        let fpu_xcr0 = unsafe { (*task.fpu_state.get()).xcr0_mask };
1535        let effective_xcr0 = (silo.config.xcr0_mask & fpu_xcr0).max(0x3);
1536        task.xcr0_mask
1537            .store(effective_xcr0, core::sync::atomic::Ordering::Relaxed);
1538    }
1539    mgr.map_task(task_id, silo_id);
1540    mgr.push_event(SiloEvent {
1541        silo_id: silo_id.into(),
1542        kind: SiloEventKind::Started,
1543        data0: 0,
1544        data1: 0,
1545        tick: crate::process::scheduler::ticks(),
1546    });
1547    drop(mgr);
1548    crate::process::add_task(task);
1549    Ok(silo_id)
1550}
1551
1552/// Performs the resolve selector to silo id operation.
1553fn resolve_selector_to_silo_id(selector: &str, mgr: &SiloManager) -> Result<u32, SyscallError> {
1554    if let Ok(id) = selector.parse::<u32>() {
1555        if mgr.silos.contains_key(&id) {
1556            return Ok(id);
1557        }
1558        return Err(SyscallError::NotFound);
1559    }
1560    let mut found: Option<u32> = None;
1561    for s in mgr.silos.values() {
1562        if s.strate_label.as_deref() == Some(selector) {
1563            if found.is_some() {
1564                return Err(SyscallError::InvalidArgument);
1565            }
1566            found = Some(s.id.sid);
1567        }
1568    }
1569    found.ok_or(SyscallError::NotFound)
1570}
1571
1572/// Performs the kernel stop silo operation.
1573pub fn kernel_stop_silo(selector: &str, force_kill: bool) -> Result<u32, SyscallError> {
1574    let (silo_id, tasks) = {
1575        let mut mgr = SILO_MANAGER.lock();
1576        let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
1577        let mut tasks = HVec::<TaskId, 64>::new();
1578        {
1579            let silo = mgr.get_mut(silo_id)?;
1580            match silo.state {
1581                SiloState::Running | SiloState::Paused => {
1582                    tasks = silo.tasks.clone();
1583                    silo.tasks.clear();
1584                    silo.state = if force_kill {
1585                        SiloState::Stopped
1586                    } else {
1587                        SiloState::Stopping
1588                    };
1589                }
1590                SiloState::Stopping => {
1591                    if force_kill {
1592                        silo.state = SiloState::Stopped;
1593                    }
1594                }
1595                SiloState::Stopped | SiloState::Created | SiloState::Ready => {}
1596                _ => return Err(SyscallError::InvalidArgument),
1597            }
1598        }
1599        for tid in &tasks {
1600            mgr.unmap_task(*tid);
1601        }
1602        mgr.push_event(SiloEvent {
1603            silo_id: silo_id as u64,
1604            kind: if force_kill {
1605                SiloEventKind::Killed
1606            } else {
1607                SiloEventKind::Stopped
1608            },
1609            data0: 0,
1610            data1: 0,
1611            tick: crate::process::scheduler::ticks(),
1612        });
1613        (silo_id, tasks)
1614    };
1615    for tid in tasks {
1616        crate::process::kill_task(tid);
1617    }
1618    Ok(silo_id)
1619}
1620
1621/// Performs the kernel start silo operation.
1622pub fn kernel_start_silo(selector: &str) -> Result<u32, SyscallError> {
1623    let silo_id = {
1624        let mgr = SILO_MANAGER.lock();
1625        resolve_selector_to_silo_id(selector, &mgr)?
1626    };
1627    let _ = start_silo_by_id(silo_id)?;
1628    Ok(silo_id)
1629}
1630
1631/// Performs the kernel destroy silo operation.
1632pub fn kernel_destroy_silo(selector: &str) -> Result<u32, SyscallError> {
1633    let (silo_id, module_id) = {
1634        let mut mgr = SILO_MANAGER.lock();
1635        let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
1636        let module_id = {
1637            let silo = mgr.get(silo_id)?;
1638            if !silo.tasks.is_empty() {
1639                return Err(SyscallError::InvalidArgument);
1640            }
1641            match silo.state {
1642                SiloState::Stopped | SiloState::Created | SiloState::Ready | SiloState::Crashed => {
1643                }
1644                _ => return Err(SyscallError::InvalidArgument),
1645            }
1646            silo.module_id
1647        };
1648        let _ = mgr.silos.remove(&silo_id);
1649        (silo_id, module_id)
1650    };
1651    if let Some(mid) = module_id {
1652        let mut reg = MODULE_REGISTRY.lock();
1653        let _ = reg.remove(mid);
1654    }
1655    Ok(silo_id)
1656}
1657
1658/// Performs the kernel rename silo label operation.
1659pub fn kernel_rename_silo_label(selector: &str, new_label: &str) -> Result<u32, SyscallError> {
1660    if !is_valid_label(new_label) {
1661        return Err(SyscallError::InvalidArgument);
1662    }
1663    let mut mgr = SILO_MANAGER.lock();
1664    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
1665    if mgr
1666        .silos
1667        .values()
1668        .any(|s| s.id.sid != silo_id && s.strate_label.as_deref() == Some(new_label))
1669    {
1670        return Err(SyscallError::AlreadyExists);
1671    }
1672    let silo = mgr.get_mut(silo_id)?;
1673    match silo.state {
1674        SiloState::Stopped | SiloState::Created | SiloState::Ready | SiloState::Crashed => {
1675            silo.strate_label = Some(String::from(new_label));
1676            Ok(silo_id)
1677        }
1678        _ => Err(SyscallError::InvalidArgument),
1679    }
1680}
1681
1682/// Performs the register boot strate task operation.
1683pub fn register_boot_strate_task(task_id: TaskId, label: &str) -> Result<u32, SyscallError> {
1684    crate::serial_println!(
1685        "[trace][silo] register_boot_strate_task enter tid={} label={}",
1686        task_id.as_u64(),
1687        label
1688    );
1689    BOOT_REG_IN_PROGRESS.store(true, Ordering::Relaxed);
1690    let result = (|| -> Result<u32, SyscallError> {
1691        let sanitized = sanitize_label(label);
1692        let mgr = SILO_MANAGER.lock();
1693        crate::serial_println!(
1694            "[trace][silo] register_boot_strate_task lock acquired tid={}",
1695            task_id.as_u64()
1696        );
1697        crate::serial_println!(
1698            "[trace][silo] register_boot_strate_task before sid scan tid={}",
1699            task_id.as_u64()
1700        );
1701        let mut sid = 1u32;
1702        while mgr.silos.contains_key(&sid) {
1703            sid = sid.checked_add(1).ok_or(SyscallError::OutOfMemory)?;
1704        }
1705        crate::serial_println!(
1706            "[trace][silo] register_boot_strate_task sid selected tid={} sid={}",
1707            task_id.as_u64(),
1708            sid
1709        );
1710        crate::serial_println!(
1711            "[trace][silo] register_boot_strate_task before label uniqueness tid={} label={}",
1712            task_id.as_u64(),
1713            sanitized.as_str()
1714        );
1715        if mgr
1716            .silos
1717            .values()
1718            .any(|s| s.strate_label.as_deref() == Some(sanitized.as_str()))
1719        {
1720            return Err(SyscallError::AlreadyExists);
1721        }
1722        drop(mgr);
1723
1724        let id = SiloId::new(sid);
1725        let silo = Silo {
1726            id,
1727            name: alloc::format!("silo-{}", id.sid),
1728            strate_label: Some(sanitized),
1729            state: SiloState::Running,
1730            config: SiloConfig {
1731                sid: id.sid,
1732                mode: 0o777,
1733                family: StrateFamily::SYS as u8,
1734                ..SiloConfig::default()
1735            },
1736            mode: OctalMode::from_octal(0o777),
1737            family: StrateFamily::SYS,
1738            mem_usage_bytes: 0,
1739            flags: 0,
1740            module_id: None,
1741            tasks: {
1742                let mut v = HVec::new();
1743                let _ = v.push(task_id);
1744                v
1745            },
1746            granted_caps: HVec::new(),
1747            granted_resources: HVec::new(),
1748            unveil_rules: HVec::new(),
1749            sandboxed: false,
1750            event_seq: 0,
1751            output_buf: None,
1752        };
1753
1754        let mut mgr = SILO_MANAGER.lock();
1755        if mgr.silos.contains_key(&id.sid) {
1756            return Err(SyscallError::Again);
1757        }
1758        if mgr
1759            .silos
1760            .values()
1761            .any(|s| s.strate_label.as_deref() == silo.strate_label.as_deref())
1762        {
1763            return Err(SyscallError::AlreadyExists);
1764        }
1765        crate::serial_println!(
1766            "[trace][silo] register_boot_strate_task before silo insert tid={} sid={}",
1767            task_id.as_u64(),
1768            id.sid
1769        );
1770        mgr.silos.insert(id.sid, Box::new(silo));
1771        drop(mgr);
1772        Ok(id.sid)
1773    })();
1774    BOOT_REG_IN_PROGRESS.store(false, Ordering::Relaxed);
1775    result
1776}
1777
1778/// Returns true while boot-time silo registration critical path is executing.
1779pub fn debug_boot_reg_active() -> bool {
1780    BOOT_REG_IN_PROGRESS.load(Ordering::Relaxed)
1781}
1782
1783/// Performs the resolve module handle operation.
1784fn resolve_module_handle(handle: u64, required: CapPermissions) -> Result<u64, SyscallError> {
1785    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1786    let caps = unsafe { &*task.process.capabilities.get() };
1787    let cap_id = CapId::from_raw(handle);
1788    let cap = caps.get(cap_id).ok_or(SyscallError::BadHandle)?;
1789
1790    if cap.resource_type != ResourceType::Module {
1791        return Err(SyscallError::BadHandle);
1792    }
1793
1794    if (!required.read || cap.permissions.read)
1795        && (!required.write || cap.permissions.write)
1796        && (!required.execute || cap.permissions.execute)
1797        && (!required.grant || cap.permissions.grant)
1798        && (!required.revoke || cap.permissions.revoke)
1799    {
1800        Ok(cap.resource as u64)
1801    } else {
1802        Err(SyscallError::PermissionDenied)
1803    }
1804}
1805
1806/// Grant the Silo Admin capability to a task (bootstrapping).
1807///
1808/// This should be called only for the initial admin task (e.g. "init").
1809pub fn create_silo_admin_capability() -> Capability {
1810    get_capability_manager().create_capability(
1811        ResourceType::Silo,
1812        SILO_ADMIN_RESOURCE,
1813        CapPermissions::all(),
1814    )
1815}
1816
1817pub fn grant_silo_admin_to_task(task: &alloc::sync::Arc<Task>) -> CapId {
1818    let cap = create_silo_admin_capability();
1819    // SAFETY: Bootstrapping. Caller must ensure exclusive access.
1820    unsafe { (&mut *task.process.capabilities.get()).insert(cap) }
1821}
1822
1823// ============================================================================
1824// Module syscalls (temporary blob loader)
1825// ============================================================================
1826
1827/// Performs the sys module load operation.
1828pub fn sys_module_load(fd_or_ptr: u64, len: u64) -> Result<u64, SyscallError> {
1829    // Module loading is currently restricted to admin.
1830    require_silo_admin()?;
1831
1832    // Transitional path: if len != 0, treat arg1 as a userspace blob pointer.
1833    if len != 0 {
1834        let len = len as usize;
1835        if len == 0 || len > MAX_MODULE_BLOB_LEN {
1836            return Err(SyscallError::InvalidArgument);
1837        }
1838
1839        if len <= 4096 {
1840            let user = UserSliceRead::new(fd_or_ptr, len)?;
1841            if matches!(user.read_u8(0), Ok(b'/')) {
1842                let path_buf = user.read_to_vec();
1843                if let Ok(path) = core::str::from_utf8(&path_buf) {
1844                    if let Some(data) = crate::vfs::get_initfs_file_bytes(path) {
1845                        let mut registry = MODULE_REGISTRY.lock();
1846                        let id = registry.register_static(data)?;
1847                        drop(registry);
1848
1849                        let cap = get_capability_manager().create_capability(
1850                            ResourceType::Module,
1851                            id as usize,
1852                            CapPermissions::all(),
1853                        );
1854
1855                        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1856                        let cap_id = unsafe { (&mut *task.process.capabilities.get()).insert(cap) };
1857                        return Ok(cap_id.as_u64());
1858                    }
1859                }
1860            }
1861        }
1862
1863        let user = UserSliceRead::new(fd_or_ptr, len)?;
1864        let data = user.read_to_vec();
1865        if data.len() >= 4 {
1866            log::debug!(
1867                "module_load: len={} magic={:02x}{:02x}{:02x}{:02x}",
1868                data.len(),
1869                data[0],
1870                data[1],
1871                data[2],
1872                data[3]
1873            );
1874        } else {
1875            log::debug!("module_load: len={} (too small)", data.len());
1876        }
1877
1878        let mut registry = MODULE_REGISTRY.lock();
1879        let id = registry.register(data)?;
1880        drop(registry);
1881
1882        let cap = get_capability_manager().create_capability(
1883            ResourceType::Module,
1884            id as usize,
1885            CapPermissions::all(),
1886        );
1887
1888        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1889        let cap_id = unsafe { (&mut *task.process.capabilities.get()).insert(cap) };
1890
1891        return Ok(cap_id.as_u64());
1892    }
1893
1894    // TODO: Load from a file handle (fd) via VFS once the path exists.
1895    // For now, interpret `fd_or_ptr` as either:
1896    // - a File handle (read all), or
1897    // - an IPC port handle that streams the module bytes.
1898    //
1899    // Stream protocol:
1900    // - msg_type = IPC_STREAM_DATA, flags = payload length (0..48)
1901    // - msg_type = IPC_STREAM_EOF (or DATA with flags=0) ends the stream
1902    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1903    let caps = unsafe { &*task.process.capabilities.get() };
1904    let required = CapPermissions {
1905        read: true,
1906        write: false,
1907        execute: false,
1908        grant: false,
1909        revoke: false,
1910    };
1911    let cap = caps
1912        .get_with_permissions(CapId::from_raw(fd_or_ptr), required)
1913        .ok_or(SyscallError::PermissionDenied)?;
1914    let data = match cap.resource_type {
1915        ResourceType::File => {
1916            let fd = u32::try_from(cap.resource).map_err(|_| SyscallError::BadHandle)?;
1917            crate::vfs::read_all(fd)?
1918        }
1919        ResourceType::IpcPort => {
1920            let port_id = PortId::from_u64(cap.resource as u64);
1921            let port = port::get_port(port_id).ok_or(SyscallError::BadHandle)?;
1922            read_module_stream_from_port(&port)?
1923        }
1924        _ => return Err(SyscallError::BadHandle),
1925    };
1926    if data.len() > MAX_MODULE_BLOB_LEN {
1927        return Err(SyscallError::InvalidArgument);
1928    }
1929
1930    let mut registry = MODULE_REGISTRY.lock();
1931    let id = registry.register(data)?;
1932    drop(registry);
1933
1934    let cap = get_capability_manager().create_capability(
1935        ResourceType::Module,
1936        id as usize,
1937        CapPermissions::all(),
1938    );
1939
1940    let cap_id = unsafe { (&mut *task.process.capabilities.get()).insert(cap) };
1941
1942    Ok(cap_id.as_u64())
1943}
1944
1945/// Performs the sys module unload operation.
1946pub fn sys_module_unload(handle: u64) -> Result<u64, SyscallError> {
1947    require_silo_admin()?;
1948    let required = CapPermissions {
1949        read: false,
1950        write: false,
1951        execute: false,
1952        grant: false,
1953        revoke: true,
1954    };
1955    let module_id = resolve_module_handle(handle, required)?;
1956    let mut registry = MODULE_REGISTRY.lock();
1957    registry.remove(module_id);
1958    Ok(0)
1959}
1960
1961/// Performs the sys module get symbol operation.
1962pub fn sys_module_get_symbol(handle: u64, _ordinal: u64) -> Result<u64, SyscallError> {
1963    let required = CapPermissions {
1964        read: true,
1965        write: false,
1966        execute: false,
1967        grant: false,
1968        revoke: false,
1969    };
1970    let module_id = resolve_module_handle(handle, required)?;
1971    let registry = MODULE_REGISTRY.lock();
1972    let module = registry.get(module_id).ok_or(SyscallError::BadHandle)?;
1973
1974    // The export table format is a simple array of u64 RVAs indexed by ordinal.
1975    let rva = resolve_export_offset(module, _ordinal)?;
1976    let header = module.header.ok_or(SyscallError::InvalidArgument)?;
1977    Ok(header.code_offset.saturating_add(rva))
1978}
1979
1980/// Performs the sys module query operation.
1981pub fn sys_module_query(handle: u64, out_ptr: u64) -> Result<u64, SyscallError> {
1982    let required = CapPermissions {
1983        read: true,
1984        write: false,
1985        execute: false,
1986        grant: false,
1987        revoke: false,
1988    };
1989    let module_id = resolve_module_handle(handle, required)?;
1990    if out_ptr == 0 {
1991        return Err(SyscallError::Fault);
1992    }
1993
1994    let registry = MODULE_REGISTRY.lock();
1995    let module = registry.get(module_id).ok_or(SyscallError::BadHandle)?;
1996
1997    let (format, flags, version, cpu_arch, code_size, data_size, bss_size, entry_point) =
1998        if let Some(header) = module.header {
1999            (
2000                1u32,
2001                header.flags,
2002                header.version,
2003                header.cpu_arch,
2004                header.code_size,
2005                header.data_size,
2006                header.bss_size,
2007                header.entry_point,
2008            )
2009        } else {
2010            (0u32, 0u32, 0u16, 0u8, 0u64, 0u64, 0u64, 0u64)
2011        };
2012
2013    let info = ModuleInfo {
2014        id: module.id,
2015        format,
2016        flags,
2017        version,
2018        cpu_arch,
2019        reserved: 0,
2020        code_size,
2021        data_size,
2022        bss_size,
2023        entry_point,
2024        total_size: module.data.len() as u64,
2025    };
2026
2027    const INFO_SIZE: usize = core::mem::size_of::<ModuleInfo>();
2028    let user = UserSliceWrite::new(out_ptr, INFO_SIZE)?;
2029    let src =
2030        unsafe { core::slice::from_raw_parts(&info as *const ModuleInfo as *const u8, INFO_SIZE) };
2031    user.copy_from(src);
2032    Ok(0)
2033}
2034
2035// ============================================================================
2036// Syscall handlers (kernel entry points)
2037// ============================================================================
2038
2039/// Performs the sys silo create operation.
2040pub fn sys_silo_create(config_ptr: u64) -> Result<u64, SyscallError> {
2041    require_silo_admin()?;
2042    let config = read_user_config(config_ptr)?;
2043    config.validate()?;
2044
2045    let mut mgr = SILO_MANAGER.lock();
2046    let id = mgr.create_silo(&config)?;
2047    drop(mgr);
2048
2049    let cap = get_capability_manager().create_capability(
2050        ResourceType::Silo,
2051        id.sid as usize,
2052        CapPermissions::all(),
2053    );
2054
2055    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2056    let cap_id = unsafe { (&mut *task.process.capabilities.get()).insert(cap) };
2057
2058    Ok(cap_id.as_u64())
2059}
2060
2061/// Performs the sys silo config operation.
2062pub fn sys_silo_config(handle: u64, res_ptr: u64) -> Result<u64, SyscallError> {
2063    require_silo_admin()?;
2064    let config = read_user_config(res_ptr)?;
2065    config.validate()?;
2066    let family = decode_family(config.family)?;
2067
2068    let mut granted_caps = HVec::<u64, 64>::new();
2069    let mut granted_resources = HVec::<GrantedResource, 32>::new();
2070    if config.caps_len > 0 {
2071        let caps_list = read_caps_list(config.caps_ptr, config.caps_len)?;
2072        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2073        let caps = unsafe { &*task.process.capabilities.get() };
2074
2075        for cap_handle in caps_list {
2076            let cap = caps
2077                .get(CapId::from_raw(cap_handle))
2078                .ok_or(SyscallError::BadHandle)?;
2079            if !cap.permissions.grant {
2080                return Err(SyscallError::PermissionDenied);
2081            }
2082            if !is_delegated_resource(cap.resource_type) {
2083                return Err(SyscallError::InvalidArgument);
2084            }
2085            if !granted_caps.contains(&cap_handle) {
2086                if let Err(cap) = granted_caps.push(cap_handle) {
2087                    log::warn!(
2088                        "[silo] granted_caps full (capacity=64), cap {} dropped",
2089                        cap
2090                    );
2091                }
2092            }
2093            add_or_merge_granted_resource(
2094                &mut granted_resources,
2095                GrantedResource {
2096                    resource_type: cap.resource_type,
2097                    resource: cap.resource,
2098                    permissions: cap.permissions,
2099                },
2100            );
2101        }
2102    }
2103
2104    let sid = resolve_silo_handle(handle, CapPermissions::read_write())?;
2105    let mut mgr = SILO_MANAGER.lock();
2106    let silo = mgr.get_mut(sid as u32)?;
2107
2108    let requested_mode = OctalMode::from_octal(config.mode);
2109    kernel_check_spawn_invariants(&silo.id, &requested_mode)?;
2110    if silo.sandboxed && !requested_mode.is_subset_of(&silo.mode) {
2111        return Err(SyscallError::PermissionDenied);
2112    }
2113    if silo.sandboxed && !requested_mode.registry.is_empty() {
2114        return Err(SyscallError::PermissionDenied);
2115    }
2116
2117    silo.config = config;
2118    silo.mode = requested_mode;
2119    silo.family = family;
2120    silo.flags = config.flags as u32;
2121    silo.granted_caps = granted_caps;
2122    silo.granted_resources = granted_resources;
2123    Ok(0)
2124}
2125
2126/// Performs the sys silo attach module operation.
2127pub fn sys_silo_attach_module(handle: u64, module_handle: u64) -> Result<u64, SyscallError> {
2128    require_silo_admin()?;
2129    let silo_id = resolve_silo_handle(handle, CapPermissions::read_write())?;
2130
2131    let required = CapPermissions {
2132        read: true,
2133        write: false,
2134        execute: false,
2135        grant: false,
2136        revoke: false,
2137    };
2138    let module_id = resolve_module_handle(module_handle, required)?;
2139
2140    let mut mgr = SILO_MANAGER.lock();
2141    let silo = mgr.get_mut(silo_id)?;
2142
2143    match silo.state {
2144        SiloState::Created | SiloState::Stopped | SiloState::Ready => {
2145            silo.module_id = Some(module_id);
2146            silo.state = SiloState::Ready;
2147            Ok(0)
2148        }
2149        SiloState::Running | SiloState::Paused => {
2150            silo.module_id = Some(module_id);
2151            Ok(0)
2152        }
2153        _ => Err(SyscallError::InvalidArgument),
2154    }
2155}
2156
2157/// Starts silo by id.
2158fn start_silo_by_id(silo_id: u32) -> Result<u64, SyscallError> {
2159    let (
2160        module_id,
2161        granted_caps,
2162        silo_flags,
2163        previous_state,
2164        can_start,
2165        within_task_limit,
2166        silo_name,
2167        silo_label,
2168    ) = {
2169        let mut mgr = SILO_MANAGER.lock();
2170        let silo = mgr.get_mut(silo_id)?;
2171        let previous_state = silo.state;
2172        let can_start = matches!(
2173            previous_state,
2174            SiloState::Ready | SiloState::Stopped | SiloState::Running
2175        );
2176        let within_task_limit = match silo.config.max_tasks {
2177            0 => true, // 0 = unlimited
2178            max => silo.tasks.len() < max as usize,
2179        };
2180        let module_id = silo.module_id;
2181        let granted_caps = silo.granted_caps.clone();
2182        let silo_flags = silo.config.flags;
2183        let silo_name = silo.name.clone();
2184        let silo_label = silo.strate_label.clone();
2185        if can_start && within_task_limit {
2186            silo.state = SiloState::Loading;
2187        }
2188        (
2189            module_id,
2190            granted_caps,
2191            silo_flags,
2192            previous_state,
2193            can_start,
2194            within_task_limit,
2195            silo_name,
2196            silo_label,
2197        )
2198    };
2199
2200    if !can_start {
2201        return Err(SyscallError::InvalidArgument);
2202    }
2203    if !within_task_limit {
2204        return Err(SyscallError::QueueFull);
2205    }
2206
2207    let rollback_loading = |state: SiloState| {
2208        let mut mgr = SILO_MANAGER.lock();
2209        if let Ok(silo) = mgr.get_mut(silo_id) {
2210            if matches!(silo.state, SiloState::Loading) {
2211                silo.state = state;
2212            }
2213        }
2214    };
2215
2216    let module_id = match module_id {
2217        Some(id) => id,
2218        None => {
2219            rollback_loading(previous_state);
2220            return Err(SyscallError::InvalidArgument);
2221        }
2222    };
2223
2224    let mut seed_caps = {
2225        let task = match current_task_clone() {
2226            Some(t) => t,
2227            None => {
2228                rollback_loading(previous_state);
2229                return Err(SyscallError::PermissionDenied);
2230            }
2231        };
2232        let caps = unsafe { &mut *task.process.capabilities.get() };
2233        let mut out = Vec::with_capacity(granted_caps.len());
2234        for handle in granted_caps {
2235            // Enforce: caller must currently hold the capability.
2236            if !silo_has_capability(&task, handle) {
2237                rollback_loading(previous_state);
2238                return Err(SyscallError::PermissionDenied);
2239            }
2240            if let Some(dup) = caps.duplicate(CapId::from_raw(handle)) {
2241                out.push(dup);
2242            } else {
2243                rollback_loading(previous_state);
2244                return Err(SyscallError::PermissionDenied);
2245            }
2246        }
2247        out
2248    };
2249    if silo_flags & SILO_FLAG_ADMIN != 0 {
2250        seed_caps.push(create_silo_admin_capability());
2251    }
2252
2253    let display = silo_label.unwrap_or(silo_name);
2254    let task_name_owned = if silo_flags & SILO_FLAG_ADMIN != 0 {
2255        alloc::format!("silo-{}/strate-admin-{}", silo_id, display)
2256    } else {
2257        alloc::format!("silo-{}/strate-{}", silo_id, display)
2258    };
2259    // Intentional leak: task names are expected to live for the task lifetime.
2260    // This avoids generic "silo" labels in process viewers.
2261    let task_name: &'static str = Box::leak(task_name_owned.into_boxed_str());
2262
2263    let module_data = {
2264        let registry = MODULE_REGISTRY.lock();
2265        match registry.get(module_id) {
2266            Some(module) => module.data.clone(),
2267            None => {
2268                rollback_loading(previous_state);
2269                return Err(SyscallError::BadHandle);
2270            }
2271        }
2272    };
2273
2274    let load_result =
2275        crate::process::elf::load_elf_task_with_caps(module_data.as_slice(), task_name, &seed_caps)
2276            .map_err(|err| {
2277                log::warn!(
2278                    "silo_start: sid={} module={} task='{}' load failed: {}",
2279                    silo_id,
2280                    module_id,
2281                    task_name,
2282                    err
2283                );
2284                map_elf_start_error(err)
2285            });
2286
2287    let task = match load_result {
2288        Ok(task) => task,
2289        Err(e) => {
2290            rollback_loading(previous_state);
2291            return Err(e);
2292        }
2293    };
2294    let task_id = task.id;
2295    let task_pid = task.pid;
2296
2297    // Give the silo an EOF stdin so that any read(0, …) returns 0 immediately
2298    // instead of EBADF (which can cause busy-loops) or blocking on the
2299    // keyboard (which would steal input from the foreground shell).
2300    let bg_stdin = crate::vfs::create_background_stdin();
2301    let fd_table = unsafe { &mut *task.process.fd_table.get() };
2302    fd_table.insert_at(crate::vfs::STDIN, bg_stdin);
2303
2304    let mut mgr = SILO_MANAGER.lock();
2305    {
2306        let silo = match mgr.get_mut(silo_id) {
2307            Ok(silo) => silo,
2308            Err(e) => {
2309                return Err(e);
2310            }
2311        };
2312        if let Err(task) = silo.tasks.push(task_id) {
2313            log::error!(
2314                "[silo] tasks full (capacity=64), task {} not registered",
2315                task.0
2316            );
2317        }
2318        silo.state = SiloState::Running;
2319        let fpu_xcr0 = unsafe { (*task.fpu_state.get()).xcr0_mask };
2320        let effective_xcr0 = (silo.config.xcr0_mask & fpu_xcr0).max(0x3);
2321        task.xcr0_mask
2322            .store(effective_xcr0, core::sync::atomic::Ordering::Relaxed);
2323    }
2324    mgr.map_task(task_id, silo_id);
2325    mgr.push_event(SiloEvent {
2326        silo_id: silo_id.into(),
2327        kind: SiloEventKind::Started,
2328        data0: 0,
2329        data1: 0,
2330        tick: crate::process::scheduler::ticks(),
2331    });
2332    drop(mgr);
2333    crate::process::add_task(task);
2334    Ok(task_pid as u64)
2335}
2336
2337/// Performs the sys silo start operation.
2338pub fn sys_silo_start(handle: u64) -> Result<u64, SyscallError> {
2339    require_silo_admin()?;
2340    let required = CapPermissions {
2341        read: false,
2342        write: false,
2343        execute: true,
2344        grant: false,
2345        revoke: false,
2346    };
2347    let silo_id = resolve_silo_handle(handle, required)?;
2348    start_silo_by_id(silo_id)
2349}
2350
2351/// Best-effort cleanup hook called by the scheduler when a task terminates.
2352///
2353/// Ensures `task_to_silo` mappings are removed even for normal exits and
2354/// transitions a running/paused silo to `Stopped` when its last task is gone.
2355pub fn on_task_terminated(task_id: TaskId) {
2356    let mut mgr = SILO_MANAGER.lock();
2357    let silo_id = match mgr.silo_for_task(task_id) {
2358        Some(id) => id,
2359        None => return,
2360    };
2361    mgr.unmap_task(task_id);
2362
2363    let mut emit_stopped = false;
2364    if let Ok(silo) = mgr.get_mut(silo_id) {
2365        if let Some(pos) = silo.tasks.iter().position(|tid| *tid == task_id) {
2366            silo.tasks.swap_remove(pos);
2367        }
2368        if silo.tasks.is_empty() {
2369            match silo.state {
2370                SiloState::Running | SiloState::Paused | SiloState::Stopping => {
2371                    silo.state = SiloState::Stopped;
2372                    silo.event_seq = silo.event_seq.wrapping_add(1);
2373                    emit_stopped = true;
2374                }
2375                _ => {}
2376            }
2377        }
2378    }
2379
2380    if emit_stopped {
2381        mgr.push_event(SiloEvent {
2382            silo_id: silo_id.into(),
2383            kind: SiloEventKind::Stopped,
2384            data0: 0,
2385            data1: 0,
2386            tick: crate::process::scheduler::ticks(),
2387        });
2388    }
2389}
2390
2391/// Stops or kill silo by id.
2392fn stop_or_kill_silo_by_id(
2393    silo_id: u32,
2394    force_kill: bool,
2395    require_running: bool,
2396) -> Result<HVec<TaskId, 64>, SyscallError> {
2397    let mut mgr = SILO_MANAGER.lock();
2398    let tasks = {
2399        let silo = mgr.get_mut(silo_id)?;
2400        if force_kill {
2401            silo.state = SiloState::Stopped;
2402            let tasks = silo.tasks.clone();
2403            silo.tasks.clear();
2404            tasks
2405        } else {
2406            match silo.state {
2407                SiloState::Running | SiloState::Paused => {
2408                    silo.state = SiloState::Stopping;
2409                    let tasks = silo.tasks.clone();
2410                    silo.tasks.clear();
2411                    tasks
2412                }
2413                _ if require_running => return Err(SyscallError::InvalidArgument),
2414                _ => HVec::new(),
2415            }
2416        }
2417    };
2418
2419    for tid in &tasks {
2420        mgr.unmap_task(*tid);
2421    }
2422    if !force_kill {
2423        if let Ok(silo) = mgr.get_mut(silo_id) {
2424            silo.state = SiloState::Stopped;
2425        }
2426    }
2427    mgr.push_event(SiloEvent {
2428        silo_id: silo_id.into(),
2429        kind: if force_kill {
2430            SiloEventKind::Killed
2431        } else {
2432            SiloEventKind::Stopped
2433        },
2434        data0: 0,
2435        data1: 0,
2436        tick: crate::process::scheduler::ticks(),
2437    });
2438
2439    Ok(tasks)
2440}
2441
2442/// Performs the sys silo stop operation.
2443pub fn sys_silo_stop(handle: u64) -> Result<u64, SyscallError> {
2444    require_silo_admin()?;
2445    let required = CapPermissions {
2446        read: false,
2447        write: false,
2448        execute: true,
2449        grant: false,
2450        revoke: false,
2451    };
2452    let silo_id = resolve_silo_handle(handle, required)?;
2453    let tasks = stop_or_kill_silo_by_id(silo_id, false, true)?;
2454
2455    for tid in tasks {
2456        crate::process::kill_task(tid);
2457    }
2458    Ok(0)
2459}
2460
2461/// Performs the sys silo kill operation.
2462pub fn sys_silo_kill(handle: u64) -> Result<u64, SyscallError> {
2463    require_silo_admin()?;
2464    let required = CapPermissions {
2465        read: false,
2466        write: false,
2467        execute: true,
2468        grant: false,
2469        revoke: false,
2470    };
2471    let silo_id = resolve_silo_handle(handle, required)?;
2472    let tasks = stop_or_kill_silo_by_id(silo_id, true, false)?;
2473
2474    for tid in tasks {
2475        crate::process::kill_task(tid);
2476    }
2477    Ok(0)
2478}
2479
2480/// Performs the silo has capability operation.
2481fn silo_has_capability(task: &Task, cap_id: u64) -> bool {
2482    let caps = unsafe { &*task.process.capabilities.get() };
2483    caps.get(CapId::from_raw(cap_id)).is_some()
2484}
2485
2486/// Returns whether delegated resource.
2487fn is_delegated_resource(rt: ResourceType) -> bool {
2488    matches!(
2489        rt,
2490        ResourceType::Nic
2491            | ResourceType::FileSystem
2492            | ResourceType::Console
2493            | ResourceType::Keyboard
2494            | ResourceType::Volume
2495            | ResourceType::Namespace
2496            | ResourceType::Device
2497            | ResourceType::File
2498            | ResourceType::IoPortRange
2499            | ResourceType::InterruptLine
2500    )
2501}
2502
2503/// Returns whether admin task.
2504fn is_admin_task(task: &Task) -> bool {
2505    let caps = unsafe { &*task.process.capabilities.get() };
2506    let required = CapPermissions {
2507        read: false,
2508        write: false,
2509        execute: false,
2510        grant: true,
2511        revoke: false,
2512    };
2513    caps.has_resource_with_permissions(ResourceType::Silo, SILO_ADMIN_RESOURCE, required)
2514}
2515
2516/// Maps elf start error.
2517fn map_elf_start_error(err: &'static str) -> SyscallError {
2518    if err.contains("allocate")
2519        || err.contains("Out of memory")
2520        || err.contains("No virtual range")
2521        || err.contains("Failed to map page")
2522    {
2523        return SyscallError::OutOfMemory;
2524    }
2525    if err.contains("ELF")
2526        || err.contains("PT_")
2527        || err.contains("entry")
2528        || err.contains("relocation")
2529        || err.contains("Program header")
2530        || err.contains("x86_64")
2531        || err.contains("Unsupported")
2532    {
2533        return SyscallError::ExecFormatError;
2534    }
2535    SyscallError::InvalidArgument
2536}
2537
2538#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2539struct GrantedResource {
2540    resource_type: ResourceType,
2541    resource: usize,
2542    permissions: CapPermissions,
2543}
2544
2545/// Performs the merge permissions operation.
2546fn merge_permissions(a: CapPermissions, b: CapPermissions) -> CapPermissions {
2547    CapPermissions {
2548        read: a.read || b.read,
2549        write: a.write || b.write,
2550        execute: a.execute || b.execute,
2551        grant: a.grant || b.grant,
2552        revoke: a.revoke || b.revoke,
2553    }
2554}
2555
2556/// Performs the permissions subset operation.
2557fn permissions_subset(requested: CapPermissions, allowed: CapPermissions) -> bool {
2558    (!requested.read || allowed.read)
2559        && (!requested.write || allowed.write)
2560        && (!requested.execute || allowed.execute)
2561        && (!requested.grant || allowed.grant)
2562        && (!requested.revoke || allowed.revoke)
2563}
2564
2565/// Performs the add or merge granted resource operation.
2566fn add_or_merge_granted_resource(list: &mut HVec<GrantedResource, 32>, grant: GrantedResource) {
2567    for existing in list.iter_mut() {
2568        if existing.resource_type == grant.resource_type && existing.resource == grant.resource {
2569            existing.permissions = merge_permissions(existing.permissions, grant.permissions);
2570            return;
2571        }
2572    }
2573    if list.push(grant).is_err() {
2574        log::warn!("[silo] granted_resources full (capacity=32), resource dropped");
2575    }
2576}
2577
2578/// Performs the register current task granted resource operation.
2579pub fn register_current_task_granted_resource(
2580    resource_type: ResourceType,
2581    resource: usize,
2582    permissions: CapPermissions,
2583) -> Result<(), SyscallError> {
2584    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2585    let mut mgr = SILO_MANAGER.lock();
2586    let silo_id = mgr
2587        .silo_for_task(task.id)
2588        .ok_or(SyscallError::PermissionDenied)?;
2589    let silo = mgr.get_mut(silo_id)?;
2590    add_or_merge_granted_resource(
2591        &mut silo.granted_resources,
2592        GrantedResource {
2593            resource_type,
2594            resource,
2595            permissions,
2596        },
2597    );
2598    Ok(())
2599}
2600
2601/// Enforce that the current task may use a delegated capability.
2602pub fn enforce_cap_for_current_task(handle: u64) -> Result<(), SyscallError> {
2603    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2604
2605    // Admin tasks bypass delegated-cap enforcement.
2606    if is_admin_task(&task) {
2607        return Ok(());
2608    }
2609
2610    let caps = unsafe { &*task.process.capabilities.get() };
2611    let cap = caps
2612        .get(CapId::from_raw(handle))
2613        .ok_or(SyscallError::BadHandle)?;
2614
2615    if !is_delegated_resource(cap.resource_type) {
2616        return Ok(());
2617    }
2618
2619    let mgr = SILO_MANAGER.lock();
2620    if let Some(silo_id) = mgr.silo_for_task(task.id) {
2621        if let Ok(silo) = mgr.get(silo_id) {
2622            for grant in &silo.granted_resources {
2623                if grant.resource_type == cap.resource_type && grant.resource == cap.resource {
2624                    if permissions_subset(cap.permissions, grant.permissions) {
2625                        return Ok(());
2626                    }
2627                    return Err(SyscallError::PermissionDenied);
2628                }
2629            }
2630        }
2631    }
2632
2633    Err(SyscallError::PermissionDenied)
2634}
2635
2636/// Performs the enforce registry bind for current task operation.
2637pub fn enforce_registry_bind_for_current_task() -> Result<(), SyscallError> {
2638    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2639    if is_admin_task(&task) {
2640        return Ok(());
2641    }
2642    let mgr = SILO_MANAGER.lock();
2643    let silo_id = mgr
2644        .silo_for_task(task.id)
2645        .ok_or(SyscallError::PermissionDenied)?;
2646    let silo = mgr.get(silo_id)?;
2647    if silo.sandboxed {
2648        return Err(SyscallError::PermissionDenied);
2649    }
2650    if silo.mode.registry.contains(RegistryMode::BIND) {
2651        Ok(())
2652    } else {
2653        Err(SyscallError::PermissionDenied)
2654    }
2655}
2656
2657/// Enforce console access for the current task.
2658///
2659/// Only admin tasks or tasks holding a Console capability with write permission
2660/// can access the kernel console (SYS_WRITE fd=1/2).
2661pub fn enforce_console_access() -> Result<(), SyscallError> {
2662    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
2663    if is_admin_task(&task) {
2664        return Ok(());
2665    }
2666    let mgr = SILO_MANAGER.lock();
2667    if let Some(silo_id) = mgr.silo_for_task(task.id) {
2668        if let Ok(silo) = mgr.get(silo_id) {
2669            if matches!(silo.family, StrateFamily::SYS | StrateFamily::NET) {
2670                return Ok(());
2671            }
2672        }
2673    }
2674    drop(mgr);
2675    let caps = unsafe { &*task.process.capabilities.get() };
2676    let required = CapPermissions {
2677        read: false,
2678        write: true,
2679        execute: false,
2680        grant: false,
2681        revoke: false,
2682    };
2683    if caps.has_resource_type_with_permissions(ResourceType::Console, required) {
2684        Ok(())
2685    } else {
2686        Err(SyscallError::PermissionDenied)
2687    }
2688}
2689
2690/// Performs the sys silo event next operation.
2691pub fn sys_silo_event_next(_event_ptr: u64) -> Result<u64, SyscallError> {
2692    require_silo_admin()?;
2693    if _event_ptr == 0 {
2694        return Err(SyscallError::Fault);
2695    }
2696
2697    let event = {
2698        let mut mgr = SILO_MANAGER.lock();
2699        mgr.events.pop_front()
2700    };
2701
2702    let event = match event {
2703        Some(e) => e,
2704        None => return Err(SyscallError::Again),
2705    };
2706
2707    const EVT_SIZE: usize = core::mem::size_of::<SiloEvent>();
2708    let user = UserSliceWrite::new(_event_ptr, EVT_SIZE)?;
2709    let src =
2710        unsafe { core::slice::from_raw_parts(&event as *const SiloEvent as *const u8, EVT_SIZE) };
2711    user.copy_from(src);
2712    Ok(0)
2713}
2714
2715/// Performs the sys silo suspend operation.
2716pub fn sys_silo_suspend(handle: u64) -> Result<u64, SyscallError> {
2717    require_silo_admin()?;
2718    let required = CapPermissions {
2719        read: false,
2720        write: false,
2721        execute: true,
2722        grant: false,
2723        revoke: false,
2724    };
2725    let silo_id = resolve_silo_handle(handle, required)?;
2726
2727    // Lock is released before suspend_task (which takes the scheduler lock)
2728    // to avoid lock-ordering deadlock. Tasks added between the two locks
2729    // won't be suspended : acceptable best-effort trade-off.
2730    let tasks = {
2731        let mut mgr = SILO_MANAGER.lock();
2732        let silo = mgr.get_mut(silo_id)?;
2733        match silo.state {
2734            SiloState::Running => {
2735                silo.state = SiloState::Paused;
2736                silo.tasks.clone()
2737            }
2738            _ => return Err(SyscallError::InvalidArgument),
2739        }
2740    };
2741
2742    for tid in &tasks {
2743        crate::process::suspend_task(*tid);
2744    }
2745
2746    let mut mgr = SILO_MANAGER.lock();
2747    mgr.push_event(SiloEvent {
2748        silo_id: silo_id.into(),
2749        kind: SiloEventKind::Paused,
2750        data0: 0,
2751        data1: 0,
2752        tick: crate::process::scheduler::ticks(),
2753    });
2754
2755    Ok(0)
2756}
2757
2758/// Performs the sys silo resume operation.
2759pub fn sys_silo_resume(handle: u64) -> Result<u64, SyscallError> {
2760    require_silo_admin()?;
2761    let required = CapPermissions {
2762        read: false,
2763        write: false,
2764        execute: true,
2765        grant: false,
2766        revoke: false,
2767    };
2768    let silo_id = resolve_silo_handle(handle, required)?;
2769
2770    let tasks = {
2771        let mut mgr = SILO_MANAGER.lock();
2772        let silo = mgr.get_mut(silo_id)?;
2773        match silo.state {
2774            SiloState::Paused => {
2775                silo.state = SiloState::Running;
2776                silo.tasks.clone()
2777            }
2778            _ => return Err(SyscallError::InvalidArgument),
2779        }
2780    };
2781
2782    // Same lock-ordering pattern as sys_silo_suspend (see note there).
2783    for tid in &tasks {
2784        crate::process::resume_task(*tid);
2785    }
2786
2787    let mut mgr = SILO_MANAGER.lock();
2788    mgr.push_event(SiloEvent {
2789        silo_id: silo_id.into(),
2790        kind: SiloEventKind::Resumed,
2791        data0: 0,
2792        data1: 0,
2793        tick: crate::process::scheduler::ticks(),
2794    });
2795
2796    Ok(0)
2797}
2798
2799// ============================================================================
2800// Kernel-side CLI helpers (no capability gate : shell runs in Ring 0)
2801// ============================================================================
2802
2803pub fn kernel_suspend_silo(selector: &str) -> Result<u32, SyscallError> {
2804    let (silo_id, tasks) = {
2805        let mut mgr = SILO_MANAGER.lock();
2806        let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2807        let silo = mgr.get_mut(silo_id)?;
2808        match silo.state {
2809            SiloState::Running => {
2810                silo.state = SiloState::Paused;
2811                let t = silo.tasks.clone();
2812                (silo_id, t)
2813            }
2814            _ => return Err(SyscallError::InvalidArgument),
2815        }
2816    };
2817    for tid in &tasks {
2818        crate::process::suspend_task(*tid);
2819    }
2820    let mut mgr = SILO_MANAGER.lock();
2821    mgr.push_event(SiloEvent {
2822        silo_id: silo_id.into(),
2823        kind: SiloEventKind::Paused,
2824        data0: 0,
2825        data1: 0,
2826        tick: crate::process::scheduler::ticks(),
2827    });
2828    Ok(silo_id)
2829}
2830
2831pub fn kernel_resume_silo(selector: &str) -> Result<u32, SyscallError> {
2832    let (silo_id, tasks) = {
2833        let mut mgr = SILO_MANAGER.lock();
2834        let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2835        let silo = mgr.get_mut(silo_id)?;
2836        match silo.state {
2837            SiloState::Paused => {
2838                silo.state = SiloState::Running;
2839                let t = silo.tasks.clone();
2840                (silo_id, t)
2841            }
2842            _ => return Err(SyscallError::InvalidArgument),
2843        }
2844    };
2845    for tid in &tasks {
2846        crate::process::resume_task(*tid);
2847    }
2848    let mut mgr = SILO_MANAGER.lock();
2849    mgr.push_event(SiloEvent {
2850        silo_id: silo_id.into(),
2851        kind: SiloEventKind::Resumed,
2852        data0: 0,
2853        data1: 0,
2854        tick: crate::process::scheduler::ticks(),
2855    });
2856    Ok(silo_id)
2857}
2858
2859pub fn silo_detail_snapshot(selector: &str) -> Result<SiloDetailSnapshot, SyscallError> {
2860    let mgr = SILO_MANAGER.lock();
2861    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2862    let s = mgr.get(silo_id)?;
2863    Ok(SiloDetailSnapshot {
2864        base: SiloSnapshot {
2865            id: s.id.sid,
2866            tier: s.id.tier,
2867            name: s.name.clone(),
2868            strate_label: s.strate_label.clone(),
2869            state: s.state,
2870            task_count: s.tasks.len(),
2871            mem_usage_bytes: s.mem_usage_bytes,
2872            mem_min_bytes: s.config.mem_min,
2873            mem_max_bytes: s.config.mem_max,
2874            mode: s.config.mode,
2875            graphics_flags: s.config.flags
2876                & (SILO_FLAG_GRAPHICS
2877                    | SILO_FLAG_WEBRTC_NATIVE
2878                    | SILO_FLAG_GRAPHICS_READ_ONLY
2879                    | SILO_FLAG_WEBRTC_TURN_FORCE),
2880            graphics_max_sessions: s.config.graphics_max_sessions,
2881            graphics_session_ttl_sec: s.config.graphics_session_ttl_sec,
2882        },
2883        family: s.family,
2884        sandboxed: s.sandboxed,
2885        cpu_shares: s.config.cpu_shares,
2886        cpu_affinity_mask: s.config.cpu_affinity_mask,
2887        max_tasks: s.config.max_tasks,
2888        task_ids: s.tasks.iter().map(|t| t.as_u64()).collect(),
2889        unveil_rules: s
2890            .unveil_rules
2891            .iter()
2892            .map(|r| {
2893                let bits = (if r.rights.read { 4 } else { 0 })
2894                    | (if r.rights.write { 2 } else { 0 })
2895                    | (if r.rights.execute { 1 } else { 0 });
2896                (r.path.clone(), bits)
2897            })
2898            .collect(),
2899        granted_caps_count: s.granted_caps.len(),
2900        cpu_features_required: s.config.cpu_features_required,
2901        cpu_features_allowed: s.config.cpu_features_allowed,
2902        xcr0_mask: s.config.xcr0_mask,
2903        graphics_flags: s.config.flags
2904            & (SILO_FLAG_GRAPHICS
2905                | SILO_FLAG_WEBRTC_NATIVE
2906                | SILO_FLAG_GRAPHICS_READ_ONLY
2907                | SILO_FLAG_WEBRTC_TURN_FORCE),
2908        graphics_max_sessions: s.config.graphics_max_sessions,
2909        graphics_session_ttl_sec: s.config.graphics_session_ttl_sec,
2910    })
2911}
2912
2913pub fn list_events_snapshot() -> Vec<SiloEventSnapshot> {
2914    let mgr = SILO_MANAGER.lock();
2915    mgr.events
2916        .iter()
2917        .map(|e| SiloEventSnapshot {
2918            silo_id: e.silo_id,
2919            kind: e.kind,
2920            data0: e.data0,
2921            data1: e.data1,
2922            tick: e.tick,
2923        })
2924        .collect()
2925}
2926
2927pub fn list_events_for_silo(selector: &str) -> Result<Vec<SiloEventSnapshot>, SyscallError> {
2928    let mgr = SILO_MANAGER.lock();
2929    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2930    let sid64 = silo_id as u64;
2931    Ok(mgr
2932        .events
2933        .iter()
2934        .filter(|e| e.silo_id == sid64)
2935        .map(|e| SiloEventSnapshot {
2936            silo_id: e.silo_id,
2937            kind: e.kind,
2938            data0: e.data0,
2939            data1: e.data1,
2940            tick: e.tick,
2941        })
2942        .collect())
2943}
2944
2945pub fn kernel_pledge_silo(selector: &str, mode_val: u16) -> Result<(u16, u16), SyscallError> {
2946    let new_mode = OctalMode::from_octal(mode_val);
2947    let mut mgr = SILO_MANAGER.lock();
2948    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2949    let silo = mgr.get_mut(silo_id)?;
2950    let old_raw = silo.config.mode;
2951    silo.mode.pledge(new_mode)?;
2952    silo.config.mode = mode_val;
2953    Ok((old_raw, mode_val))
2954}
2955
2956pub fn kernel_unveil_silo(
2957    selector: &str,
2958    path: &str,
2959    rights_str: &str,
2960) -> Result<u32, SyscallError> {
2961    let rights = UnveilRights {
2962        read: rights_str.contains('r'),
2963        write: rights_str.contains('w'),
2964        execute: rights_str.contains('x'),
2965    };
2966    let mut mgr = SILO_MANAGER.lock();
2967    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2968    let silo = mgr.get_mut(silo_id)?;
2969    if let Some(rule) = silo.unveil_rules.iter_mut().find(|r| r.path == path) {
2970        rule.rights = rights;
2971    } else {
2972        if silo
2973            .unveil_rules
2974            .push(UnveilRule {
2975                path: String::from(path),
2976                rights,
2977            })
2978            .is_err()
2979        {
2980            log::warn!("[silo] unveil_rules full (capacity=128), rule dropped");
2981        }
2982    }
2983    Ok(silo_id)
2984}
2985
2986pub fn kernel_sandbox_silo(selector: &str) -> Result<u32, SyscallError> {
2987    let mut mgr = SILO_MANAGER.lock();
2988    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
2989    let silo = mgr.get_mut(silo_id)?;
2990    silo.sandboxed = true;
2991    crate::audit::log(
2992        crate::audit::AuditCategory::Security,
2993        0,
2994        silo_id,
2995        alloc::format!("silo sandboxed"),
2996    );
2997    Ok(silo_id)
2998}
2999
3000/// Get the silo ID for a given task, if any.
3001pub fn task_silo_id(task_id: TaskId) -> Option<u32> {
3002    SILO_MANAGER.lock().silo_for_task(task_id)
3003}
3004
3005/// Append data to a silo's output ring buffer (called from `sys_debug_log`).
3006pub fn silo_output_write(silo_id: u32, data: &[u8]) {
3007    let mut mgr = SILO_MANAGER.lock();
3008    if let Ok(silo) = mgr.get_mut(silo_id) {
3009        let buf = silo
3010            .output_buf
3011            .get_or_insert_with(|| Box::new(SiloOutputBuf::new()));
3012        buf.push(data);
3013    }
3014}
3015
3016/// Drain the output buffer for a silo, returning accumulated bytes.
3017pub fn silo_output_drain(selector: &str) -> Result<Vec<u8>, SyscallError> {
3018    let mut mgr = SILO_MANAGER.lock();
3019    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
3020    let silo = mgr.get_mut(silo_id)?;
3021    let mut buf = match silo.output_buf.take() {
3022        Some(buf) => buf,
3023        None => return Ok(Vec::new()),
3024    };
3025    let out = buf.drain();
3026    silo.output_buf = Some(buf);
3027    Ok(out)
3028}
3029
3030/// Dynamically adjust resource quotas for a silo.
3031///
3032/// `key` can be: `mem_max`, `mem_min`, `max_tasks`, `cpu_shares`.
3033/// Values are parsed as u64 (bytes for memory, count otherwise).
3034pub fn kernel_limit_silo(selector: &str, key: &str, value: u64) -> Result<u32, SyscallError> {
3035    let mut mgr = SILO_MANAGER.lock();
3036    let silo_id = resolve_selector_to_silo_id(selector, &mgr)?;
3037    let silo = mgr.get_mut(silo_id)?;
3038    let mut next_mem_min = silo.config.mem_min;
3039    let mut next_mem_max = silo.config.mem_max;
3040    let mut next_max_tasks = silo.config.max_tasks;
3041    let mut next_cpu_shares = silo.config.cpu_shares;
3042    match key {
3043        "mem_max" => next_mem_max = value,
3044        "mem_min" => next_mem_min = value,
3045        "max_tasks" => {
3046            if value > u32::MAX as u64 {
3047                return Err(SyscallError::InvalidArgument);
3048            }
3049            next_max_tasks = value as u32;
3050        }
3051        "cpu_shares" => {
3052            if value > u32::MAX as u64 {
3053                return Err(SyscallError::InvalidArgument);
3054            }
3055            next_cpu_shares = value as u32;
3056        }
3057        _ => return Err(SyscallError::InvalidArgument),
3058    }
3059    if next_mem_max != 0 && next_mem_min > next_mem_max {
3060        return Err(SyscallError::InvalidArgument);
3061    }
3062    silo.config.mem_min = next_mem_min;
3063    silo.config.mem_max = next_mem_max;
3064    silo.config.max_tasks = next_max_tasks;
3065    silo.config.cpu_shares = next_cpu_shares;
3066    crate::audit::log(
3067        crate::audit::AuditCategory::Security,
3068        0,
3069        silo_id,
3070        alloc::format!("silo limit: {}={}", key, value),
3071    );
3072    Ok(silo_id)
3073}
3074
3075// ============================================================================
3076// Fault handling (called from exception handlers)
3077// ============================================================================
3078
3079/// Performs the dump user fault operation.
3080fn dump_user_fault(task_id: TaskId, reason: SiloFaultReason, extra: u64, subcode: u64, rip: u64) {
3081    let task_meta = crate::process::get_task_by_id(task_id).map(|task| {
3082        let state = task.get_state();
3083        let as_ref = task.process.address_space_arc();
3084        (
3085            task.pid,
3086            task.tid,
3087            task.name,
3088            state,
3089            as_ref.cr3().as_u64(),
3090            as_ref.is_kernel(),
3091        )
3092    });
3093
3094    if let Some((pid, tid, name, state, as_cr3, as_is_kernel)) = task_meta {
3095        crate::serial_force_println!(
3096            "\x1b[31m[handle_user_fault]\x1b[0m task={} \x1b[36mpid={}\x1b[0m tid={} name='{}' state={:?} reason={:?} \x1b[35mrip={:#x}\x1b[0m \x1b[35mextra={:#x}\x1b[0m subcode={:#x} as_cr3={:#x} as_kernel={}",
3097            task_id.as_u64(),
3098            pid,
3099            tid,
3100            name,
3101            state,
3102            reason,
3103            rip,
3104            extra,
3105            subcode,
3106            as_cr3,
3107            as_is_kernel
3108        );
3109    } else {
3110        crate::serial_force_println!(
3111            "\x1b[31m[handle_user_fault]\x1b[0m task={} reason={:?} \x1b[35mrip={:#x}\x1b[0m \x1b[35mextra={:#x}\x1b[0m subcode={:#x} (task metadata unavailable)",
3112            task_id.as_u64(),
3113            reason,
3114            rip,
3115            extra,
3116            subcode
3117        );
3118    }
3119
3120    if reason == SiloFaultReason::PageFault {
3121        let present = (subcode & 0x1) != 0;
3122        let write = (subcode & 0x2) != 0;
3123        let user = (subcode & 0x4) != 0;
3124        let reserved = (subcode & 0x8) != 0;
3125        let instr_fetch = (subcode & 0x10) != 0;
3126        let pkey = (subcode & 0x20) != 0;
3127        let shadow_stack = (subcode & 0x40) != 0;
3128        let sgx = (subcode & 0x8000) != 0;
3129        crate::serial_force_println!(
3130            "\x1b[31m[handle_user_fault]\x1b[0m \x1b[31mpagefault\x1b[0m \x1b[35maddr={:#x}\x1b[0m \x1b[35mrip={:#x}\x1b[0m ec={:#x} present={} write={} user={} reserved={} ifetch={} pkey={} shadow_stack={} sgx={}",
3131            extra,
3132            rip,
3133            subcode,
3134            present,
3135            write,
3136            user,
3137            reserved,
3138            instr_fetch,
3139            pkey,
3140            shadow_stack,
3141            sgx
3142        );
3143        if user && extra < 0x1000 {
3144            crate::serial_force_println!(
3145                "\x1b[31m[handle_user_fault]\x1b[0m \x1b[33mhint: low user address fault ({:#x}) -> probable NULL/near-NULL dereference\x1b[0m",
3146                extra
3147            );
3148        }
3149    } else {
3150        crate::serial_force_println!(
3151            "\x1b[31m[handle_user_fault]\x1b[0m \x1b[31mfault detail\x1b[0m \x1b[35mrip={:#x}\x1b[0m code={:#x}",
3152            rip,
3153            subcode
3154        );
3155    }
3156}
3157
3158/// Handles user fault.
3159pub fn handle_user_fault(
3160    task_id: TaskId,
3161    reason: SiloFaultReason,
3162    extra: u64,
3163    subcode: u64,
3164    rip: u64,
3165) {
3166    // FORCE OUTPUT for user fault - bypasses normal logging mutexes
3167    crate::serial_force_println!(
3168        "\x1b[31;1m[handle_user_fault] CRITICAL FAULT\x1b[0m: tid={} reason={:?} rip={:#x} addr={:#x} err={:#x}",
3169        task_id.as_u64(),
3170        reason,
3171        rip,
3172        extra,
3173        subcode
3174    );
3175
3176    dump_user_fault(task_id, reason, extra, subcode, rip);
3177
3178    // Best-effort: map task to silo, mark crashed, emit event, kill tasks.
3179    let tasks = {
3180        let mut mgr = SILO_MANAGER.lock();
3181        let silo_id = match mgr.silo_for_task(task_id) {
3182            Some(id) => id,
3183            None => {
3184                crate::serial_force_println!(
3185                    "[handle_user_fault] Non-silo task {} crashed (reason={:?})! Killing it.",
3186                    task_id.as_u64(),
3187                    reason
3188                );
3189                drop(mgr);
3190                crate::process::kill_task(task_id);
3191                return;
3192            }
3193        };
3194        let mut tasks = HVec::<TaskId, 64>::new();
3195        {
3196            if let Ok(silo) = mgr.get_mut(silo_id) {
3197                silo.state = SiloState::Crashed;
3198                tasks = silo.tasks.clone();
3199                silo.tasks.clear();
3200                silo.event_seq = silo.event_seq.wrapping_add(1);
3201            }
3202        }
3203        for tid in &tasks {
3204            mgr.unmap_task(*tid);
3205        }
3206        mgr.push_event(SiloEvent {
3207            silo_id: silo_id.into(),
3208            kind: SiloEventKind::Crashed,
3209            data0: pack_fault(reason, subcode),
3210            data1: extra,
3211            tick: crate::process::scheduler::ticks(),
3212        });
3213        tasks
3214    };
3215
3216    for tid in &tasks {
3217        crate::process::kill_task(*tid);
3218    }
3219    if !tasks.contains(&task_id) {
3220        crate::process::kill_task(task_id);
3221    }
3222}