ax-task 0.8.0

OS-independent IRQ-safe SMP task scheduling core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Generation-checked registry and scheduling orchestration.

mod balance;
mod cancellation;
mod cpu_lifecycle;
mod deadline;
mod deferred_work;
mod delivery;
mod dispatch;
mod exited_work;
mod lifecycle;
mod membarrier;
mod migration;
mod model;
mod outcome;
mod park_exit;
mod pi;
#[cfg(axtest)]
pub use {
    pi::PiScheduleTestProbeSnapshot, pi::begin_pi_schedule_test_probe,
    pi::end_pi_schedule_test_probe, pi::pi_schedule_test_probe_snapshot,
};
mod placement;
mod priority_index;
mod registry;
mod root_domain;
mod scheduling;
mod switch;
mod thread_api;
mod thread_callbacks;
mod thread_creation;

use alloc::{sync::Arc, vec::Vec};
use core::{pin::Pin, ptr};

use exited_work::ExitedThreadWork;
pub(crate) use membarrier::{MembarrierCpuTargets, MembarrierTarget};
use model::{
    BalanceReason, BalanceTransferOutcome, DeferredTaskWorkClass, DetachedOwnerMessageBatch,
    FAIR_BALANCE_BALANCED_BACKOFF_FACTOR, FAIR_BALANCE_CONSTRAINED_BACKOFF_FACTOR,
    FairBalanceResult, FairPolicyPlacement,
};
pub use model::{DeferredTaskWorkBatch, OwnedThreadReapError, TaskSystem};
pub(crate) use outcome::SwitchEndpoint;
pub use outcome::{
    ChargeOutcome, DeadlineActivitySnapshot, DeadlineRuntimeSnapshot, OwnerControlDrain,
    ScheduleDecision, SchedulerOutcome, SwitchInCompletion, YieldOutcome,
};
pub(crate) use park_exit::CurrentExitPermit;
use priority_index::RootDomainPriorityIndex;
use registry::{
    CpuRegistration, DeadlineCallbackClaim, DetachedThreadRecord, TaskSystemState, ThreadRecord,
    ThreadSlot,
};
use root_domain::{DeadlineBandwidthRebuild, RootDomain, RootDomainPushClass, RootDomainState};
use thread_callbacks::ThreadCallbackState;

use super::thread_sched::{
    PiScheduleUpdate, ThreadDeadlineInit, ThreadPlacementInit, ThreadPolicyInit, ThreadRuntimeInit,
    ThreadSchedCell, ThreadSchedInit, ThreadSchedState,
};
use crate::{
    executor::CoroutineHeader,
    runtime::{
        RuntimeStatus,
        config::TaskSystemConfig,
        cpu::{CpuLocal, CpuRemote, CpuRemoteHandle, CpuSnapshot, RuntimeCpuId},
        delivery::{
            inbox::{InboxKind, InboxMessage, InboxOperation, PublishResult, SchedulerInbox},
            work::{TaskWorkConsumerGuard, TaskWorkDoorbell},
        },
        lock::{IrqScope, IrqTicketLock, PreemptTicketLock},
        resource::{
            AddressSpaceDestroyOutcome, AddressSpaceMembarrierId, AddressSpaceMembarrierState,
            AddressSpaceReclaimArmOutcome, MembarrierRegistration, MembarrierRegistrationPhase,
            ThreadResources,
        },
        switch::{ContextThreadBinding, CurrentThreadPublication, CurrentThreadRef},
        sync::{PiMutexRaw, PiWaitToken},
        task_runtime,
    },
    sched::{
        CpuId, CpuSet, DeadlineBandwidthSnapshot, FairMode, SchedulePolicy, SchedulerTimestamp,
        SchedulingClass, ThreadAffinityChange,
        algorithm::{
            ActiveSchedulingState, DeadlineAdmission, EnqueueReason, PickedThread, QueuedThread,
            QueuedThreadSnapshot, RqTaskMetadata, SchedulingEntity,
        },
        system::{
            CpuRemotePublication, SchedulerDeadlineDerivationSource, SchedulerPolicyRef,
            cpu::{
                CpuRunQueueState, CurrentDispatch, DeadlineBaseGuardSource, EqualRtWakeAction,
                HardTimerServiceClaim, HardTimerServiceStep, IdlePullReservation,
                KtimerServiceClaim, OwnerRqEntry, OwnerRqTxn, PreparedMigrationDelivery,
                RescheduleKind, RunQueueClockSnapshot, RunQueueDomainPublication,
                RunQueueGuardSource, SchedulerDeadlineRqObservation, SchedulerRequestScope,
                SchedulerThreadRef, SoftTimerExpireBatch, WakePreemptionDecision,
            },
        },
    },
    thread::{
        DEADLINE_CLASS_RANK, DeadlineEntity, DeadlineServer, OwnedThreadSchedulerExit, ParkCommit,
        ParkPrepare, ParkTicket, PiDonation, PiWaitKey, PiWaitRegistration, REALTIME_CLASS_RANK,
        SchedulingUrgency, SwitchReason, TaskError, ThreadCore, ThreadCoreInit, ThreadExtension,
        ThreadExtensionBorrow, ThreadExtensionLease, ThreadExtensionView, ThreadHandle, ThreadId,
        ThreadRuntimeSnapshot, ThreadSpec, ThreadState, ThreadWakeHandle, WaitWakeClaim,
        WaitWakeDelivery, WakeIntent, WakeResult,
    },
    time::{
        MonotonicDeadline, MonotonicInstant,
        queue::{
            ExpiredTaskDeadline, KernelTimerExecution, TaskDeadlineArmPlan, TaskDeadlineError,
            TaskDeadlineKind, TaskDeadlineNode, TaskDeadlineQueue, TaskDeadlineRegistration,
        },
    },
};

