diff --git a/kernel/arch/hpet.rs b/kernel/arch/hpet.rs index 77c8caf..af2ff8f 100644 --- a/kernel/arch/hpet.rs +++ b/kernel/arch/hpet.rs @@ -298,6 +298,182 @@ pub fn frequency_hz() -> Option { HPET_STATE.get().map(|info| info.frequency_hz) } +/// N2.6b: Read monotonic nanoseconds elapsed since HPET initialization. +/// +/// Only uses 64-bit HPET counters so counter wraparound (~40,000+ years at +/// 14.318 MHz) cannot regress monotonic time. Returns `None` if HPET is +/// unavailable or 32-bit-only (caller falls back to 1 kHz tick time). +#[inline] +pub fn elapsed_ns() -> Option { + let info = HPET_STATE.get()?; + if !info.counter_64bit || info.period_fs == 0 { + return None; + } + let counter = read_main_counter()?; + // counter * period_fs / 1_000_000 (1 ns = 10^6 fs). + Some(((counter as u128).saturating_mul(info.period_fs as u128) / 1_000_000) as u64) +} + +/// N2.6b: Effective HPET clock resolution in nanoseconds (at least 1 ns). +#[inline] +pub fn resolution_ns() -> Option { + let info = HPET_STATE.get()?; + if !info.counter_64bit || info.period_fs == 0 { + return None; + } + Some((info.period_fs / 1_000_000).max(1)) +} + +// ============================================================================ +// N2.6b: MC146818 CMOS RTC Wall-Clock Reader (x86_64 ports 0x70 / 0x71) +// ============================================================================ + +/// Convert a Gregorian calendar UTC date/time to Unix epoch seconds (1970-01-01). +/// Pure, no-I/O implementation using Howard Hinnant's civil-days algorithm. +pub fn civil_to_unix_secs( + year: i64, + month: u8, + day: u8, + hour: u8, + minute: u8, + second: u8, +) -> Option { + if year < 1970 + || !(1..=12).contains(&month) + || !(1..=31).contains(&day) + || hour > 23 + || minute > 59 + || second > 59 + { + return None; + } + let m = month as i64; + let d = day as i64; + let y = year - if m <= 2 { 1 } else { 0 }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; // [0, 399] + let mp = m + if m > 2 { -3 } else { 9 }; // [0, 11] + let doy = (153 * mp + 2) / 5 + d - 1; // [0, 365] + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] + let days_since_epoch = era * 146097 + doe - 719468; + if days_since_epoch < 0 { + return None; + } + let total_secs = (days_since_epoch as u64) + .checked_mul(86_400)? + .checked_add((hour as u64) * 3_600)? + .checked_add((minute as u64) * 60)? + .checked_add(second as u64)?; + Some(total_secs) +} + +#[inline] +fn bcd_to_bin(v: u8) -> Option { + let lo = v & 0x0F; + let hi = (v >> 4) & 0x0F; + if lo > 9 || hi > 9 { + return None; + } + Some(hi * 10 + lo) +} + +/// Decode raw MC146818 CMOS RTC registers into Unix epoch seconds. +pub fn decode_cmos_rtc_fields( + mut sec: u8, + mut min: u8, + mut hour: u8, + mut day: u8, + mut month: u8, + mut year: u8, + mut century: u8, + status_b: u8, +) -> Option { + let is_binary = (status_b & 0x04) != 0; + let is_24h = (status_b & 0x02) != 0; + let pm = !is_24h && (hour & 0x80) != 0; + hour &= 0x7F; + + if !is_binary { + sec = bcd_to_bin(sec)?; + min = bcd_to_bin(min)?; + hour = bcd_to_bin(hour)?; + day = bcd_to_bin(day)?; + month = bcd_to_bin(month)?; + year = bcd_to_bin(year)?; + if century != 0 { + century = bcd_to_bin(century).unwrap_or(0); + } + } + + if !is_24h { + if hour == 12 { + hour = if pm { 12 } else { 0 }; + } else if pm { + hour = hour.checked_add(12)?; + } + } + + let full_year = if (19..=99).contains(¢ury) { + (century as i64) * 100 + (year as i64) + } else { + 2000 + (year as i64) + }; + civil_to_unix_secs(full_year, month, day, hour, min, sec) +} + +/// Read the x86 MC146818 CMOS RTC at boot and return UTC Unix epoch seconds. +/// +/// Bounded retry loop waits for UIP (Update-In-Progress) to clear and requires +/// two identical consecutive reads to avoid mid-second rollover corruption. +/// Returns `None` if the RTC is absent or reports invalid/uninitialized fields. +#[cfg(target_arch = "x86_64")] +pub fn read_cmos_rtc_unix_secs() -> Option { + use x86_64::instructions::port::Port; + + let read_reg = |reg: u8| -> u8 { + // SAFETY: MC146818 CMOS index (0x70) / data (0x71) ports, ring 0 only. + unsafe { + let mut idx: Port = Port::new(0x70); + let mut data: Port = Port::new(0x71); + idx.write(reg & 0x7F); + data.read() + } + }; + + let sample = || -> Option<[u8; 8]> { + for _ in 0..10_000 { + if (read_reg(0x0A) & 0x80) == 0 { + return Some([ + read_reg(0x00), + read_reg(0x02), + read_reg(0x04), + read_reg(0x07), + read_reg(0x08), + read_reg(0x09), + read_reg(0x32), + read_reg(0x0B), + ]); + } + core::hint::spin_loop(); + } + None + }; + + for _ in 0..8 { + let a = sample()?; + let b = sample()?; + if a == b { + return decode_cmos_rtc_fields(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]); + } + } + None +} + +#[cfg(not(target_arch = "x86_64"))] +pub fn read_cmos_rtc_unix_secs() -> Option { + None +} + // ============================================================================ // Internal Implementation // ============================================================================ @@ -463,3 +639,58 @@ unsafe fn write_reg64(base_virt: u64, offset: usize, value: u64) { let addr = (base_virt + offset as u64) as *mut u64; write_volatile(addr, value); } + +#[cfg(test)] +mod n2_6b_rtc_tests { + use super::*; + + #[test] + fn n2_6b_civil_to_unix_secs_epoch_and_leap_years() { + assert_eq!(civil_to_unix_secs(1970, 1, 1, 0, 0, 0), Some(0)); + assert_eq!( + civil_to_unix_secs(2000, 2, 29, 12, 30, 45), + Some(951_827_445) + ); + assert_eq!(civil_to_unix_secs(2024, 3, 1, 0, 0, 0), Some(1_709_251_200)); + assert_eq!( + civil_to_unix_secs(2026, 11, 28, 4, 0, 0), + Some(1_795_838_400) + ); + // Invalid bounds fail closed. + assert_eq!(civil_to_unix_secs(1969, 12, 31, 23, 59, 59), None); + assert_eq!(civil_to_unix_secs(2026, 13, 1, 0, 0, 0), None); + assert_eq!(civil_to_unix_secs(2026, 1, 1, 24, 0, 0), None); + } + + #[test] + fn n2_6b_decode_cmos_rtc_bcd_binary_and_12h() { + // BCD + 24h (status_b = 0x02): 2026-11-28 04:00:00 UTC + assert_eq!( + decode_cmos_rtc_fields(0x00, 0x00, 0x04, 0x28, 0x11, 0x26, 0x20, 0x02), + Some(1_795_838_400) + ); + // Binary + 24h (status_b = 0x06), century = 0 defaults to 20xx + assert_eq!( + decode_cmos_rtc_fields(0, 0, 4, 28, 11, 26, 0, 0x06), + Some(1_795_838_400) + ); + // Binary + 12h PM (status_b = 0x04): 12:00 PM -> 12:00, 1:00 PM -> 13:00, 12:00 AM -> 00:00 + assert_eq!( + decode_cmos_rtc_fields(0, 0, 12 | 0x80, 1, 1, 70, 19, 0x04), + Some(12 * 3600) + ); + assert_eq!( + decode_cmos_rtc_fields(0, 0, 1 | 0x80, 1, 1, 70, 19, 0x04), + Some(13 * 3600) + ); + assert_eq!( + decode_cmos_rtc_fields(0, 0, 12, 1, 1, 70, 19, 0x04), + Some(0) + ); + // Malformed BCD digit rejected. + assert_eq!( + decode_cmos_rtc_fields(0x0A, 0x00, 0x04, 0x28, 0x11, 0x26, 0x20, 0x02), + None + ); + } +} diff --git a/kernel/kernel_core/process.rs b/kernel/kernel_core/process.rs index 38a59f7..d7959e4 100644 --- a/kernel/kernel_core/process.rs +++ b/kernel/kernel_core/process.rs @@ -13108,6 +13108,8 @@ pub fn terminate_process(pid: ProcessId, exit_code: i32) { // last live member exits, under the group id (an init is always a group // leader), never when the first of several threads does. if last_live { + // N2.6b: Reclaim all interval timers and POSIX timers owned by this process. + crate::time::cleanup_all_timers_for_process(tgid); if tgid == pid { handle_namespace_init_death(pid, &pid_ns_chain); } else { diff --git a/kernel/kernel_core/scheduler_hook.rs b/kernel/kernel_core/scheduler_hook.rs index e05f693..2dfc24d 100644 --- a/kernel/kernel_core/scheduler_hook.rs +++ b/kernel/kernel_core/scheduler_hook.rs @@ -389,6 +389,9 @@ fn reschedule_if_needed_inner(post_drain: Option, forced_origin: Option Result Result { + send_process_signal(pid, signal, false, Some(info), false) +} + +/// N2.6b: Kernel-authoritative thread-directed signal with explicit `SigInfo` +/// (e.g. POSIX `timer_create(SIGEV_THREAD_ID)` with `SI_TIMER`). +pub fn send_signal_kernel_thread_with_info( + tid: ProcessId, + signal: Signal, + info: SigInfo, +) -> Result { + send_signal_inner(tid, signal, false, SignalScope::Thread, Some(info), false) +} + /// GAP-5 G7: where a generated signal is queued. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SignalScope { diff --git a/kernel/kernel_core/syscall/abi.rs b/kernel/kernel_core/syscall/abi.rs index 968d63b..a645b28 100644 --- a/kernel/kernel_core/syscall/abi.rs +++ b/kernel/kernel_core/syscall/abi.rs @@ -127,6 +127,66 @@ pub(super) struct TimeSpec { // H.0.1-3: Compile-time ABI size assertion. const _: [(); 16] = [(); core::mem::size_of::()]; +/// struct itimerval (Linux x86_64 ABI, 32 bytes, N2.6b) +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(super) struct ITimerVal { + pub(super) it_interval_sec: i64, + pub(super) it_interval_usec: i64, + pub(super) it_value_sec: i64, + pub(super) it_value_usec: i64, +} + +const _: [(); 32] = [(); core::mem::size_of::()]; +const _: [(); 8] = [(); core::mem::align_of::()]; +const _: [(); 0] = [(); core::mem::offset_of!(ITimerVal, it_interval_sec)]; +const _: [(); 16] = [(); core::mem::offset_of!(ITimerVal, it_value_sec)]; + +/// struct itimerspec (Linux x86_64 ABI, 32 bytes, N2.6b) +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(super) struct ITimerSpec { + pub(super) it_interval_sec: i64, + pub(super) it_interval_nsec: i64, + pub(super) it_value_sec: i64, + pub(super) it_value_nsec: i64, +} + +const _: [(); 32] = [(); core::mem::size_of::()]; +const _: [(); 8] = [(); core::mem::align_of::()]; +const _: [(); 0] = [(); core::mem::offset_of!(ITimerSpec, it_interval_sec)]; +const _: [(); 16] = [(); core::mem::offset_of!(ITimerSpec, it_value_sec)]; + +/// struct sigevent (Linux x86_64 ABI, 64 bytes, N2.6b) +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct SigEvent { + pub(super) sigev_value: u64, + pub(super) sigev_signo: i32, + pub(super) sigev_notify: i32, + pub(super) sigev_notify_tid: i32, + pub(super) _pad: [u8; 44], +} + +impl Default for SigEvent { + fn default() -> Self { + Self { + sigev_value: 0, + sigev_signo: 0, + sigev_notify: 0, + sigev_notify_tid: 0, + _pad: [0; 44], + } + } +} + +const _: [(); 64] = [(); core::mem::size_of::()]; +const _: [(); 8] = [(); core::mem::align_of::()]; +const _: [(); 0] = [(); core::mem::offset_of!(SigEvent, sigev_value)]; +const _: [(); 8] = [(); core::mem::offset_of!(SigEvent, sigev_signo)]; +const _: [(); 12] = [(); core::mem::offset_of!(SigEvent, sigev_notify)]; +const _: [(); 16] = [(); core::mem::offset_of!(SigEvent, sigev_notify_tid)]; + /// struct utsname (Linux ABI, fixed-size strings) /// /// D2-ABI-STAT-LAYOUT (LOW leg): Linux `new_utsname` is 6 x [u8;65] = 390 diff --git a/kernel/kernel_core/syscall/exec.rs b/kernel/kernel_core/syscall/exec.rs index 786634a..6712da6 100644 --- a/kernel/kernel_core/syscall/exec.rs +++ b/kernel/kernel_core/syscall/exec.rs @@ -904,6 +904,7 @@ pub(super) fn exec_from_bytes( cloexec_cgroup_id, cloexec_closed, old_shared_regions, + exec_tgid, ) = { let mut proc = process.lock(); @@ -1199,6 +1200,7 @@ pub(super) fn exec_from_bytes( proc.poll_restore_blocked = None; // N2.6a: POSIX/Linux execve(2) disables any established alternate signal stack. proc.sigaltstack = crate::signal::SigAltStack::disabled(); + let exec_tgid = proc.tgid; // Robust-list registration is address-space-local. Clear the old // image's pointer before publishing the replacement so exit cleanup // cannot dereference stale or newly-reused virtual memory. @@ -1223,9 +1225,14 @@ pub(super) fn exec_from_bytes( cloexec_cgroup_id, cloexec_closed, old_shared_regions, + exec_tgid, ) }; + // N2.6b: POSIX execve(2) deletes POSIX timer_create timers while preserving + // ITIMER_REAL / alarm. Run outside the Process lock. + crate::time::cleanup_posix_timers_for_exec(exec_tgid); + // R169-4 FIX (HIGH, lock inversion): Drop the closed CLOEXEC // FileDescriptors and uncharge the per-cgroup FD budget OUTSIDE the Process // lock. SocketFile::Drop → socket close → wake_all (re-locks PROCESS_TABLE + diff --git a/kernel/kernel_core/syscall/futex.rs b/kernel/kernel_core/syscall/futex.rs index d720891..62ab4f4 100644 --- a/kernel/kernel_core/syscall/futex.rs +++ b/kernel/kernel_core/syscall/futex.rs @@ -489,10 +489,19 @@ pub(super) fn sys_futex( Some(match timeout_kind { FutexTimeoutKind::Relative => timeout_ns, // A deadline already passed becomes 0, which times out at once - // (after the value check, as on Linux). CLOCK_REALTIME and - // CLOCK_MONOTONIC read the same tick here. - FutexTimeoutKind::Absolute => timeout_ns - .saturating_sub(crate::time::current_timestamp_ms().saturating_mul(1_000_000)), + // (after the value check, as on Linux). N2.6b: honor + // FUTEX_CLOCK_REALTIME (and FUTEX_LOCK_PI which is always realtime) + // against wall-clock `realtime_ns()`, and monotonic ops against + // `monotonic_ns()`. + FutexTimeoutKind::Absolute => { + let use_realtime = (linux_op & 256) != 0 || (linux_op & !(128 | 256)) == 6; + let now_ns = if use_realtime { + crate::time::realtime_ns() + } else { + crate::time::monotonic_ns() + }; + timeout_ns.saturating_sub(now_ns) + } }) } else { None diff --git a/kernel/kernel_core/syscall/mod.rs b/kernel/kernel_core/syscall/mod.rs index 95969e6..a8ebdcd 100644 --- a/kernel/kernel_core/syscall/mod.rs +++ b/kernel/kernel_core/syscall/mod.rs @@ -855,8 +855,34 @@ pub fn syscall_dispatcher( // 时间相关 Sc::Nanosleep => sys_nanosleep(arg0 as *const TimeSpec, arg1 as *mut TimeSpec), + Sc::Getitimer => sys_getitimer(arg0 as i32, arg1 as *mut ITimerVal), + Sc::Alarm => sys_alarm(arg0 as u32), + Sc::Setitimer => sys_setitimer( + arg0 as i32, + arg1 as *const ITimerVal, + arg2 as *mut ITimerVal, + ), Sc::Gettimeofday => sys_gettimeofday(arg0 as *mut TimeVal, arg1 as usize), + Sc::TimerCreate => { + sys_timer_create(arg0 as i32, arg1 as *const SigEvent, arg2 as *mut i32) + } + Sc::TimerSettime => sys_timer_settime( + arg0 as i32, + arg1 as i32, + arg2 as *const ITimerSpec, + arg3 as *mut ITimerSpec, + ), + Sc::TimerGettime => sys_timer_gettime(arg0 as i32, arg1 as *mut ITimerSpec), + Sc::TimerGetoverrun => sys_timer_getoverrun(arg0 as i32), + Sc::TimerDelete => sys_timer_delete(arg0 as i32), Sc::ClockGettime => sys_clock_gettime(arg0 as i32, arg1 as *mut TimeSpec), + Sc::ClockGetres => sys_clock_getres(arg0 as i32, arg1 as *mut TimeSpec), + Sc::ClockNanosleep => sys_clock_nanosleep( + arg0 as i32, + arg1 as i32, + arg2 as *const TimeSpec, + arg3 as *mut TimeSpec, + ), // 系统信息 Sc::Uname => sys_uname(arg0 as *mut UtsName), diff --git a/kernel/kernel_core/syscall/time.rs b/kernel/kernel_core/syscall/time.rs index 385e668..fb74a1e 100644 --- a/kernel/kernel_core/syscall/time.rs +++ b/kernel/kernel_core/syscall/time.rs @@ -111,6 +111,24 @@ pub(super) const CLOCK_REALTIME_COARSE: i32 = 5; pub(super) const CLOCK_MONOTONIC_COARSE: i32 = 6; pub(super) const CLOCK_BOOTTIME: i32 = 7; +/// Build a `struct timespec` from nanoseconds. +#[inline] +pub(super) fn timespec_from_ns(ns: u64) -> TimeSpec { + TimeSpec { + tv_sec: (ns / 1_000_000_000) as i64, + tv_nsec: (ns % 1_000_000_000) as i64, + } +} + +/// Build a `struct timeval` from nanoseconds. +#[inline] +pub(super) fn timeval_from_ns(ns: u64) -> TimeVal { + TimeVal { + tv_sec: (ns / 1_000_000_000) as i64, + tv_usec: ((ns % 1_000_000_000) / 1_000) as i64, + } +} + /// Build a `struct timespec` from a millisecond count (sec + nanosecond remainder). pub(super) fn timespec_from_ms(ms: u64) -> TimeSpec { TimeSpec { @@ -127,16 +145,54 @@ pub(super) fn timeval_from_ms(ms: u64) -> TimeVal { } } -/// Whether `clock_gettime` can satisfy `clockid` from the current time source. -/// -/// Zero-OS exposes a SINGLE monotonic millisecond tick (`current_timestamp_ms`), -/// so REALTIME currently aliases uptime exactly as `sys_gettimeofday` already -/// does, and the whole MONOTONIC family resolves to that same source. CPU-time -/// clocks (PROCESS/THREAD_CPUTIME_ID = 2/3) and unknown/negative/dynamic ids -/// return EINVAL until a real epoch wall-clock + per-task CPU accounting land -/// (Phase U). The realtime-vs-monotonic split is intentionally NOT branched on -/// today (both arms would be identical); that divergence seam is documented here -/// so the future epoch source only has to add an offset, not re-classify. +/// Convert a validated Linux `TimeSpec` into nanoseconds. +#[inline] +pub(super) fn timespec_to_ns(ts: &TimeSpec) -> Result { + if ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1_000_000_000 { + return Err(SyscallError::EINVAL); + } + Ok((ts.tv_sec as u64) + .saturating_mul(1_000_000_000) + .saturating_add(ts.tv_nsec as u64)) +} + +/// Convert a validated Linux `TimeVal` pair `(sec, usec)` into nanoseconds. +#[inline] +pub(super) fn timeval_pair_to_ns(sec: i64, usec: i64) -> Result { + if sec < 0 || usec < 0 || usec >= 1_000_000 { + return Err(SyscallError::EINVAL); + } + Ok((sec as u64) + .saturating_mul(1_000_000_000) + .saturating_add((usec as u64).saturating_mul(1_000))) +} + +/// N2.6b: Read the nanosecond timestamp for a supported `CLOCK_*` id. +#[inline] +pub(super) fn read_clock_ns(clockid: i32) -> Result { + match clockid { + CLOCK_REALTIME | CLOCK_REALTIME_COARSE => Ok(crate::time::realtime_ns()), + CLOCK_MONOTONIC | CLOCK_MONOTONIC_RAW | CLOCK_MONOTONIC_COARSE | CLOCK_BOOTTIME => { + Ok(crate::time::monotonic_ns()) + } + _ => Err(SyscallError::EINVAL), + } +} + +/// N2.6b: Map a `clockid` accepted by `timer_create` / `clock_nanosleep` to `TimerClock`. +#[inline] +pub(super) fn clockid_to_timer_clock( + clockid: i32, +) -> Result { + match clockid { + CLOCK_REALTIME => Ok(crate::time::TimerClock::Realtime), + CLOCK_MONOTONIC => Ok(crate::time::TimerClock::Monotonic), + CLOCK_BOOTTIME => Ok(crate::time::TimerClock::Boottime), + _ => Err(SyscallError::EINVAL), + } +} + +/// Whether `clock_gettime` / `clock_getres` can satisfy `clockid`. pub(super) fn startup_clockid_supported(clockid: i32) -> bool { matches!( clockid, @@ -151,17 +207,15 @@ pub(super) fn startup_clockid_supported(clockid: i32) -> bool { /// sys_clock_gettime - high-resolution clock query (syscall 228). /// -/// musl's crt faults without this. Fills a `struct timespec` from the kernel -/// millisecond tick for every supported clock id (see `startup_clockid_supported`). +/// N2.6b: `CLOCK_REALTIME` / `CLOCK_REALTIME_COARSE` return wall-clock Unix +/// epoch nanoseconds (seeded from CMOS RTC at boot); monotonic/boottime clocks +/// return nanosecond monotonic uptime (HPET 64-bit counter with 1 kHz fallback). pub(super) fn sys_clock_gettime(clockid: i32, tp: *mut TimeSpec) -> SyscallResult { if tp.is_null() { return Err(SyscallError::EFAULT); } - if !startup_clockid_supported(clockid) { - return Err(SyscallError::EINVAL); - } - - let timespec = timespec_from_ms(crate::time::current_timestamp_ms()); + let ns = read_clock_ns(clockid)?; + let timespec = timespec_from_ns(ns); // lint-repr-c-copy: allow (no-padding: TimeSpec {i64,i64} = 16 bytes) let tp_bytes = unsafe { @@ -176,6 +230,438 @@ pub(super) fn sys_clock_gettime(clockid: i32, tp: *mut TimeSpec) -> SyscallResul Ok(0) } +/// sys_clock_getres - query clock resolution (syscall 229, N2.6b). +/// +/// Linux/POSIX: a NULL `res` pointer is valid and checks `clockid` only. +pub(super) fn sys_clock_getres(clockid: i32, res: *mut TimeSpec) -> SyscallResult { + if !startup_clockid_supported(clockid) { + return Err(SyscallError::EINVAL); + } + if res.is_null() { + return Ok(0); + } + let coarse = matches!(clockid, CLOCK_REALTIME_COARSE | CLOCK_MONOTONIC_COARSE); + let res_ts = timespec_from_ns(crate::time::clock_resolution_ns(coarse)); + // lint-repr-c-copy: allow (no-padding: TimeSpec {i64,i64} = 16 bytes) + let bytes = unsafe { + core::slice::from_raw_parts( + &res_ts as *const TimeSpec as *const u8, + core::mem::size_of::(), + ) + }; + crate::usercopy::copy_to_user_safe(res as *mut u8, bytes).map_err(|_| SyscallError::EFAULT)?; + Ok(0) +} + +/// Linux `TIMER_ABSTIME` flag for `clock_nanosleep(2)` and `timer_settime(2)`. +pub(super) const TIMER_ABSTIME: i32 = 1; + +/// sys_clock_nanosleep - high-resolution sleep with selectable clock and +/// optional `TIMER_ABSTIME` (syscall 230, N2.6b). +pub(super) fn sys_clock_nanosleep( + clockid: i32, + flags: i32, + req: *const TimeSpec, + rem: *mut TimeSpec, +) -> SyscallResult { + if req.is_null() { + return Err(SyscallError::EFAULT); + } + if (flags & !TIMER_ABSTIME) != 0 { + return Err(SyscallError::EINVAL); + } + let clock = clockid_to_timer_clock(clockid)?; + let abstime = (flags & TIMER_ABSTIME) != 0; + + let mut ts = TimeSpec::default(); + // lint-repr-c-copy: allow (no-padding: TimeSpec {i64,i64} = 16 bytes; user→kernel) + let ts_bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut ts as *mut TimeSpec as *mut u8, + core::mem::size_of::(), + ) + }; + crate::usercopy::copy_from_user_safe(ts_bytes, req as *const u8) + .map_err(|_| SyscallError::EFAULT)?; + let req_ns = timespec_to_ns(&ts)?; + + let now_mono = crate::time::monotonic_ns(); + let deadline_mono = if abstime { + match clock { + crate::time::TimerClock::Realtime => { + req_ns.saturating_sub(crate::time::wall_clock_offset_ns()) + } + crate::time::TimerClock::Monotonic | crate::time::TimerClock::Boottime => req_ns, + } + } else { + now_mono.saturating_add(req_ns) + }; + + let mut interrupted = false; + while crate::time::monotonic_ns() < deadline_mono { + if let Some(pid) = current_pid() { + if wait_should_abort(pid) || crate::signal::has_deliverable_signal(pid) { + interrupted = true; + break; + } + } + crate::reschedule_if_needed(); + debug_assert!( + x86_64::instructions::interrupts::are_enabled(), + "clock_nanosleep loop must hlt with IRQs enabled" + ); + unsafe { + core::arch::asm!("hlt", options(nomem, nostack, preserves_flags)); + } + } + + // POSIX: `rem` is written ONLY on relative-sleep EINTR (never for TIMER_ABSTIME). + if interrupted && !abstime && !rem.is_null() { + let remaining_ns = deadline_mono.saturating_sub(crate::time::monotonic_ns()); + let rem_ts = timespec_from_ns(remaining_ns); + // lint-repr-c-copy: allow (no-padding: TimeSpec {i64,i64} = 16 bytes; kernel→user) + let rem_bytes = unsafe { + core::slice::from_raw_parts( + &rem_ts as *const TimeSpec as *const u8, + core::mem::size_of::(), + ) + }; + crate::usercopy::copy_to_user_safe(rem as *mut u8, rem_bytes) + .map_err(|_| SyscallError::EFAULT)?; + } + + if interrupted { + Err(SyscallError::EINTR) + } else { + Ok(0) + } +} + +// ============================================================================ +// N2.6b: Interval Timers (`alarm`, `getitimer`, `setitimer`) & POSIX Timers +// ============================================================================ + +pub(super) const ITIMER_REAL: i32 = 0; +pub(super) const ITIMER_VIRTUAL: i32 = 1; +pub(super) const ITIMER_PROF: i32 = 2; + +pub(super) const SIGEV_SIGNAL: i32 = 0; +pub(super) const SIGEV_NONE: i32 = 1; +pub(super) const SIGEV_THREAD_ID: i32 = 4; + +fn current_tgid() -> Result { + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let tgid = proc_arc.lock().tgid; + Ok(tgid) +} + +#[inline] +pub(super) fn itimerval_from_ns(interval_ns: u64, value_ns: u64) -> ITimerVal { + let iv = timeval_from_ns(interval_ns); + let val = timeval_from_ns(value_ns); + ITimerVal { + it_interval_sec: iv.tv_sec, + it_interval_usec: iv.tv_usec, + it_value_sec: val.tv_sec, + it_value_usec: val.tv_usec, + } +} + +#[inline] +pub(super) fn itimerspec_from_ns(interval_ns: u64, value_ns: u64) -> ITimerSpec { + let iv = timespec_from_ns(interval_ns); + let val = timespec_from_ns(value_ns); + ITimerSpec { + it_interval_sec: iv.tv_sec, + it_interval_nsec: iv.tv_nsec, + it_value_sec: val.tv_sec, + it_value_nsec: val.tv_nsec, + } +} + +/// Convert previous remaining `ITIMER_REAL` nanoseconds to POSIX `alarm(2)` return seconds. +/// Returns 0 if disarmed, otherwise rounds up to at least 1 second (POSIX). +#[inline] +pub(super) fn alarm_remaining_secs(remaining_ns: u64) -> usize { + if remaining_ns == 0 { + 0 + } else { + let secs = remaining_ns / 1_000_000_000; + let rem = remaining_ns % 1_000_000_000; + let rounded = if rem >= 500_000_000 { secs + 1 } else { secs }; + rounded.max(1) as usize + } +} + +/// sys_alarm - set a one-shot `SIGALRM` delivery timer in seconds (syscall 37, N2.6b). +pub(super) fn sys_alarm(seconds: u32) -> SyscallResult { + let tgid = current_tgid()?; + let value_ns = (seconds as u64).saturating_mul(1_000_000_000); + let (_prev_iv, prev_rem) = crate::time::set_real_itimer(tgid, 0, value_ns)?; + Ok(alarm_remaining_secs(prev_rem)) +} + +/// sys_getitimer - query an interval timer (syscall 36, N2.6b). +pub(super) fn sys_getitimer(which: i32, curr_value: *mut ITimerVal) -> SyscallResult { + if curr_value.is_null() { + return Err(SyscallError::EFAULT); + } + let (iv_ns, rem_ns) = match which { + ITIMER_REAL => { + let tgid = current_tgid()?; + crate::time::get_real_itimer(tgid) + } + ITIMER_VIRTUAL | ITIMER_PROF => (0, 0), + _ => return Err(SyscallError::EINVAL), + }; + let out = itimerval_from_ns(iv_ns, rem_ns); + // lint-repr-c-copy: allow (ITimerVal is 32B #[repr(C)] no padding; kernel→user) + let bytes = unsafe { + core::slice::from_raw_parts( + &out as *const ITimerVal as *const u8, + core::mem::size_of::(), + ) + }; + copy_to_user(curr_value as *mut u8, bytes)?; + Ok(0) +} + +/// sys_setitimer - arm/disarm an interval timer (syscall 38, N2.6b). +pub(super) fn sys_setitimer( + which: i32, + new_value: *const ITimerVal, + old_value: *mut ITimerVal, +) -> SyscallResult { + if !matches!(which, ITIMER_REAL | ITIMER_VIRTUAL | ITIMER_PROF) { + return Err(SyscallError::EINVAL); + } + if new_value.is_null() { + return Err(SyscallError::EFAULT); + } + let mut req = ITimerVal::default(); + // lint-repr-c-copy: allow (ITimerVal is 32B #[repr(C)] no padding; user→kernel) + let req_bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut req as *mut ITimerVal as *mut u8, + core::mem::size_of::(), + ) + }; + copy_from_user(req_bytes, new_value as *const u8)?; + let interval_ns = timeval_pair_to_ns(req.it_interval_sec, req.it_interval_usec)?; + let value_ns = timeval_pair_to_ns(req.it_value_sec, req.it_value_usec)?; + + if !old_value.is_null() { + verify_user_memory( + old_value as *const u8, + core::mem::size_of::(), + true, + )?; + } + + let (prev_iv, prev_rem) = match which { + ITIMER_REAL => { + let tgid = current_tgid()?; + crate::time::set_real_itimer(tgid, interval_ns, value_ns)? + } + ITIMER_VIRTUAL | ITIMER_PROF => { + if value_ns != 0 || interval_ns != 0 { + return Err(SyscallError::EOPNOTSUPP); + } + (0, 0) + } + _ => return Err(SyscallError::EINVAL), + }; + + if !old_value.is_null() { + let out = itimerval_from_ns(prev_iv, prev_rem); + // lint-repr-c-copy: allow (ITimerVal is 32B #[repr(C)] no padding; kernel→user) + let bytes = unsafe { + core::slice::from_raw_parts( + &out as *const ITimerVal as *const u8, + core::mem::size_of::(), + ) + }; + copy_to_user(old_value as *mut u8, bytes)?; + } + Ok(0) +} + +/// sys_timer_create - create a POSIX per-process timer (syscall 222, N2.6b). +pub(super) fn sys_timer_create( + clockid: i32, + sevp: *const SigEvent, + timerid_out: *mut i32, +) -> SyscallResult { + if timerid_out.is_null() { + return Err(SyscallError::EFAULT); + } + let clock = clockid_to_timer_clock(clockid)?; + verify_user_memory(timerid_out as *const u8, core::mem::size_of::(), true)?; + + let pid = current_pid().ok_or(SyscallError::ESRCH)?; + let (tgid, owning_ns) = { + let proc_arc = get_process(pid).ok_or(SyscallError::ESRCH)?; + let proc = proc_arc.lock(); + ( + proc.tgid, + crate::pid_namespace::owning_namespace(&proc.pid_ns_chain), + ) + }; + + let notify = if sevp.is_null() { + None + } else { + let mut ev = SigEvent::default(); + // lint-repr-c-copy: allow (SigEvent is 64B #[repr(C)] with explicit _pad; user→kernel) + let ev_bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut ev as *mut SigEvent as *mut u8, + core::mem::size_of::(), + ) + }; + copy_from_user(ev_bytes, sevp as *const u8)?; + match ev.sigev_notify { + SIGEV_NONE => Some(crate::time::PosixTimerNotify::None), + SIGEV_SIGNAL => { + let sig = crate::signal::Signal::from_raw(ev.sigev_signo) + .map_err(|_| SyscallError::EINVAL)?; + Some(crate::time::PosixTimerNotify::Signal { + sig, + sival: ev.sigev_value, + }) + } + SIGEV_THREAD_ID => { + if ev.sigev_notify_tid <= 0 { + return Err(SyscallError::EINVAL); + } + let sig = crate::signal::Signal::from_raw(ev.sigev_signo) + .map_err(|_| SyscallError::EINVAL)?; + let target_tid = match &owning_ns { + Some(ns) => crate::pid_namespace::resolve_pid_in_namespace( + ns, + ev.sigev_notify_tid as ProcessId, + ) + .ok_or(SyscallError::EINVAL)?, + None => ev.sigev_notify_tid as ProcessId, + }; + let target_arc = get_process(target_tid).ok_or(SyscallError::EINVAL)?; + if target_arc.lock().tgid != tgid { + return Err(SyscallError::EINVAL); + } + Some(crate::time::PosixTimerNotify::ThreadSignal { + tid: target_tid, + sig, + sival: ev.sigev_value, + }) + } + _ => return Err(SyscallError::EINVAL), + } + }; + + let id = crate::time::create_posix_timer(tgid, clock, notify)?; + if copy_to_user(timerid_out as *mut u8, &id.to_ne_bytes()).is_err() { + let _ = crate::time::delete_posix_timer(tgid, id); + return Err(SyscallError::EFAULT); + } + Ok(0) +} + +/// sys_timer_settime - arm/disarm a POSIX per-process timer (syscall 223, N2.6b). +pub(super) fn sys_timer_settime( + timerid: i32, + flags: i32, + new_value: *const ITimerSpec, + old_value: *mut ITimerSpec, +) -> SyscallResult { + if (flags & !TIMER_ABSTIME) != 0 { + return Err(SyscallError::EINVAL); + } + if new_value.is_null() { + return Err(SyscallError::EFAULT); + } + let mut req = ITimerSpec::default(); + // lint-repr-c-copy: allow (ITimerSpec is 32B #[repr(C)] no padding; user→kernel) + let req_bytes = unsafe { + core::slice::from_raw_parts_mut( + &mut req as *mut ITimerSpec as *mut u8, + core::mem::size_of::(), + ) + }; + copy_from_user(req_bytes, new_value as *const u8)?; + let interval_ns = timespec_to_ns(&TimeSpec { + tv_sec: req.it_interval_sec, + tv_nsec: req.it_interval_nsec, + })?; + let value_ns = timespec_to_ns(&TimeSpec { + tv_sec: req.it_value_sec, + tv_nsec: req.it_value_nsec, + })?; + + if !old_value.is_null() { + verify_user_memory( + old_value as *const u8, + core::mem::size_of::(), + true, + )?; + } + + let tgid = current_tgid()?; + let (prev_iv, prev_rem) = crate::time::settime_posix_timer( + tgid, + timerid, + (flags & TIMER_ABSTIME) != 0, + interval_ns, + value_ns, + )?; + + if !old_value.is_null() { + let out = itimerspec_from_ns(prev_iv, prev_rem); + // lint-repr-c-copy: allow (ITimerSpec is 32B #[repr(C)] no padding; kernel→user) + let bytes = unsafe { + core::slice::from_raw_parts( + &out as *const ITimerSpec as *const u8, + core::mem::size_of::(), + ) + }; + copy_to_user(old_value as *mut u8, bytes)?; + } + Ok(0) +} + +/// sys_timer_gettime - fetch remaining time of a POSIX timer (syscall 224, N2.6b). +pub(super) fn sys_timer_gettime(timerid: i32, curr_value: *mut ITimerSpec) -> SyscallResult { + if curr_value.is_null() { + return Err(SyscallError::EFAULT); + } + let tgid = current_tgid()?; + let (iv_ns, rem_ns) = crate::time::gettime_posix_timer(tgid, timerid)?; + let out = itimerspec_from_ns(iv_ns, rem_ns); + // lint-repr-c-copy: allow (ITimerSpec is 32B #[repr(C)] no padding; kernel→user) + let bytes = unsafe { + core::slice::from_raw_parts( + &out as *const ITimerSpec as *const u8, + core::mem::size_of::(), + ) + }; + copy_to_user(curr_value as *mut u8, bytes)?; + Ok(0) +} + +/// sys_timer_getoverrun - get overrun count for a POSIX timer (syscall 225, N2.6b). +pub(super) fn sys_timer_getoverrun(timerid: i32) -> SyscallResult { + let tgid = current_tgid()?; + let overrun = crate::time::getoverrun_posix_timer(tgid, timerid)?; + Ok(overrun as usize) +} + +/// sys_timer_delete - delete a POSIX per-process timer (syscall 226, N2.6b). +pub(super) fn sys_timer_delete(timerid: i32) -> SyscallResult { + let tgid = current_tgid()?; + crate::time::delete_posix_timer(tgid, timerid)?; + Ok(0) +} + /// M0 #2 self-test for the pure startup-ABI helpers — the wires a green /// build/boot can't catch (clock-id accept/reject set, ms→timespec/timeval /// boundary arithmetic, and the rt_sigprocmask Linux-semantics validator @@ -334,13 +820,13 @@ pub fn run_startup_abi_self_test() { ); } -/// sys_gettimeofday - 获取当前时间 +/// sys_gettimeofday - 获取当前墙钟时间 (N2.6b: CMOS RTC epoch + ns monotonic) pub(super) fn sys_gettimeofday(tv: *mut TimeVal, _tz: usize) -> SyscallResult { if tv.is_null() { return Err(SyscallError::EFAULT); } - let timeval = timeval_from_ms(crate::time::current_timestamp_ms()); + let timeval = timeval_from_ns(crate::time::realtime_ns()); // lint-repr-c-copy: allow (no-padding: TimeVal {i64,i64} = 16 bytes) let tv_bytes = unsafe { @@ -354,3 +840,157 @@ pub(super) fn sys_gettimeofday(tv: *mut TimeVal, _tz: usize) -> SyscallResult { Ok(0) } + +#[cfg(test)] +mod n2_6b_timer_tests { + use super::*; + use crate::time::{ + advance_expired_timer, cleanup_all_timers_for_process, cleanup_posix_timers_for_exec, + compute_timer_deadline_ns, create_posix_timer, delete_posix_timer, get_real_itimer, + getoverrun_posix_timer, gettime_posix_timer, set_real_itimer, settime_posix_timer, + PosixTimerNotify, TimerClock, MAX_POSIX_TIMERS_PER_PROCESS, + }; + + #[test] + fn n2_6b_nanosecond_conversions_and_alarm_rounding() { + let ts = timespec_from_ns(1_795_838_400_123_456_789); + assert_eq!(ts.tv_sec, 1_795_838_400); + assert_eq!(ts.tv_nsec, 123_456_789); + assert_eq!(timespec_to_ns(&ts), Ok(1_795_838_400_123_456_789)); + + let tv = timeval_from_ns(1_795_838_400_123_456_789); + assert_eq!(tv.tv_sec, 1_795_838_400); + assert_eq!(tv.tv_usec, 123_456); + assert_eq!(timeval_pair_to_ns(1, 500_000), Ok(1_500_000_000)); + assert_eq!(timeval_pair_to_ns(-1, 0), Err(SyscallError::EINVAL)); + assert_eq!(timeval_pair_to_ns(0, 1_000_000), Err(SyscallError::EINVAL)); + assert_eq!( + timespec_to_ns(&TimeSpec { + tv_sec: 0, + tv_nsec: 1_000_000_000 + }), + Err(SyscallError::EINVAL) + ); + + // POSIX alarm(2) rounding: 0 stays 0; nonzero sub-second rounds up to 1. + assert_eq!(alarm_remaining_secs(0), 0); + assert_eq!(alarm_remaining_secs(1), 1); + assert_eq!(alarm_remaining_secs(499_999_999), 1); + assert_eq!(alarm_remaining_secs(1_499_999_999), 1); + assert_eq!(alarm_remaining_secs(1_500_000_000), 2); + } + + #[test] + fn n2_6b_clock_resolution_and_abstime_deadline_math() { + assert_eq!(crate::time::clock_resolution_ns(true), 1_000_000); + assert!(crate::time::clock_resolution_ns(false) >= 1); + assert_eq!( + clockid_to_timer_clock(CLOCK_REALTIME), + Ok(TimerClock::Realtime) + ); + assert_eq!( + clockid_to_timer_clock(CLOCK_MONOTONIC), + Ok(TimerClock::Monotonic) + ); + assert_eq!( + clockid_to_timer_clock(CLOCK_BOOTTIME), + Ok(TimerClock::Boottime) + ); + assert_eq!(clockid_to_timer_clock(99), Err(SyscallError::EINVAL)); + + // Relative vs absolute deadline conversion on monotonic and realtime clocks. + let mono = 10_000_000_000u64; + let offset = 1_700_000_000_000_000_000u64; + assert_eq!( + compute_timer_deadline_ns(0, false, TimerClock::Monotonic, mono, offset), + None + ); + assert_eq!( + compute_timer_deadline_ns(500_000_000, false, TimerClock::Monotonic, mono, offset), + Some(mono + 500_000_000) + ); + assert_eq!( + compute_timer_deadline_ns( + offset + mono + 250_000_000, + true, + TimerClock::Realtime, + mono, + offset + ), + Some(mono + 250_000_000) + ); + } + + #[test] + fn n2_6b_real_itimer_and_overrun_advancement() { + let tgid = 910_001usize; + cleanup_all_timers_for_process(tgid); + assert_eq!(get_real_itimer(tgid), (0, 0)); + + // Arm periodic ITIMER_REAL: 500ms initial, 200ms interval. + let prev = set_real_itimer(tgid, 200_000_000, 500_000_000).unwrap(); + assert_eq!(prev, (0, 0)); + let (iv, rem) = get_real_itimer(tgid); + assert_eq!(iv, 200_000_000); + assert!(rem > 0 && rem <= 500_000_000); + + // Disarming returns previous interval + remaining and clears entry. + let (old_iv, old_rem) = set_real_itimer(tgid, 0, 0).unwrap(); + assert_eq!(old_iv, 200_000_000); + assert!(old_rem > 0); + assert_eq!(get_real_itimer(tgid), (0, 0)); + + // Overrun math: one-shot disarms with overrun 0; periodic computes missed intervals. + assert_eq!(advance_expired_timer(1_000, 0, 5_000), (None, 0)); + assert_eq!(advance_expired_timer(1_000, 100, 1_050), (Some(1_100), 0)); + assert_eq!(advance_expired_timer(1_000, 100, 1_350), (Some(1_400), 3)); + } + + #[test] + fn n2_6b_posix_timers_quota_lifecycle_and_exec_cleanup() { + let tgid = 910_002usize; + cleanup_all_timers_for_process(tgid); + + // Arm ITIMER_REAL alongside POSIX timers to verify exec preserves ITIMER_REAL + // while deleting POSIX timers (POSIX.1-2008). + set_real_itimer(tgid, 0, 5_000_000_000).unwrap(); + + let mut ids = [0i32; MAX_POSIX_TIMERS_PER_PROCESS]; + for slot in ids.iter_mut() { + *slot = create_posix_timer( + tgid, + TimerClock::Monotonic, + Some(PosixTimerNotify::Signal { + sig: crate::signal::Signal::from_raw(34).unwrap(), + sival: 0x1234, + }), + ) + .expect("within per-process quota"); + } + // Per-process cap enforced with EAGAIN. + assert_eq!( + create_posix_timer(tgid, TimerClock::Monotonic, None), + Err(SyscallError::EAGAIN) + ); + + // Arm, query, check overrun, and delete one timer. + let tid0 = ids[0]; + let old = settime_posix_timer(tgid, tid0, false, 100_000_000, 1_000_000_000).unwrap(); + assert_eq!(old, (0, 0)); + let (iv, rem) = gettime_posix_timer(tgid, tid0).unwrap(); + assert_eq!(iv, 100_000_000); + assert!(rem > 0 && rem <= 1_000_000_000); + assert_eq!(getoverrun_posix_timer(tgid, tid0), Ok(0)); + assert!(delete_posix_timer(tgid, tid0).is_ok()); + assert_eq!(gettime_posix_timer(tgid, tid0), Err(SyscallError::EINVAL)); + + // Exec cleanup deletes all remaining POSIX timers, keeps ITIMER_REAL. + cleanup_posix_timers_for_exec(tgid); + assert_eq!(gettime_posix_timer(tgid, ids[1]), Err(SyscallError::EINVAL)); + assert!(get_real_itimer(tgid).1 > 0); + + // Process exit cleanup removes ITIMER_REAL too. + cleanup_all_timers_for_process(tgid); + assert_eq!(get_real_itimer(tgid), (0, 0)); + } +} diff --git a/kernel/kernel_core/time.rs b/kernel/kernel_core/time.rs index 61bfcf2..e34091f 100644 --- a/kernel/kernel_core/time.rs +++ b/kernel/kernel_core/time.rs @@ -2,7 +2,9 @@ //! //! 提供基于时钟中断的时间戳支持 +use alloc::vec::Vec; use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use spin::{Mutex, Once}; /// 全局时钟计数器(每次时钟中断递增) static TICK_COUNT: AtomicU64 = AtomicU64::new(0); @@ -10,6 +12,31 @@ static TICK_COUNT: AtomicU64 = AtomicU64::new(0); /// 系统启动时间的 TSC 值(用于更精确的时间测量) static BOOT_TSC: AtomicU64 = AtomicU64::new(0); +/// N2.6b: Optional high-resolution monotonic nanosecond clock callback +/// (registered by `arch::hpet` when a 64-bit HPET counter is present). +type MonotonicNsProvider = fn() -> Option; +static MONOTONIC_NS_PROVIDER: Once = Once::new(); + +/// Effective high-resolution clock period in nanoseconds (defaults to 1 ms +/// PIT tick resolution until HPET registers its finer period). +static HIGHRES_RESOLUTION_NS: AtomicU64 = AtomicU64::new(1_000_000); + +/// Monotonicity floor: guarantees `monotonic_ns()` never regresses across CPUs +/// or across provider activation. +static LAST_MONOTONIC_NS: AtomicU64 = AtomicU64::new(0); + +/// N2.6b: Offset added to `monotonic_ns()` to produce Unix epoch nanoseconds +/// for `CLOCK_REALTIME` / `gettimeofday` (seeded from CMOS RTC at boot). +static WALL_CLOCK_OFFSET_NS: AtomicU64 = AtomicU64::new(0); + +/// N2.6b: Earliest armed process timer (ITIMER_REAL or POSIX timer) expiry in +/// monotonic nanoseconds (`u64::MAX` when no timers are armed). +static NEXT_TIMER_EXPIRY_NS: AtomicU64 = AtomicU64::new(u64::MAX); + +/// N2.6b: Set from `on_timer_tick()` when `monotonic_ns() >= NEXT_TIMER_EXPIRY_NS`; +/// drained in safe process context by `drain_deferred_process_timers()`. +static PROCESS_TIMER_DEFERRED: AtomicBool = AtomicBool::new(false); + /// Last TIME_WAIT sweep timestamp (ms) static LAST_TIME_WAIT_SWEEP: AtomicU64 = AtomicU64::new(0); @@ -57,6 +84,63 @@ pub fn init() { BOOT_TSC.store(tsc, Ordering::SeqCst); } +/// N2.6b: Register a lock-free high-resolution monotonic nanosecond clock source +/// (e.g. 64-bit HPET main counter) and its effective resolution in nanoseconds. +pub fn register_monotonic_ns_provider(provider: MonotonicNsProvider, resolution_ns: u64) { + let clamped_res = resolution_ns.max(1); + HIGHRES_RESOLUTION_NS.store(clamped_res, Ordering::Release); + MONOTONIC_NS_PROVIDER.call_once(|| provider); + // Advance floor so monotonic_ns() stays smooth after registration. + let _ = monotonic_ns(); +} + +/// N2.6b: Seed the wall-clock offset for `CLOCK_REALTIME` / `gettimeofday` +/// from the boot-time CMOS RTC reading (UTC Unix epoch seconds). +pub fn set_wall_clock_epoch_secs(unix_secs: u64) { + let epoch_ns = unix_secs.saturating_mul(1_000_000_000); + let mono = monotonic_ns(); + WALL_CLOCK_OFFSET_NS.store(epoch_ns.saturating_sub(mono), Ordering::Release); +} + +/// N2.6b: Current wall-clock offset (`realtime_ns - monotonic_ns`). +#[inline] +pub fn wall_clock_offset_ns() -> u64 { + WALL_CLOCK_OFFSET_NS.load(Ordering::Acquire) +} + +/// N2.6b: Current monotonic uptime in nanoseconds. +/// +/// Uses the registered 64-bit HPET provider when available, falling back to +/// `get_ticks() * 1_000_000`. Enforces strict cross-CPU monotonicity via +/// `fetch_max`. +#[inline] +pub fn monotonic_ns() -> u64 { + let raw = MONOTONIC_NS_PROVIDER + .get() + .and_then(|f| f()) + .unwrap_or_else(|| get_ticks().saturating_mul(1_000_000)); + let prev = LAST_MONOTONIC_NS.fetch_max(raw, Ordering::AcqRel); + raw.max(prev) +} + +/// N2.6b: Current wall-clock Unix epoch time in nanoseconds (`CLOCK_REALTIME`). +#[inline] +pub fn realtime_ns() -> u64 { + WALL_CLOCK_OFFSET_NS + .load(Ordering::Acquire) + .saturating_add(monotonic_ns()) +} + +/// N2.6b: Effective clock resolution in nanoseconds for `clock_getres(2)`. +#[inline] +pub fn clock_resolution_ns(coarse: bool) -> u64 { + if coarse { + 1_000_000 + } else { + HIGHRES_RESOLUTION_NS.load(Ordering::Acquire).max(1) + } +} + /// 时钟中断处理 - 递增时钟计数器 /// /// 应由定时器中断处理程序调用 @@ -64,6 +148,14 @@ pub fn init() { pub fn on_timer_tick() { let current = TICK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; // lint-fetch-add: allow (monotonic counter) + // N2.6b: Lock-free single-load check for expired process itimers / POSIX timers. + // Delivery runs in safe process context via `drain_deferred_process_timers()`. + let next_exp = NEXT_TIMER_EXPIRY_NS.load(Ordering::Acquire); + if next_exp != u64::MAX && monotonic_ns() >= next_exp { + PROCESS_TIMER_DEFERRED.store(true, Ordering::Release); + crate::request_resched_from_irq(); + } + // R53-3 FIX: Drive TCP timers at two frequencies: // - Fast timer (200ms): Data/FIN retransmission checks // - Slow timer (1s): TIME_WAIT cleanup @@ -258,3 +350,496 @@ pub fn drain_deferred_tcp_timers() { pub fn poll_net_rx_ingress() { let _ = net::rx_ingress_poll_throttled(current_timestamp_ms()); } + +// ============================================================================ +// N2.6b: Bounded Process Interval Timers (`ITIMER_REAL`/`alarm`) & POSIX Timers +// ============================================================================ +// +// Stored out-of-line in a global lock-protected registry keyed by `tgid` so +// `Process` and `ThreadGroup` incur ZERO per-PCB memory overhead. IRQ context +// never acquires `TIMER_REGISTRY`; it only reads `NEXT_TIMER_EXPIRY_NS` and +// sets `PROCESS_TIMER_DEFERRED` for process-context delivery. + +/// Maximum number of active POSIX `timer_create` timers per process (thread group). +pub const MAX_POSIX_TIMERS_PER_PROCESS: usize = 32; +/// Global safety cap on `ITIMER_REAL` entries to prevent unbounded kernel heap growth. +const MAX_GLOBAL_ITIMERS: usize = 512; +/// Maximum expired timers dispatched per single deferred-drain pass (stack-allocated). +const TIMER_DRAIN_BATCH: usize = 16; + +/// How a POSIX timer notifies its owning process/thread on expiry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PosixTimerNotify { + /// `SIGEV_NONE`: record expiry/overrun without sending a signal. + None, + /// `SIGEV_SIGNAL`: process-directed signal to `tgid`. + Signal { + sig: crate::signal::Signal, + sival: u64, + }, + /// `SIGEV_THREAD_ID`: thread-directed signal to specific `tid` in `tgid`. + ThreadSignal { + tid: crate::process::ProcessId, + sig: crate::signal::Signal, + sival: u64, + }, +} + +/// Clock base recorded for a POSIX timer (`timer_create`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimerClock { + Realtime, + Monotonic, + Boottime, +} + +#[derive(Debug, Clone, Copy)] +struct RealITimerEntry { + tgid: crate::process::ProcessId, + /// Armed monotonic deadline in ns (`None` when disarmed). + expiry_ns: Option, + /// Periodic reload interval in ns (`0` for one-shot). + interval_ns: u64, +} + +#[derive(Debug, Clone, Copy)] +struct PosixTimerEntry { + tgid: crate::process::ProcessId, + timer_id: i32, + clock: TimerClock, + notify: PosixTimerNotify, + /// Armed monotonic deadline in ns (`None` when disarmed). + expiry_ns: Option, + /// Periodic reload interval in ns (`0` for one-shot). + interval_ns: u64, + /// Overrun count from the most recent expiration. + overrun: i32, +} + +#[derive(Debug, Clone, Copy)] +enum TimerFireEvent { + Process { + tgid: crate::process::ProcessId, + sig: crate::signal::Signal, + info: crate::signal::SigInfo, + }, + Thread { + tid: crate::process::ProcessId, + sig: crate::signal::Signal, + info: crate::signal::SigInfo, + }, +} + +struct TimerRegistry { + itimers: Vec, + posix: Vec, + next_timer_id: i32, +} + +impl TimerRegistry { + const fn new() -> Self { + Self { + itimers: Vec::new(), + posix: Vec::new(), + next_timer_id: 1, + } + } + + fn recompute_next_expiry(&self) -> u64 { + let mut min_ns = u64::MAX; + for t in &self.itimers { + if let Some(exp) = t.expiry_ns { + if exp < min_ns { + min_ns = exp; + } + } + } + for t in &self.posix { + if let Some(exp) = t.expiry_ns { + if exp < min_ns { + min_ns = exp; + } + } + } + min_ns + } + + fn publish_next_expiry(&self) { + let min_ns = self.recompute_next_expiry(); + NEXT_TIMER_EXPIRY_NS.store(min_ns, Ordering::Release); + if min_ns != u64::MAX && monotonic_ns() >= min_ns { + PROCESS_TIMER_DEFERRED.store(true, Ordering::Release); + } + } +} + +static TIMER_REGISTRY: Mutex = Mutex::new(TimerRegistry::new()); + +/// Compute `(interval_ns, remaining_ns)` for a timer at monotonic time `now_ns`. +#[inline] +fn remaining_pair(expiry_ns: Option, interval_ns: u64, now_ns: u64) -> (u64, u64) { + match expiry_ns { + Some(exp) => (interval_ns, exp.saturating_sub(now_ns).max(1)), + None => (interval_ns, 0), + } +} + +/// Convert a `(value_ns, interval_ns, abstime, clock)` request into an armed +/// monotonic deadline (`None` when `value_ns == 0`). +#[inline] +pub(crate) fn compute_timer_deadline_ns( + value_ns: u64, + abstime: bool, + clock: TimerClock, + now_mono_ns: u64, + wall_offset_ns: u64, +) -> Option { + if value_ns == 0 { + return None; + } + if abstime { + let target_mono = match clock { + TimerClock::Realtime => value_ns.saturating_sub(wall_offset_ns), + TimerClock::Monotonic | TimerClock::Boottime => value_ns, + }; + Some(target_mono) + } else { + Some(now_mono_ns.saturating_add(value_ns)) + } +} + +/// Read the current `ITIMER_REAL` `(interval_ns, remaining_ns)` for `tgid`. +pub(crate) fn get_real_itimer(tgid: crate::process::ProcessId) -> (u64, u64) { + let now = monotonic_ns(); + let reg = TIMER_REGISTRY.lock(); + match reg.itimers.iter().find(|e| e.tgid == tgid) { + Some(e) => remaining_pair(e.expiry_ns, e.interval_ns, now), + None => (0, 0), + } +} + +/// Set `ITIMER_REAL` for `tgid` to `(interval_ns, value_ns)` (`value_ns == 0` disarms). +/// Returns the previous `(interval_ns, remaining_ns)`. +pub(crate) fn set_real_itimer( + tgid: crate::process::ProcessId, + interval_ns: u64, + value_ns: u64, +) -> Result<(u64, u64), crate::syscall::SyscallError> { + let now = monotonic_ns(); + let new_expiry = if value_ns == 0 { + None + } else { + Some(now.saturating_add(value_ns)) + }; + let mut reg = TIMER_REGISTRY.lock(); + let prev = if let Some(pos) = reg.itimers.iter().position(|e| e.tgid == tgid) { + let old = remaining_pair( + reg.itimers[pos].expiry_ns, + reg.itimers[pos].interval_ns, + now, + ); + if new_expiry.is_none() { + reg.itimers.swap_remove(pos); + } else { + reg.itimers[pos].expiry_ns = new_expiry; + reg.itimers[pos].interval_ns = interval_ns; + } + old + } else { + if let Some(exp) = new_expiry { + if reg.itimers.len() >= MAX_GLOBAL_ITIMERS { + return Err(crate::syscall::SyscallError::ENOMEM); + } + reg.itimers + .try_reserve(1) + .map_err(|_| crate::syscall::SyscallError::ENOMEM)?; + reg.itimers.push(RealITimerEntry { + tgid, + expiry_ns: Some(exp), + interval_ns, + }); + } + (0, 0) + }; + reg.publish_next_expiry(); + Ok(prev) +} + +/// Create a POSIX per-process timer owned by `tgid` and return its `timer_id`. +pub(crate) fn create_posix_timer( + tgid: crate::process::ProcessId, + clock: TimerClock, + notify_opt: Option, +) -> Result { + let mut reg = TIMER_REGISTRY.lock(); + let owned = reg.posix.iter().filter(|e| e.tgid == tgid).count(); + if owned >= MAX_POSIX_TIMERS_PER_PROCESS { + return Err(crate::syscall::SyscallError::EAGAIN); + } + reg.posix + .try_reserve(1) + .map_err(|_| crate::syscall::SyscallError::ENOMEM)?; + + // Allocate a unique positive timer_id not currently held by `tgid`. + let mut id = reg.next_timer_id.max(1); + while reg.posix.iter().any(|e| e.tgid == tgid && e.timer_id == id) { + id = id.checked_add(1).unwrap_or(1); + } + reg.next_timer_id = id.checked_add(1).unwrap_or(1); + + let notify = notify_opt.unwrap_or(PosixTimerNotify::Signal { + sig: crate::signal::Signal::SIGALRM, + sival: id as u64, + }); + reg.posix.push(PosixTimerEntry { + tgid, + timer_id: id, + clock, + notify, + expiry_ns: None, + interval_ns: 0, + overrun: 0, + }); + Ok(id) +} + +/// Arm or disarm a POSIX timer owned by `tgid`. Returns previous `(interval_ns, remaining_ns)`. +pub(crate) fn settime_posix_timer( + tgid: crate::process::ProcessId, + timer_id: i32, + abstime: bool, + interval_ns: u64, + value_ns: u64, +) -> Result<(u64, u64), crate::syscall::SyscallError> { + let now = monotonic_ns(); + let offset = wall_clock_offset_ns(); + let mut reg = TIMER_REGISTRY.lock(); + let entry = reg + .posix + .iter_mut() + .find(|e| e.tgid == tgid && e.timer_id == timer_id) + .ok_or(crate::syscall::SyscallError::EINVAL)?; + let prev = remaining_pair(entry.expiry_ns, entry.interval_ns, now); + entry.expiry_ns = compute_timer_deadline_ns(value_ns, abstime, entry.clock, now, offset); + entry.interval_ns = if entry.expiry_ns.is_some() { + interval_ns + } else { + 0 + }; + entry.overrun = 0; + reg.publish_next_expiry(); + Ok(prev) +} + +/// Query `(interval_ns, remaining_ns)` of a POSIX timer owned by `tgid`. +pub(crate) fn gettime_posix_timer( + tgid: crate::process::ProcessId, + timer_id: i32, +) -> Result<(u64, u64), crate::syscall::SyscallError> { + let now = monotonic_ns(); + let reg = TIMER_REGISTRY.lock(); + let entry = reg + .posix + .iter() + .find(|e| e.tgid == tgid && e.timer_id == timer_id) + .ok_or(crate::syscall::SyscallError::EINVAL)?; + Ok(remaining_pair(entry.expiry_ns, entry.interval_ns, now)) +} + +/// Query the overrun count of a POSIX timer owned by `tgid`. +pub(crate) fn getoverrun_posix_timer( + tgid: crate::process::ProcessId, + timer_id: i32, +) -> Result { + let reg = TIMER_REGISTRY.lock(); + let entry = reg + .posix + .iter() + .find(|e| e.tgid == tgid && e.timer_id == timer_id) + .ok_or(crate::syscall::SyscallError::EINVAL)?; + Ok(entry.overrun) +} + +/// Delete a POSIX timer owned by `tgid`. +pub(crate) fn delete_posix_timer( + tgid: crate::process::ProcessId, + timer_id: i32, +) -> Result<(), crate::syscall::SyscallError> { + let mut reg = TIMER_REGISTRY.lock(); + let pos = reg + .posix + .iter() + .position(|e| e.tgid == tgid && e.timer_id == timer_id) + .ok_or(crate::syscall::SyscallError::EINVAL)?; + reg.posix.swap_remove(pos); + reg.publish_next_expiry(); + Ok(()) +} + +/// POSIX `execve(2)`: delete all POSIX `timer_create` timers owned by `tgid` +/// while preserving `ITIMER_REAL` (`alarm`/`setitimer`). +pub(crate) fn cleanup_posix_timers_for_exec(tgid: crate::process::ProcessId) { + let mut reg = TIMER_REGISTRY.lock(); + let before = reg.posix.len(); + reg.posix.retain(|e| e.tgid != tgid); + if reg.posix.len() != before { + reg.publish_next_expiry(); + } +} + +/// Process exit (last live thread of `tgid`): reclaim both `ITIMER_REAL` and +/// all POSIX timers owned by `tgid`. +pub(crate) fn cleanup_all_timers_for_process(tgid: crate::process::ProcessId) { + let mut reg = TIMER_REGISTRY.lock(); + let before_i = reg.itimers.len(); + let before_p = reg.posix.len(); + reg.itimers.retain(|e| e.tgid != tgid); + reg.posix.retain(|e| e.tgid != tgid); + if reg.itimers.len() != before_i || reg.posix.len() != before_p { + reg.publish_next_expiry(); + } +} + +/// Advance a single expired timer entry at `now_ns`, returning `(next_expiry, overrun)`. +#[inline] +pub(crate) fn advance_expired_timer( + expiry_ns: u64, + interval_ns: u64, + now_ns: u64, +) -> (Option, i32) { + if interval_ns == 0 { + (None, 0) + } else { + let elapsed = now_ns.saturating_sub(expiry_ns); + let missed = elapsed / interval_ns; + let overrun = missed.min(i32::MAX as u64) as i32; + let next = expiry_ns.saturating_add(missed.saturating_add(1).saturating_mul(interval_ns)); + (Some(next), overrun) + } +} + +/// Process-context drain of expired `ITIMER_REAL` and POSIX timers. +/// +/// Called from `scheduler_hook::process_deferred_work()` right next to +/// `drain_deferred_tcp_timers()`. Never allocates on the heap and always drops +/// `TIMER_REGISTRY` before delivering signals. +pub fn drain_deferred_process_timers() { + if !PROCESS_TIMER_DEFERRED.swap(false, Ordering::AcqRel) { + return; + } + let now = monotonic_ns(); + let mut batch: [Option; TIMER_DRAIN_BATCH] = [None; TIMER_DRAIN_BATCH]; + let mut count = 0usize; + let mut more_pending = false; + + { + let mut reg = TIMER_REGISTRY.lock(); + + // 1. Scan ITIMER_REAL entries (removing disarmed one-shots). + let mut idx = 0usize; + while idx < reg.itimers.len() { + let Some(exp) = reg.itimers[idx].expiry_ns else { + reg.itimers.swap_remove(idx); + continue; + }; + if now < exp { + idx += 1; + continue; + } + if count >= TIMER_DRAIN_BATCH { + more_pending = true; + break; + } + let tgid = reg.itimers[idx].tgid; + let interval_ns = reg.itimers[idx].interval_ns; + let (next_exp, _overrun) = advance_expired_timer(exp, interval_ns, now); + batch[count] = Some(TimerFireEvent::Process { + tgid, + sig: crate::signal::Signal::SIGALRM, + info: crate::signal::SigInfo::from_sender( + crate::signal::Signal::SIGALRM, + crate::signal::SI_KERNEL, + 0, + 0, + ), + }); + count += 1; + if let Some(next) = next_exp { + reg.itimers[idx].expiry_ns = Some(next); + idx += 1; + } else { + reg.itimers.swap_remove(idx); + } + } + + // 2. Scan POSIX timers. + for t in reg.posix.iter_mut() { + let Some(exp) = t.expiry_ns else { + continue; + }; + if now < exp { + continue; + } + if count >= TIMER_DRAIN_BATCH { + more_pending = true; + break; + } + let (next_exp, overrun) = advance_expired_timer(exp, t.interval_ns, now); + t.expiry_ns = next_exp; + t.overrun = overrun; + match t.notify { + PosixTimerNotify::None => {} + PosixTimerNotify::Signal { sig, sival } => { + batch[count] = Some(TimerFireEvent::Process { + tgid: t.tgid, + sig, + info: crate::signal::SigInfo { + signo: sig.as_i32(), + errno: 0, + code: crate::signal::SI_TIMER, + pid: t.timer_id, + uid: overrun as u32, + value: sival, + }, + }); + count += 1; + } + PosixTimerNotify::ThreadSignal { tid, sig, sival } => { + batch[count] = Some(TimerFireEvent::Thread { + tid, + sig, + info: crate::signal::SigInfo { + signo: sig.as_i32(), + errno: 0, + code: crate::signal::SI_TIMER, + pid: t.timer_id, + uid: overrun as u32, + value: sival, + }, + }); + count += 1; + } + } + } + + let min_ns = reg.recompute_next_expiry(); + NEXT_TIMER_EXPIRY_NS.store(min_ns, Ordering::Release); + if more_pending { + PROCESS_TIMER_DEFERRED.store(true, Ordering::Release); + } + } + + // Deliver all due signals outside `TIMER_REGISTRY`. + for slot in batch.iter().take(count) { + if let Some(event) = *slot { + match event { + TimerFireEvent::Process { tgid, sig, info } => { + let _ = crate::signal::send_signal_kernel_with_info(tgid, sig, info); + } + TimerFireEvent::Thread { tid, sig, info } => { + let _ = crate::signal::send_signal_kernel_thread_with_info(tid, sig, info); + } + } + } + } +} diff --git a/kernel/seccomp/syscall_table.rs b/kernel/seccomp/syscall_table.rs index aaad86b..900df13 100644 --- a/kernel/seccomp/syscall_table.rs +++ b/kernel/seccomp/syscall_table.rs @@ -280,6 +280,10 @@ define_syscall_table! { (32, SYS_DUP, Dup, "dup", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (33, SYS_DUP2, Dup2, "dup2", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (35, SYS_NANOSLEEP, Nanosleep, "nanosleep", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + // Interval timers & alarm (N2.6b) + (36, SYS_GETITIMER, Getitimer, "getitimer", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (37, SYS_ALARM, Alarm, "alarm", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (38, SYS_SETITIMER, Setitimer, "setitimer", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (39, SYS_GETPID, Getpid, "getpid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_STDIO), reason: ""), // Sockets (Linux x86_64 ABI) (41, SYS_SOCKET, Socket, "socket", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), @@ -354,7 +358,15 @@ define_syscall_table! { (204, SYS_SCHED_GETAFFINITY, SchedGetaffinity, "sched_getaffinity", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (217, SYS_GETDENTS64, Getdents64, "getdents64", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_RPATH), reason: ""), (218, SYS_SET_TID_ADDRESS, SetTidAddress, "set_tid_address", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_THREAD), reason: ""), + // POSIX timers & clocks (N2.6b) + (222, SYS_TIMER_CREATE, TimerCreate, "timer_create", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (223, SYS_TIMER_SETTIME, TimerSettime, "timer_settime", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (224, SYS_TIMER_GETTIME, TimerGettime, "timer_gettime", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (225, SYS_TIMER_GETOVERRUN, TimerGetoverrun, "timer_getoverrun", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), + (226, SYS_TIMER_DELETE, TimerDelete, "timer_delete", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (228, SYS_CLOCK_GETTIME, ClockGettime, "clock_gettime", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_TIME), reason: ""), + (229, SYS_CLOCK_GETRES, ClockGetres, "clock_getres", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_TIME), reason: ""), + (230, SYS_CLOCK_NANOSLEEP, ClockNanosleep, "clock_nanosleep", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (231, SYS_EXIT_GROUP, ExitGroup, "exit_group", strict: true, drop_proc: true, status: Dispatched, pledge: PledgePolicy::Always, reason: ""), (234, SYS_TGKILL, Tgkill, "tgkill", strict: false, drop_proc: true, status: Dispatched, pledge: PledgePolicy::Unpledged, reason: ""), (247, SYS_WAITID, Waitid, "waitid", strict: false, drop_proc: false, status: Dispatched, pledge: PledgePolicy::Promises(P_PROC), reason: ""), diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 93ca91a..a463d4b 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -914,6 +914,12 @@ extern "C" fn kernel_main(boot_info_ptr: u64) -> ! { info.comparator_count, info.counter_64bit ); + if let Some(res_ns) = arch::hpet::resolution_ns() { + kernel_core::time::register_monotonic_ns_provider( + arch::hpet::elapsed_ns, + res_ns, + ); + } } Err(e) => { klog_always!( @@ -922,6 +928,14 @@ extern "C" fn kernel_main(boot_info_ptr: u64) -> ! { ); } } + // N2.6b: Seed CLOCK_REALTIME wall-clock offset from MC146818 CMOS RTC. + if let Some(epoch_secs) = arch::hpet::read_cmos_rtc_unix_secs() { + kernel_core::time::set_wall_clock_epoch_secs(epoch_secs); + klog_always!( + " ✓ CMOS RTC wall clock seeded (epoch={} s)", + epoch_secs + ); + } // Calibrate LAPIC timer using HPET (preferred) or PIT channel 2 as reference // This determines the correct initial count for ~1kHz ticks diff --git a/scripts/tools/abi_layout_oracle.py b/scripts/tools/abi_layout_oracle.py index 975286c..be40449 100644 --- a/scripts/tools/abi_layout_oracle.py +++ b/scripts/tools/abi_layout_oracle.py @@ -417,6 +417,31 @@ def _sub_sizeof(m): c_type="stack_t", c_include="signal.h", c_fields=[("ss_sp", 0), ("ss_flags", 8), ("ss_size", 16)], ), + "ITimerVal": dict( + src="syscall_abi", layer=LINUX_UAPI, + cite="uapi/linux/time.h struct itimerval (x86-64, 32B)", + fields=[("it_interval_sec", 0, 8), ("it_interval_usec", 8, 8), + ("it_value_sec", 16, 8), ("it_value_usec", 24, 8)], size=32, + c_type="struct itimerval", c_include="sys/time.h", + c_fields=[("it_interval", 0), ("it_value", 16)], + ), + "ITimerSpec": dict( + src="syscall_abi", layer=LINUX_UAPI, + cite="uapi/linux/time.h struct itimerspec (x86-64, 32B)", + fields=[("it_interval_sec", 0, 8), ("it_interval_nsec", 8, 8), + ("it_value_sec", 16, 8), ("it_value_nsec", 24, 8)], size=32, + c_type="struct itimerspec", c_include="time.h", + c_fields=[("it_interval", 0), ("it_value", 16)], + ), + "SigEvent": dict( + src="syscall_abi", layer=LINUX_UAPI, + cite="uapi/asm-generic/siginfo.h struct sigevent (x86-64, 64B)", + fields=[("sigev_value", 0, 8), ("sigev_signo", 8, 4), + ("sigev_notify", 12, 4), ("sigev_notify_tid", 16, 4), + ("_pad", 20, 44)], size=64, + c_type="struct sigevent", c_include="signal.h", + c_fields=[("sigev_value", 0), ("sigev_signo", 8), ("sigev_notify", 12)], + ), "VfsStat": dict( # D2-ABI-STAT-LAYOUT RESOLVED (2026-07-24): converted from the former # 112-byte private layout to the Linux x86-64 struct stat wire layout. diff --git a/scripts/tools/hosted_subcrate_tests.sh b/scripts/tools/hosted_subcrate_tests.sh index 3a1e0e5..f47ecfa 100755 --- a/scripts/tools/hosted_subcrate_tests.sh +++ b/scripts/tools/hosted_subcrate_tests.sh @@ -246,14 +246,14 @@ run_suite cgroup-access 1 0 \ # Includes the C3 aligned TID store and concurrent word tests, the C3 # work-stealing hint with its model, and P2 wake-affine / placement / voluntary-yield policy tests. -run_suite kernel-core 227 0 \ +run_suite kernel-core 231 0 \ --manifest-path kernel/kernel_core/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features host_harness \ --lib --locked -# Includes SMP AP trampoline GDT/CR4/CR3/page-separation invariants, x2APIC helpers, and syscall frame layout tests. -run_suite arch 9 0 \ +# Includes SMP AP trampoline GDT/CR4/CR3/page-separation invariants, x2APIC helpers, syscall frame layout, and CMOS RTC tests. +run_suite arch 11 0 \ --manifest-path kernel/arch/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features mm/host_harness \ @@ -292,7 +292,7 @@ run_suite security-wxorx 6 14 \ --features mm/host_harness,cpu_local/host_harness \ --lib --locked -- wxorx::tests -run_suite mitigation-mappings 5 227 \ +run_suite mitigation-mappings 5 231 \ --manifest-path kernel/kernel_core/Cargo.toml \ --target x86_64-unknown-linux-gnu \ --features host_harness,mitigation_probe \