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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Deadline server ownership and CBS execution ledger.

use super::*;

/// Stable task-owned Deadline server, equivalent to Linux's embedded
/// `task_struct::dl`.
///
/// A task may expose its configured parameters through another task's
/// `pi_of()` reference, but each task's mutable CBS execution ledger remains
/// local and is never copied between runqueues.
#[derive(Clone, Debug)]
pub(crate) struct DeadlineServer {
    storage: Arc<IrqTicketLock<DeadlineServerStorage>>,
}

#[derive(Debug)]
struct DeadlineServerStorage {
    policy: Option<DeadlinePolicy>,
    execution: DeadlineServerState,
}

impl DeadlineServer {
    pub(crate) fn unbound() -> Result<Self, crate::thread::TaskError> {
        Ok(Self {
            storage: crate::thread::allocation::try_arc(IrqTicketLock::new(
                DeadlineServerStorage {
                    policy: None,
                    execution: DeadlineServerState::new(),
                },
            ))?,
        })
    }

    pub(crate) fn bind(&self, policy: DeadlinePolicy) {
        let mut storage = self
            .storage
            .lock(crate::runtime::IrqGuardSource::DeadlineServerTicket);
        storage.policy = Some(policy);
        storage.execution = DeadlineServerState::new();
    }

    fn policy(&self) -> DeadlinePolicy {
        self.storage
            .lock(crate::runtime::IrqGuardSource::DeadlineServerTicket)
            .policy
            .expect("Deadline parameters require a bound task server")
    }

    fn with_execution<R>(&self, operation: impl FnOnce(&DeadlineServerState) -> R) -> R {
        operation(
            &self
                .storage
                .lock(crate::runtime::IrqGuardSource::DeadlineServerTicket)
                .execution,
        )
    }

    fn with_execution_mut<R>(&self, operation: impl FnOnce(&mut DeadlineServerState) -> R) -> R {
        operation(
            &mut self
                .storage
                .lock(crate::runtime::IrqGuardSource::DeadlineServerTicket)
                .execution,
        )
    }
}

impl PartialEq for DeadlineServer {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.storage, &other.storage)
    }
}

impl Eq for DeadlineServer {}

/// Linux-style local Deadline execution state plus effective PI parameters.
///
/// `local` is the task's embedded `sched_dl_entity`: runtime, absolute
/// deadline, throttle, and overrun state are charged exactly once there.
/// `parameters` is Linux `pi_of(dl_se)`: normally the same server, or the
/// stable donor server while boosted. PREEMPT_RT disables proxy execution, so
/// the donor's mutable runtime is not charged by the owner.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct DeadlineEntity {
    local: DeadlineServer,
    parameters: DeadlineServer,
}

/// Mutable CBS accounting associated with one stable Deadline server.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DeadlineServerState {
    absolute_deadline: Option<SchedulerTimestamp>,
    next_period: Option<SchedulerTimestamp>,
    remaining_runtime_ns: i128,
    state: DeadlineJobState,
    overruns: u64,
}

/// Mutually exclusive CBS lifecycle owned by the Deadline class.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DeadlineJobState {
    Inactive,
    Runnable,
    Throttled(DeadlineThrottleReason),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DeadlineThrottleReason {
    RuntimeExhausted,
    Yielded,
    ConstrainedWake,
}

impl DeadlineEntity {
    pub(crate) fn from_task_server(policy: DeadlinePolicy, server: DeadlineServer) -> Self {
        server.bind(policy);
        Self {
            local: server.clone(),
            parameters: server,
        }
    }

    /// Creates the effective entity used while the local task inherits a
    /// Deadline scheduling context.
    pub(crate) fn from_donor_server(local: DeadlineServer, donor: DeadlineServer) -> Self {
        Self {
            local,
            parameters: donor,
        }
    }

    pub(crate) fn is_pi_boosted(&self) -> bool {
        self.local != self.parameters
    }

    pub(crate) fn replenish_for_pi(&self, now_ns: u64) {
        let policy = self.policy();
        self.local
            .with_execution_mut(|state| state.replenish_for_pi(now_ns, policy));
    }

    pub(crate) fn activate(&self, now_ns: u64) {
        let policy = self.policy();
        let pi_boosted = self.is_pi_boosted();
        self.local
            .with_execution_mut(|state| state.activate(now_ns, policy, pi_boosted));
    }

    pub(crate) fn charge(&self, runtime_ns: u64, reclaimed_ns: u64) -> bool {
        let policy = self.policy();
        self.local
            .with_execution_mut(|state| state.charge(policy, runtime_ns, reclaimed_ns))
    }

    pub(crate) fn replenish(&self, now_ns: u64) {
        let policy = self.policy();
        self.local
            .with_execution_mut(|state| state.replenish(now_ns, policy));
    }

    pub(crate) fn yield_job(&self) {
        self.local
            .with_execution_mut(DeadlineServerState::yield_job);
    }