struct UnpublishedThreadGuard<'system> {
    system: &'system TaskSystem,
    spec: Option<ThreadSpec>,
}

fn apply_pi_schedule_update(
    sched: &mut ThreadSchedState,
    mut active: ActiveSchedulingState,
    update: PiScheduleUpdate,
    owner_now_ns: u64,
    fair_placement: Option<FairPolicyPlacement>,
) -> Result<ActiveSchedulingState, TaskError> {
    if update.generation != sched.policy.dispatch_generation {
        return Err(TaskError::InvalidPiState);
    }

    let PiScheduleUpdate {
        policy,
        donor,
        deadline_donor,
        deadline_donor_core,
        deadline_donor_server,
        generation: _,
    } = update;
    let old_donor = sched.pi.donor;
    let old_deadline_donor = sched.pi.deadline_donor;
    let base = sched.policy.base;
    let old_uses_inherited = active.uses_inherited_entity();
    let next_uses_inherited = donor.is_some() && !pi_reuses_base_entity(base, policy);
    if old_uses_inherited && !next_uses_inherited {
        active.use_base_entity(base);
    }

    let source_changed = old_donor != donor || old_deadline_donor != deadline_donor;
    let donor_server = deadline_donor_server;
    match (donor, policy) {
        (None, base_policy) if base_policy == base => {
            active.use_base_entity(base_policy);
        }
        (Some(_), SchedulePolicy::Deadline(_)) => {
            if !next_uses_inherited {
                return Err(TaskError::InvalidPiState);
            }
            if !old_uses_inherited || source_changed {
                active.use_inherited_entity(
                    policy,
                    SchedulingEntity::Deadline(crate::thread::DeadlineEntity::from_donor_server(
                        sched.deadline.server.clone(),
                        donor_server.ok_or(TaskError::InvalidPiState)?,
                    )),
                );
            } else {
                active.update_inherited_effective_policy(policy);
            }
            let SchedulingEntity::Deadline(deadline) = active.entity() else {
                return Err(TaskError::InvalidPiState);
            };
            deadline.replenish_for_pi(owner_now_ns);
        }
        (Some(_), SchedulePolicy::Fifo { .. }) => {
            if next_uses_inherited {
                active.use_inherited_entity(policy, SchedulingEntity::Fifo);
            } else if !matches!(active.base_entity(), SchedulingEntity::Fifo) {
                return Err(TaskError::InvalidPiState);
            } else {
                active.use_base_entity_with_effective_policy(policy);
            }
        }
        (Some(_), SchedulePolicy::RoundRobin { quantum_ns, .. }) => {
            if next_uses_inherited {
                return Err(TaskError::InvalidPiState);
            }
            if !matches!(active.base_entity(), SchedulingEntity::RoundRobin { .. }) {
                return Err(TaskError::InvalidPiState);
            }
            if old_donor.is_none()
                && let SchedulingEntity::RoundRobin {
                    remaining_quantum_ns,
                } = active.base_entity_mut()
                && *remaining_quantum_ns > quantum_ns
            {
                *remaining_quantum_ns = quantum_ns;
            }
            active.use_base_entity_with_effective_policy(policy);
        }
        (Some(_), SchedulePolicy::Fair { nice, mode }) => {
            if next_uses_inherited {
                return Err(TaskError::InvalidPiState);
            }
            let SchedulingEntity::Fair(fair) = *active.base_entity() else {
                return Err(TaskError::InvalidPiState);
            };
            let placement = fair_placement.ok_or(TaskError::InvalidPiState)?;
            active.replace_base_entity(SchedulingEntity::Fair(fair.reconfigure(
                nice,
                mode,
                placement.source_virtual_time,
                placement.destination_virtual_time,
            )));
            active.use_base_entity_with_effective_policy(policy);
        }
        _ => return Err(TaskError::InvalidPiState),
    }

    sched.pi.donor = donor;
    sched.pi.deadline_donor = deadline_donor;
    sched.pi.deadline_donor_core = deadline_donor_core;
    Ok(active)
}

