use std::collections::BTreeMap;
use std::collections::BTreeSet;
use nix::sys::signal::Signal;
use tracing::info;
use super::Scheduler;
use super::ThreadStatus;
use crate::ivar::Ivar;
use crate::resources::PAUSE_FYI;
use crate::resources::Permission;
use crate::resources::ResourceID;
use crate::resources::Resources;
use crate::tool_global::SigalrmControl;
use crate::types::DetPid;
use crate::types::DetTid;
use crate::types::SigWrapper;
#[derive(Debug, Default)]
pub(crate) struct SigalrmLedger {
handled: BTreeSet<DetPid>,
pending: BTreeSet<DetPid>,
blocked: BTreeMap<DetTid, bool>,
polling: BTreeSet<DetTid>,
lost: BTreeSet<DetPid>,
producer_armed: bool,
}
impl Scheduler {
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn sigalrm_handled(&self, process: DetPid) -> bool {
self.sigalrm.handled.contains(&process)
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn sigalrm_pending(&self, process: DetPid) -> bool {
self.sigalrm.pending.contains(&process)
}
pub(crate) fn set_sigalrm_handled(&mut self, process: DetPid, handled: bool) {
if handled {
self.sigalrm.handled.insert(process);
} else {
self.sigalrm.handled.remove(&process);
self.sigalrm.pending.remove(&process);
self.sigalrm.lost.remove(&process);
}
}
pub(crate) fn sigalrm_control(&mut self, thread: DetTid, control: SigalrmControl) -> bool {
let process = self.sigchld_process(thread);
match control {
SigalrmControl::Publish { handled, blocked } => {
self.set_sigalrm_handled(process, handled);
self.set_sigalrm_blocked(thread, blocked);
return false;
}
SigalrmControl::PublishBlocked(blocked) => {
self.set_sigalrm_blocked(thread, blocked);
return false;
}
SigalrmControl::DeliveryLost => {
crate::detlog::write_loss_notice(&format!(
"thread {thread} of process {process} took a pending guest-handled SIGALRM, but the runtime could not deliver it"
));
self.sigalrm.lost.insert(process);
return false;
}
SigalrmControl::EntryDeliveryUnfaithful => {
crate::detlog::write_loss_notice(&format!(
"thread {thread} of process {process} delivers a guest-handled SIGALRM before a syscall that has not run; its handler cannot see the registers Linux would show it (rcx and r11 as the syscall instruction left them)"
));
self.sigalrm.lost.insert(process);
return false;
}
_ => {}
}
if !self.sigalrm.handled.is_empty() && !self.holds_serial_grant(thread) {
return true;
}
match control {
SigalrmControl::InstallHandler => {
let recurring = self
.blocked
.timed_waiters
.alarm_state(process)
.is_some_and(|(_, interval)| interval != crate::types::LogicalTime::ZERO);
let refused = self.sigalrm_producer_armed() || recurring;
if refused {
info!(
"[dtid {}] SIGALRM handler refused: a guest armed a kernel producer of SIGALRM, or its process has a recurring ITIMER_REAL (signal phase 1).",
thread
);
}
return refused;
}
SigalrmControl::HandlerToDefault | SigalrmControl::PendingEntry => {
return self.sigalrm.pending.contains(&process);
}
SigalrmControl::DueEntry => return self.sigalrm_due(thread),
SigalrmControl::TakeEntry => {
let taken = self.take_sigalrm(process, thread);
if taken {
info!(
"[dtid {}] takes its process's pending SIGALRM for delivery to its handler.",
thread
);
}
return taken;
}
_ => {}
}
if self.sigalrm.handled.is_empty() {
if control == SigalrmControl::ArmProducer {
self.sigalrm.producer_armed = true;
}
return false;
}
if !self.holds_serial_grant(thread) {
return true;
}
if control == SigalrmControl::UnadmittedStdioIo {
if self.sigalrm_due(thread) {
self.record_sigalrm_loss(
DetPid::from_raw(thread.as_raw()),
thread,
"a due SIGALRM found it entering I/O on inherited stdio that may sleep unadmitted",
);
}
return false;
}
let refused = match control {
SigalrmControl::SendTo(target) => {
self.sigalrm.handled.contains(&self.sigchld_process(target))
}
SigalrmControl::SendToUnnamed | SigalrmControl::ArmProducer => true,
SigalrmControl::UnadmittedStdioIo
| SigalrmControl::InstallHandler
| SigalrmControl::HandlerToDefault
| SigalrmControl::PendingEntry
| SigalrmControl::Publish { .. }
| SigalrmControl::PublishBlocked(_)
| SigalrmControl::DueEntry
| SigalrmControl::TakeEntry
| SigalrmControl::DeliveryLost
| SigalrmControl::EntryDeliveryUnfaithful => unreachable!("answered above"),
SigalrmControl::ArmRecurringTimer => {
self.sigalrm.handled.contains(&self.sigchld_process(thread))
}
};
if refused {
info!(
"[dtid {}] {:?} refused: a guest handles SIGALRM (signal phase 1).",
thread, control
);
}
refused
}
pub(crate) fn sigalrm_producer_armed(&self) -> bool {
self.sigalrm.producer_armed
}
pub(crate) fn set_sigalrm_blocked(&mut self, thread: DetTid, blocked: bool) {
self.sigalrm.blocked.insert(thread, blocked);
}
pub(crate) fn note_sigalrm_polling_wait(&mut self, thread: DetTid, request: &Resources) {
if Self::is_polling_retry(request) {
self.sigalrm.polling.insert(thread);
}
}
pub(crate) fn end_sigalrm_polling_wait(&mut self, thread: DetTid) {
self.sigalrm.polling.remove(&thread);
}
fn is_polling_retry(request: &Resources) -> bool {
request.poll_attempt > 0
&& request
.resources
.contains_key(&ResourceID::InternalIOPolling)
}
pub(super) fn in_polling_wait(&self, thread: DetTid) -> bool {
self.sigalrm.polling.contains(&thread)
|| self
.next_turns
.get(&thread)
.and_then(|turn| turn.req.try_read())
.is_some_and(|request| request.is_ok_and(|r| Self::is_polling_retry(&r)))
}
pub(crate) fn divert_sigalrm(&mut self, process: DetPid, signal: Signal) -> bool {
if signal != Signal::SIGALRM || !self.sigalrm.handled.contains(&process) {
return false;
}
if self.sigalrm.pending.insert(process) {
info!(
"[dpid {}] SIGALRM expired; a guest handler is installed, so it is pending in the ledger.",
process
);
} else {
info!(
"[dpid {}] SIGALRM expired while one was already pending; coalesced.",
process
);
}
self.act_on_pending_sigalrm(process);
true
}
pub(crate) fn step2_sigalrm_ledger(&mut self) {
let pending: Vec<DetPid> = self.sigalrm.pending.iter().copied().collect();
for process in pending {
self.act_on_pending_sigalrm(process);
}
}
pub(crate) fn admit_pause_with_due_sigalrm(&mut self, thread: DetTid) -> bool {
if !self.sigalrm_due(thread) || !self.filed_pause(thread) {
return false;
}
info!(
"[dtid {}] pause admitted with a due SIGALRM; it returns at once.",
thread
);
let wake = Self::sigalrm_wake(thread);
if let Some(turn) = self.next_turns.get_mut(&thread) {
turn.req = Ivar::full(Ok(wake));
}
true
}
pub(crate) fn take_sigalrm(&mut self, process: DetPid, thread: DetTid) -> bool {
if !self.sigalrm.handled.contains(&process)
|| self.sigalrm.blocked.get(&thread) != Some(&false)
|| !self.sigalrm.pending.remove(&process)
{
return false;
}
self.sigalrm.lost.remove(&process);
true
}
pub(crate) fn retire_sigalrm_thread(&mut self, thread: DetTid, process: DetPid) {
self.sigalrm.blocked.remove(&thread);
self.sigalrm.polling.remove(&thread);
if thread.as_raw() == process.as_raw() {
self.sigalrm.handled.remove(&process);
self.sigalrm.pending.remove(&process);
self.sigalrm.lost.remove(&process);
}
}
fn act_on_pending_sigalrm(&mut self, process: DetPid) {
let thread = Self::sigalrm_owner(process);
if !self.next_turns.contains_key(&thread) {
self.sigalrm.pending.remove(&process);
self.sigalrm.lost.remove(&process);
return;
}
match self.sigalrm.blocked.get(&thread) {
Some(true) => return,
Some(false) => {}
None => {
self.record_sigalrm_loss(process, thread, "its SIGALRM eligibility is unknown");
return;
}
}
if !matches!(self.thread_status(thread), ThreadStatus::NotRunning) {
if self.in_polling_wait(thread) {
self.record_sigalrm_loss(
process,
thread,
"a due SIGALRM found it in a polling wait that phase 1 cannot interrupt",
);
}
return;
}
if self.filed_pause(thread) {
info!("[dtid {}] a pending SIGALRM wakes its pause.", thread);
self.force_unblock_thread(thread, Self::sigalrm_wake(thread));
} else {
self.record_sigalrm_loss(
process,
thread,
"a due SIGALRM found it blocked in a wait that phase 1 cannot interrupt",
);
}
}
fn sigalrm_owner(process: DetPid) -> DetTid {
DetTid::from_raw(process.as_raw())
}
fn sigalrm_due(&self, thread: DetTid) -> bool {
let process = DetPid::from_raw(thread.as_raw());
self.sigalrm.handled.contains(&process)
&& self.sigalrm.pending.contains(&process)
&& self.sigalrm.blocked.get(&thread) == Some(&false)
}
fn sigalrm_wake(thread: DetTid) -> Resources {
let mut wake = Resources::new(thread);
wake.insert(
ResourceID::InboundSignal(SigWrapper::from(Signal::SIGALRM)),
Permission::W,
);
wake
}
#[cfg(test)]
pub(crate) fn sigalrm_loss_recorded(&self, process: DetPid) -> bool {
self.sigalrm.lost.contains(&process)
}
fn record_sigalrm_loss(&mut self, process: DetPid, thread: DetTid, why: &str) {
if self.sigalrm.lost.insert(process) {
crate::detlog::write_loss_notice(&format!(
"thread {thread} of process {process} has a pending guest-handled SIGALRM, but {why}"
));
}
}
fn filed_pause(&self, thread: DetTid) -> bool {
self.next_turns
.get(&thread)
.and_then(|turn| turn.req.try_read())
.is_some_and(|request| {
request.is_ok_and(|resources| {
resources.fyi == PAUSE_FYI
&& resources.resources.keys().any(|resource| {
matches!(resource, ResourceID::SleepUntil(deadline) if deadline.is_indefinite())
})
})
})
}
}