    pub fn absolute_deadline_ns(&self) -> Option<u64> {
        self.local
            .with_execution(DeadlineServerState::absolute_deadline_ns)
    }

    pub fn policy(&self) -> DeadlinePolicy {
        self.parameters.policy()
    }

    pub fn owner_flags(&self) -> DeadlineFlags {
        self.local
            .storage
            .lock(crate::runtime::IrqGuardSource::DeadlineServerTicket)
            .policy
            .map_or(DeadlineFlags::NONE, DeadlinePolicy::flags)
    }

    pub fn remaining_runtime_ns(&self) -> u64 {
        self.local
            .with_execution(DeadlineServerState::remaining_runtime_ns)
    }

    pub(crate) fn next_scheduler_event_ns(&self) -> Option<u64> {
        if self.is_pi_boosted() {
            None
        } else {
            self.local
                .with_execution(DeadlineServerState::next_scheduler_event_ns)
        }
    }

    pub fn is_throttled(&self) -> bool {
        self.local.with_execution(DeadlineServerState::is_throttled)
    }

    pub fn overruns(&self) -> u64 {
        self.local.with_execution(|state| state.overruns)
    }

    pub(crate) fn scheduling_urgency(&self) -> SchedulingUrgency {
        let deadline = self
            .absolute_deadline_ns()
            .expect("an inactive Deadline entity has no scheduler urgency");
        SchedulingUrgency::new(
            SchedulePolicy::Deadline(self.policy()).class_rank(),
            deadline,
        )
    }
}

impl DeadlineServerState {
    const fn new() -> Self {
        Self {
            absolute_deadline: None,
            next_period: None,
            remaining_runtime_ns: 0,
            state: DeadlineJobState::Inactive,
            overruns: 0,
        }
    }

    fn replenish_for_pi(&mut self, now_ns: u64, policy: DeadlinePolicy) {
        let now = SchedulerTimestamp::from_nanos(now_ns);
        if matches!(self.state, DeadlineJobState::Inactive)
            || self.absolute_deadline.is_none()
            || self.next_period.is_none()
        {
            self.start_fresh_job(now, policy);
            return;
        }
        if self.remaining_runtime_ns <= 0 {
            let _ = self.advance_depleted_job(now, policy);
        }
        self.state = DeadlineJobState::Runnable;
    }

    /// Applies the CBS wake-up rule and activates a fresh job when required.
    fn activate(&mut self, now_ns: u64, policy: DeadlinePolicy, pi_boosted: bool) {
        let now = SchedulerTimestamp::from_nanos(now_ns);
        if matches!(self.state, DeadlineJobState::Inactive)
            || self.absolute_deadline.is_none()
            || self.next_period.is_none()
        {
            self.start_fresh_job(now, policy);
            return;
        }
        if self.is_throttled() {
            return;
        }

        let constrained = policy.deadline_ns() < policy.period_ns();
        let absolute_deadline = self
            .absolute_deadline
            .expect("an active Deadline job must own an absolute deadline");
        // Linux runs `dl_check_constrained_dl()` before `update_dl_entity()`.
        // A constrained-deadline task waking after its absolute deadline but
        // before the next period must remain throttled; starting a fresh CBS
        // job here would let it consume runtime/deadline instead of its
        // admitted runtime/period bandwidth.
        if absolute_deadline.is_before(now) {
            let next_period = self
                .next_period
                .expect("an active Deadline job must retain its next period");
            if constrained && !pi_boosted && now.is_before(next_period) {
                self.remaining_runtime_ns = 0;
                self.state = DeadlineJobState::Throttled(DeadlineThrottleReason::ConstrainedWake);
                return;
            }
            self.start_fresh_job(now, policy);
            return;
        }
        if self.remaining_runtime_ns <= 0 {
            self.state = DeadlineJobState::Throttled(DeadlineThrottleReason::RuntimeExhausted);
            return;
        }
        let time_to_deadline_ns = absolute_deadline.since(now);
        if !density_exceeds_reservation(
            self.remaining_runtime_ns as u128,
            time_to_deadline_ns,
            policy,
        ) {
            return;
        }

        if constrained && !pi_boosted {
            self.remaining_runtime_ns = revised_wakeup_runtime(time_to_deadline_ns, policy);
            if self.remaining_runtime_ns == 0 {
                self.state = DeadlineJobState::Throttled(DeadlineThrottleReason::ConstrainedWake);
            }
        } else {
            self.start_fresh_job(now, policy);
        }
    }