fn pi_reuses_base_entity(base: SchedulePolicy, effective: SchedulePolicy) -> bool {
    matches!(
        (base, effective),
        (
            SchedulePolicy::Fifo { .. } | SchedulePolicy::RoundRobin { .. },
            SchedulePolicy::Fifo { .. } | SchedulePolicy::RoundRobin { .. }
        ) | (SchedulePolicy::Fair { .. }, SchedulePolicy::Fair { .. })
    )
}

struct OwnerNext {
    core: SchedulerThreadRef,
    policy: SchedulerPolicyRef,
    urgency: SchedulingUrgency,
}

/// Scheduler-clock consequence of one committed owner selection.
///
/// Linux updates hrtick and class timers only when the selected classes or
/// their deadline-bearing state changed. A plain FIFO-to-FIFO rotation has no
/// per-task clockevent, so it carries an explicit unchanged result instead of
/// re-deriving every shared deadline after each context switch.
enum OwnerSchedulerDeadline {
    Unchanged,
    Reevaluate(SchedulerDeadlineRqObservation),
}

impl<'system> UnpublishedThreadGuard<'system> {
    fn new(system: &'system TaskSystem, spec: ThreadSpec) -> Self {
        Self {
            system,
            spec: Some(spec),
        }
    }

    fn into_owned_parts(mut self) -> (Option<ThreadExtension>, ThreadResources) {
        self.spec
            .take()
            .expect("unpublished thread transaction must still own its specification")
            .into_owned_parts()
    }

    fn into_spec(mut self) -> ThreadSpec {
        self.spec
            .take()
            .expect("unpublished thread transaction must still own its specification")
    }

    fn spec(&self) -> &ThreadSpec {
        self.spec
            .as_ref()
            .expect("unpublished thread transaction must still own its specification")
    }
}

impl Drop for UnpublishedThreadGuard<'_> {
    fn drop(&mut self) {
        if let Some(spec) = self.spec.take() {
            let (extension, resources) = spec.into_owned_parts();
            self.system
                .release_unpublished_thread(DetachedThreadRecord::new(resources, extension));
        }
    }
}

