os/log/
context.rs

1//! 日志上下文收集
2//!
3//! 该模块为每个日志条目收集**上下文信息**(CPU ID、任务 ID、时间戳)。
4
5use crate::arch::{kernel::cpu::cpu_id, timer};
6
7/// 日志条目的上下文信息
8pub(super) struct LogContext {
9    /// 生成此日志的 CPU ID
10    pub(super) cpu_id: usize,
11    /// 生成此日志的任务/进程 ID
12    pub(super) task_id: u32,
13    /// 创建日志时的时间戳
14    pub(super) timestamp: usize,
15}
16
17/// 为新的日志条目收集上下文信息
18///
19/// # 实现状态
20///
21/// - **时间戳**: 已通过 `arch::timer::get_time()` 实现
22/// - **CPU ID**: 通过 `arch::kernel::cpu::cpu_id()` 实现
23/// - **任务 ID**: 通过当前任务的 tid 字段获取(如果存在任务)
24pub(super) fn collect_context() -> LogContext {
25    // 获取 CPU ID
26    let cpu_id = cpu_id();
27
28    // 尝试获取当前任务的 tid
29    // 注意:在早期启动或中断上下文中可能没有当前任务
30    // 更重要的是:如果当前已经在持有 task lock 的上下文中(例如 wait4),
31    // 再次尝试获取锁会导致死锁。因此这里必须使用 try_lock。
32    let task_id = crate::kernel::current_cpu()
33        .try_lock()
34        .and_then(|cpu| cpu.current_task.as_ref().cloned())
35        .and_then(|task| task.try_lock().map(|t| t.tid))
36        .unwrap_or(0);
37
38    LogContext {
39        cpu_id,
40        task_id,
41        timestamp: timer::get_time(),
42    }
43}