Skip to main content

strat9_kernel/syscall/
trace.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Kernel trace control (`SYS_TRACE_CTL`, `SYS_TRACE_READ`).
24//!
25//! The per-CPU trace rings already existed for memory events; these syscalls
26//! expose the IPC/scheduling/syscall/IRQ categories to a userspace tracing
27//! daemon. Everything is gated on silo-admin capability because records
28//! contain kernel instruction pointers, task ids and wake deadlines.
29//!
30//! Cost when tracing is disabled is a single relaxed mask load per hook:
31//! the same `enabled()` check that the memory trace already pays.
32
33use super::error::SyscallError;
34use crate::{arch::percpu, memory::UserSliceWrite, silo};
35use alloc::vec::Vec;
36use strat9_abi::{
37    data::{TraceRecord, TraceStats},
38    syscall::{TRACE_CTL_CLEAR, TRACE_CTL_GET_MASK, TRACE_CTL_SET_MASK, TRACE_CTL_STATS},
39};
40
41/// Upper bound on records returned by one `SYS_TRACE_READ` call.
42///
43/// 4096 records is 384 KiB; larger dumps should be paged by the caller so a
44/// single syscall cannot force a large kernel allocation.
45const TRACE_READ_MAX: u64 = 4096;
46
47/// `SYS_TRACE_CTL(602)`: configure the trace subsystem.
48pub fn sys_trace_ctl(cmd: u64, arg: u64) -> Result<u64, SyscallError> {
49    silo::require_silo_admin()?;
50    let cmd = u32::try_from(cmd).map_err(|_| SyscallError::InvalidArgument)?;
51    match cmd {
52        TRACE_CTL_SET_MASK => {
53            let old = crate::trace::mask();
54            crate::trace::set_mask(arg);
55            Ok(old)
56        }
57        TRACE_CTL_GET_MASK => Ok(crate::trace::mask()),
58        TRACE_CTL_CLEAR => {
59            crate::trace::clear_all();
60            Ok(0)
61        }
62        TRACE_CTL_STATS => {
63            let stats = crate::trace::stats();
64            let out = UserSliceWrite::new(arg, core::mem::size_of::<TraceStats>())?;
65            let abi = TraceStats {
66                stored: stats.stored,
67                dropped: stats.dropped,
68            };
69            let raw = unsafe {
70                core::slice::from_raw_parts(
71                    &abi as *const TraceStats as *const u8,
72                    core::mem::size_of::<TraceStats>(),
73                )
74            };
75            if out.copy_from(raw) != raw.len() {
76                return Err(SyscallError::Fault);
77            }
78            Ok(0)
79        }
80        _ => Err(SyscallError::InvalidArgument),
81    }
82}
83
84/// `SYS_TRACE_READ(603)`: copy trace records to userspace.
85pub fn sys_trace_read(out_ptr: u64, max_records: u64, flags: u64) -> Result<u64, SyscallError> {
86    silo::require_silo_admin()?;
87    if flags != 0 {
88        return Err(SyscallError::InvalidArgument);
89    }
90
91    let max = max_records.min(TRACE_READ_MAX) as usize;
92    if max == 0 {
93        return Ok(0);
94    }
95
96    let record_size = core::mem::size_of::<TraceRecord>();
97    let out = UserSliceWrite::new(out_ptr, max * record_size)?;
98
99    // Bound the total allocation: ask each CPU for a fair share, then truncate
100    // to the caller's capacity after the global sequence sort.
101    let mut online = [0usize; percpu::MAX_CPUS];
102    let online_count = percpu::online_cpu_indices(&mut online).max(1);
103    let per_cpu = (max / online_count).max(1);
104
105    let events = crate::trace::snapshot_all(per_cpu);
106    let count = events.len().min(max);
107    if count == 0 {
108        return Ok(0);
109    }
110
111    let mut raw: Vec<u8> = Vec::with_capacity(count * record_size);
112    for event in events.into_iter().take(count) {
113        let record = TraceRecord {
114            seq: event.seq,
115            ticks: event.ticks,
116            cpu: event.cpu,
117            kind: event.kind,
118            reserved: 0,
119            category: event.category,
120            flags: event.flags,
121            task_id: event.task_id,
122            pid: event.pid,
123            tid: event.tid,
124            cr3: event.cr3,
125            rip: event.rip,
126            vaddr: event.vaddr,
127            arg0: event.arg0,
128            arg1: event.arg1,
129        };
130        // SAFETY: `TraceRecord` is `repr(C)` with no padding (static-asserted
131        // in the ABI crate) and `record` is a fully initialised value.
132        let bytes = unsafe {
133            core::slice::from_raw_parts(&record as *const TraceRecord as *const u8, record_size)
134        };
135        raw.extend_from_slice(bytes);
136    }
137
138    if out.copy_from(&raw) != raw.len() {
139        return Err(SyscallError::Fault);
140    }
141    Ok(count as u64)
142}