impl TaskSystem {
    /// Creates an empty scheduler instance for a fixed topology.
    ///
    /// # Errors
    ///
    /// Returns [`TaskError::InvalidCpuCount`] for an empty or unrepresentable
    /// topology and [`TaskError::InvalidConfiguration`] for inconsistent fixed
    /// capacities or bandwidth values.
    pub fn new(config: TaskSystemConfig) -> Result<Self, TaskError> {
        validate_config(config)?;
        let task_work = Arc::new(TaskWorkDoorbell::new());
        let cpu_remotes = (0..config.cpu_count())
            .map(|index| CpuRemote::create(CpuId::new(index as u32), config))
            .collect::<Result<Vec<_>, _>>()?;
        let cpu_registrations = cpu_remotes
            .iter()
            .cloned()
            .map(|remote| CpuRegistration { remote })
            .collect();
        let root_domain = RootDomain::new(config, cpu_remotes.clone());
        Ok(Self {
            config,
            cpu_remotes,
            state: PreemptTicketLock::new(TaskSystemState {
                cpus: cpu_registrations,
                slots: crate::thread::allocation::try_vec(config.thread_capacity())?,
                free_slots: crate::thread::allocation::try_vec(config.thread_capacity())?,
                pending_address_space_reclaims: crate::thread::allocation::try_vec(
                    config.thread_capacity().max(config.cpu_count()),
                )?,
                task_work_class_cursor: DeferredTaskWorkClass::Deadline,
                address_space_reclaim_first: true,
                exited_work: ExitedThreadWork::new(config.thread_capacity())?,
            }),
            root_domain,
            deferred_coroutine_reclaims: SchedulerInbox::new(InboxKind::Reclaim),
            deferred_thread_cancellations: SchedulerInbox::new(InboxKind::Reclaim),
            deferred_deadline_callbacks: SchedulerInbox::new(InboxKind::TaskWork),
            deferred_scheduler_ticks: SchedulerInbox::new(InboxKind::TaskWork),
            task_work,
        })
    }
}

fn validate_config(config: TaskSystemConfig) -> Result<(), TaskError> {
    if config.cpu_count() == 0 || config.cpu_count() > u32::MAX as usize {
        return Err(TaskError::InvalidCpuCount(config.cpu_count()));
    }
    if config.deadline_cap_percent() == 0
        || config.deadline_cap_percent() > 100
        || config.rt_period_ns() == 0
        || config.rt_runtime_ns() > config.rt_period_ns()
        || config.balance_interval_ns() == 0
        || config.thread_capacity() == 0
        || config.thread_capacity() > u32::MAX as usize
        || config.batch_limit() == 0
        || config.batch_limit() > crate::runtime::config::DEFAULT_BATCH_LIMIT
        || config.pi_chain_limit() == 0
    {
        return Err(TaskError::InvalidConfiguration);
    }
    Ok(())
}

fn deadline_zero_lag(deadline: &DeadlineEntity) -> SchedulerTimestamp {
    let policy = deadline.policy();
    let lag_ns = deadline.remaining_runtime_ns() as u128 * policy.period_ns() as u128
        / policy.runtime_ns() as u128;
    let lag_ns = u64::try_from(lag_ns)
        .expect("Deadline zero-lag interval cannot exceed one scheduler period");
    SchedulerTimestamp::from_nanos(
        deadline
            .absolute_deadline_ns()
            .expect("an active Deadline entity must own a zero-lag anchor"),
    )
    .retreat(lag_ns)
}

fn ensure_runtime_success(status: RuntimeStatus) -> Result<(), TaskError> {
    if status == RuntimeStatus::Success {
        Ok(())
    } else {
        Err(TaskError::RuntimeFailure(status as u32))
    }
}

fn validate_affinity(affinity: &CpuSet, cpu_count: usize) -> Result<(), TaskError> {
    if affinity.topology_len() == cpu_count {
        Ok(())
    } else {
        Err(TaskError::InvalidConfiguration)
    }
}

// The top bit of the generation-bearing identity is reserved for compact
// scheduler-adjacent owner words such as the Linux-style PI mutex waiters bit.
// Exhausting a slot retires it instead of wrapping and reintroducing ABA.
const MAX_THREAD_GENERATION: u32 = i32::MAX as u32;

const fn next_generation(generation: u32) -> u32 {
    if generation < MAX_THREAD_GENERATION {
        generation + 1
    } else {
        generation
    }
}

fn advance_thread_slot_generation(slot: &mut ThreadSlot) -> bool {
    assert_eq!(
        slot.pending_deadline_reservation, 0,
        "a reusable thread slot must not retain Deadline admission"
    );
    let next = next_generation(slot.generation);
    if next == slot.generation {
        // The empty slot remains in the registry so every stale identity still
        // resolves to `record == None`, but it is never returned to free_slots:
        // wrapping would make an older generation-bearing ThreadId valid again.
        false
    } else {
        slot.generation = next;
        true
    }
}