    /// Charges execution, returning whether the reservation became throttled.
    fn charge(&mut self, policy: DeadlinePolicy, runtime_ns: u64, reclaimed_ns: u64) -> bool {
        let permitted_reclaim = if policy.flags().contains(DeadlineFlags::RECLAIM) {
            reclaimed_ns
        } else {
            0
        };
        let charge = runtime_ns.saturating_sub(permitted_reclaim);
        if charge == 0 {
            return self.is_throttled();
        }
        let had_budget = self.remaining_runtime_ns > 0;
        self.remaining_runtime_ns = self.remaining_runtime_ns.saturating_sub(charge as i128);
        if had_budget && self.remaining_runtime_ns <= 0 {
            self.state = DeadlineJobState::Throttled(DeadlineThrottleReason::RuntimeExhausted);
            self.overruns = self.overruns.saturating_add(1);
        }
        self.is_throttled()
    }

    /// Replenishes a throttled CBS entity at its scheduling event.
    ///
    /// Budget exhaustion carries overrun debt and postpones the scheduling
    /// deadline by whole periods. Explicit yield is distinct and waits for the
    /// next job release boundary.
    fn replenish(&mut self, now_ns: u64, policy: DeadlinePolicy) {
        let DeadlineJobState::Throttled(reason) = self.state else {
            return;
        };
        let now = SchedulerTimestamp::from_nanos(now_ns);
        if reason == DeadlineThrottleReason::Yielded {
            let next_period = self
                .next_period
                .expect("a yielded Deadline job must retain its next release");
            if !next_period.is_reached_by(now) {
                return;
            }
            let elapsed = now.since(next_period);
            let periods = elapsed / policy.period_ns();
            let release_advance = periods
                .checked_mul(policy.period_ns())
                .expect("elapsed scheduler time bounds the release advance");
            let release = next_period.advance(release_advance);
            self.absolute_deadline = Some(release.advance(policy.deadline_ns()));
            self.next_period = Some(release.advance(policy.period_ns()));
            self.remaining_runtime_ns = policy.runtime_ns() as i128;
        } else {
            let next_period = self
                .next_period
                .expect("a throttled Deadline job must retain its next release");
            if !next_period.is_reached_by(now) {
                return;
            }
            if !self.advance_depleted_job(now, policy) {
                return;
            }
        }
        self.state = DeadlineJobState::Runnable;
    }

    /// Ends the current job and throttles it until replenishment.
    fn yield_job(&mut self) {
        self.remaining_runtime_ns = 0;
        self.state = DeadlineJobState::Throttled(DeadlineThrottleReason::Yielded);
    }

    /// Returns the current absolute deadline.
    const fn absolute_deadline_ns(&self) -> Option<u64> {
        match self.absolute_deadline {
            Some(deadline) => Some(deadline.as_nanos()),
            None => None,
        }
    }

    /// Returns remaining CBS runtime.
    const fn remaining_runtime_ns(&self) -> u64 {
        if self.remaining_runtime_ns <= 0 {
            0
        } else if self.remaining_runtime_ns > u64::MAX as i128 {
            u64::MAX
        } else {
            self.remaining_runtime_ns as u64
        }
    }

    /// Returns the next CBS replenishment boundary.
    const fn next_period_ns(&self) -> Option<u64> {
        match self.next_period {
            Some(next_period) => Some(next_period.as_nanos()),
            None => None,
        }
    }

    const fn next_scheduler_event_ns(&self) -> Option<u64> {
        if self.is_throttled() {
            self.next_period_ns()
        } else {
            None
        }
    }

    /// Returns whether the entity is throttled.
    const fn is_throttled(&self) -> bool {
        matches!(self.state, DeadlineJobState::Throttled(_))
    }

    fn start_fresh_job(&mut self, now: SchedulerTimestamp, policy: DeadlinePolicy) {
        self.absolute_deadline = Some(now.advance(policy.deadline_ns()));
        self.next_period = Some(now.advance(policy.period_ns()));
        self.remaining_runtime_ns = policy.runtime_ns() as i128;
        self.state = DeadlineJobState::Runnable;
    }

    fn advance_depleted_job(&mut self, now: SchedulerTimestamp, policy: DeadlinePolicy) -> bool {
        if self.remaining_runtime_ns > 0 {
            return false;
        }
        let runtime_ns = policy.runtime_ns() as u128;
        let debt_ns = self.remaining_runtime_ns.unsigned_abs();
        let periods = debt_ns / runtime_ns + 1;
        let deadline_advance = periods
            .checked_mul(policy.period_ns() as u128)
            .expect("Deadline overrun debt multiplication overflowed u128");
        assert!(
            deadline_advance < SCHEDULER_TIME_HALF_RANGE as u128,
            "Deadline overrun debt exceeded the scheduler clock comparison window"
        );
        let new_deadline = self
            .absolute_deadline
            .expect("a depleted Deadline job must retain its deadline")
            .advance(deadline_advance as u64);
        let replenished_runtime = periods * runtime_ns - debt_ns;

        if new_deadline.is_before(now) {
            self.start_fresh_job(now, policy);
            return true;
        }

        self.absolute_deadline = Some(new_deadline);
        self.next_period = Some(new_deadline.advance(policy.period_ns() - policy.deadline_ns()));
        self.remaining_runtime_ns = replenished_runtime as i128;
        true
    }
}