starry-kernel 0.10.0

A Linux-compatible OS kernel built on ArceOS unikernel
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! POSIX per-process interval timers (timer_create, timer_settime, etc.)

use alloc::collections::BTreeMap;
#[cfg(axtest)]
use alloc::sync::Weak;
use core::{
    mem,
    ops::Bound::{Excluded, Included, Unbounded},
    sync::atomic::{AtomicBool, AtomicI32, Ordering},
    time::Duration,
};

use ax_runtime::hal::time::{NANOS_PER_SEC, monotonic_time_nanos, wall_time};
use linux_raw_sys::general::{
    CLOCK_BOOTTIME, CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, CLOCK_MONOTONIC_RAW,
    CLOCK_PROCESS_CPUTIME_ID, CLOCK_REALTIME, CLOCK_REALTIME_COARSE, CLOCK_THREAD_CPUTIME_ID,
    SIGEV_NONE, SIGEV_SIGNAL,
};
use starry_signal::{SignalInfo, Signo};

#[cfg(axtest)]
use super::PidIdentity;
use super::timer::{AlarmChange, AlarmSlot, AlarmTarget, AlarmToken};
use crate::{StarryError, StarryResult, sync::Mutex, time::ClockDeadline};

const EXPIRY_SCAN_BATCH_SIZE: usize = 16;
const MAX_TIMER_NANOS: u64 = i64::MAX as u64;

#[cfg(axtest)]
fn test_alarm_target() -> AlarmTarget {
    AlarmTarget::Process(Weak::<PidIdentity>::new())
}

#[derive(Clone, Copy)]
struct TimerClockSnapshot {
    realtime: u64,
    monotonic: u64,
    boottime: u64,
}

impl TimerClockSnapshot {
    fn capture(mut now_ns: impl FnMut(u32) -> u64) -> Self {
        Self {
            realtime: now_ns(CLOCK_REALTIME),
            monotonic: now_ns(CLOCK_MONOTONIC),
            boottime: now_ns(CLOCK_BOOTTIME),
        }
    }

    fn now(self, clock_id: u32) -> u64 {
        match clock_id {
            CLOCK_REALTIME => self.realtime,
            CLOCK_MONOTONIC => self.monotonic,
            CLOCK_BOOTTIME => self.boottime,
            _ => unreachable!("unsupported POSIX timer clock"),
        }
    }
}

struct ExpiryOutcome {
    signal: Option<SignalInfo>,
    alarm_change: AlarmChange,
}

impl ExpiryOutcome {
    fn apply(self, target: AlarmTarget, emitter: &mut impl FnMut(SignalInfo)) {
        // settime/delete/exec invalidate the slot generation before updating
        // the alarm queue. Mirror Linux's it_signal_seq check at the signal
        // publication boundary so an expiry collected by an older generation
        // cannot publish after the timer was replaced.
        if self.alarm_change.is_current_generation()
            && let Some(signal) = self.signal
        {
            emitter(signal);
        }
        self.alarm_change.apply(target);
    }
}

struct ExpiryScanBatch {
    outcomes: heapless::Vec<ExpiryOutcome, EXPIRY_SCAN_BATCH_SIZE>,
    last_scanned_id: Option<i32>,
    complete: bool,
}

impl ExpiryScanBatch {
    const fn new() -> Self {
        Self {
            outcomes: heapless::Vec::new(),
            last_scanned_id: None,
            complete: false,
        }
    }

    fn push(&mut self, outcome: ExpiryOutcome) {
        if self.outcomes.push(outcome).is_err() {
            unreachable!("expiry scan produced more than one outcome per timer")
        }
    }

    fn apply(self, target: AlarmTarget, emitter: &mut impl FnMut(SignalInfo)) {
        for outcome in self.outcomes {
            outcome.apply(target.clone(), emitter);
        }
    }
}

/// Kernel-side representation of a POSIX timer.
struct PosixTimer {
    /// The clock used by this timer.
    clock_id: u32,
    /// Signal to deliver on expiry (None for SIGEV_NONE).
    signo: Option<Signo>,
    /// The sigev_value passed by the user at timer_create time.
    /// Delivered back in siginfo_t.si_value on expiry.
    sigev_value: i64,
    /// Interval for periodic timers (0 = one-shot).
    interval_ns: u64,
    /// Relative realtime timers run on the monotonic clock.
    deadline_clock_id: u32,
    /// Absolute deadline in `deadline_clock_id`'s domain, or 0 if disarmed.
    deadline_ns: u64,
    /// Stable alarm-queue identity with generation-based stale-wakeup rejection.
    alarm_slot: AlarmSlot,
}

impl PosixTimer {
    fn alarm_deadline(&self) -> ClockDeadline {
        let deadline = Duration::from_nanos(self.deadline_ns);
        if self.deadline_clock_id == CLOCK_REALTIME {
            ClockDeadline::Realtime(deadline)
        } else {
            ClockDeadline::Monotonic(deadline)
        }
    }

    fn poll_expiry(&mut self, now: u64, trigger: Option<&AlarmToken>) -> Option<ExpiryOutcome> {
        if self.deadline_ns == 0 {
            return None;
        }
        if trigger.is_some_and(|token| !self.alarm_slot.matches(token)) {
            return None;
        }

        if now >= self.deadline_ns {
            let elapsed = now.saturating_sub(self.deadline_ns);
            let overrun = elapsed
                .checked_div(self.interval_ns)
                .unwrap_or(0)
                .min(i32::MAX as u64) as i32;
            let signal = self
                .signo
                .map(|signo| SignalInfo::new_timer(signo, self.sigev_value, overrun));
            let alarm_change = if let Some(elapsed_periods) = elapsed.checked_div(self.interval_ns)
            {
                // Advance to the first future period. A delayed worker
                // produces one coalesced signal rather than an unbounded
                // burst of immediate re-firings.
                let periods = elapsed_periods.saturating_add(1);
                self.deadline_ns = self
                    .deadline_ns
                    .saturating_add(periods.saturating_mul(self.interval_ns))
                    .min(MAX_TIMER_NANOS);
                self.alarm_slot.replace(Some(self.alarm_deadline()))
            } else {
                self.deadline_ns = 0;
                self.alarm_slot.replace(None)
            };
            return Some(ExpiryOutcome {
                signal,
                alarm_change,
            });
        }

        trigger.map(|_| {
            // The physical alarm may precede a non-monotonic clock deadline.
            // Its queue entry was consumed, so publish the remaining interval
            // again.
            ExpiryOutcome {
                signal: None,
                alarm_change: self.alarm_slot.replace(Some(self.alarm_deadline())),
            }
        })
    }
}

/// The value/interval pair passed to `timer_settime`.
pub struct TimerSpec {
    pub value_sec: i64,
    pub value_nsec: i64,
    pub interval_sec: i64,
    pub interval_nsec: i64,
}

/// Per-process POSIX timer table.
pub struct PosixTimerTable {
    next_id: AtomicI32,
    armed: AtomicBool,
    timers: Mutex<BTreeMap<i32, PosixTimer>>,
}

impl Default for PosixTimerTable {
    fn default() -> Self {
        Self {
            next_id: AtomicI32::new(0),
            armed: AtomicBool::new(false),
            timers: Mutex::new(BTreeMap::new()),
        }
    }
}

/// Returns true if the clock is valid for use with POSIX timers (timer_create).
/// Linux returns EOPNOTSUPP for RAW/COARSE clocks.
fn is_supported_timer_clock(clock_id: u32) -> bool {
    matches!(clock_id, CLOCK_REALTIME | CLOCK_MONOTONIC | CLOCK_BOOTTIME)
}

/// Returns true if the clock is known by the system at all.
fn is_valid_clock(clock_id: u32) -> bool {
    matches!(
        clock_id,
        CLOCK_REALTIME
            | CLOCK_REALTIME_COARSE
            | CLOCK_MONOTONIC
            | CLOCK_MONOTONIC_RAW
            | CLOCK_MONOTONIC_COARSE
            | CLOCK_BOOTTIME
            | CLOCK_PROCESS_CPUTIME_ID
            | CLOCK_THREAD_CPUTIME_ID
    )
}

fn clock_now_ns(clock_id: u32) -> u64 {
    match clock_id {
        CLOCK_REALTIME | CLOCK_REALTIME_COARSE => {
            let t = wall_time();
            t.as_secs()
                .saturating_mul(NANOS_PER_SEC)
                .saturating_add(t.subsec_nanos() as u64)
        }
        _ => monotonic_time_nanos() as u64,
    }
}

fn timespec_to_nanos_saturated(seconds: i64, nanoseconds: i64) -> u64 {
    (seconds as u64)
        .saturating_mul(NANOS_PER_SEC)
        .saturating_add(nanoseconds as u64)
        .min(MAX_TIMER_NANOS)
}

impl PosixTimerTable {
    fn publish_armed_state(&self, timers: &BTreeMap<i32, PosixTimer>) {
        self.armed.store(
            timers.values().any(|timer| timer.deadline_ns != 0),
            Ordering::Release,
        );
    }

    /// Returns whether an expiry scan can observe an armed timer.
    pub fn has_armed_timers(&self) -> bool {
        self.armed.load(Ordering::Acquire)
    }

    /// Create a new POSIX timer. Returns the timer ID.
    pub fn create(
        &self,
        clock_id: u32,
        sigev_notify: u32,
        sigev_signo: i32,
        sigev_value: i64,
    ) -> StarryResult<i32> {
        if !is_supported_timer_clock(clock_id) {
            if is_valid_clock(clock_id) {
                return Err(StarryError::OperationNotSupported);
            } else {
                return Err(StarryError::InvalidInput);
            }
        }

        let signo = match sigev_notify {
            SIGEV_NONE => None,
            SIGEV_SIGNAL => {
                if sigev_signo <= 0 || sigev_signo > 64 {
                    return Err(StarryError::InvalidInput);
                }
                Signo::from_repr(sigev_signo as u8)
            }
            _ => return Err(StarryError::InvalidInput),
        };

        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let timer = PosixTimer {
            clock_id,
            signo,
            sigev_value,
            interval_ns: 0,
            deadline_clock_id: clock_id,
            deadline_ns: 0,
            alarm_slot: AlarmSlot::new(),
        };
        self.timers.lock().insert(id, timer);
        Ok(id)
    }

    /// Delete a timer. Returns true if it existed.
    pub fn delete(&self, id: i32) -> bool {
        let timer = {
            let mut timers = self.timers.lock();
            let timer = timers.remove(&id);
            self.publish_armed_state(&timers);
            timer
        };
        if let Some(timer) = timer {
            let cancellation = timer.alarm_slot.replace(None);
            cancellation.apply_cancellation();
            true
        } else {
            false
        }
    }

    /// Clear all timers. Used on execve.
    pub fn clear(&self) {
        let timers = {
            let mut timers = self.timers.lock();
            let removed = mem::take(&mut *timers);
            self.armed.store(false, Ordering::Release);
            removed
        };
        for timer in timers.into_values() {
            let cancellation = timer.alarm_slot.replace(None);
            cancellation.apply_cancellation();
        }
    }

    /// Set (arm/disarm) a timer. Returns the old (interval, remaining) in nanos.
    pub fn settime(
        &self,
        target: AlarmTarget,
        id: i32,
        flags: i32,
        spec: TimerSpec,
    ) -> Result<(u64, u64), ()> {
        let TimerSpec {
            value_sec,
            value_nsec,
            interval_sec,
            interval_nsec,
        } = spec;
        // Validate timespec values
        if value_nsec < 0 || value_nsec >= NANOS_PER_SEC as i64 {
            return Err(());
        }
        if interval_nsec < 0 || interval_nsec >= NANOS_PER_SEC as i64 {
            return Err(());
        }
        if value_sec < 0 {
            return Err(());
        }
        if interval_sec < 0 {
            return Err(());
        }
        let clocks = TimerClockSnapshot::capture(clock_now_ns);

        let (old, alarm_change) = {
            let mut timers = self.timers.lock();
            let timer = timers.get_mut(&id).ok_or(())?;

            // Compute old remaining time
            let old_interval = timer.interval_ns;
            let old_remaining = if timer.deadline_ns > 0 {
                let now = clocks.now(timer.deadline_clock_id);
                timer.deadline_ns.saturating_sub(now)
            } else {
                0
            };

            // Compute new values
            let new_value_ns = timespec_to_nanos_saturated(value_sec, value_nsec);
            let new_interval_ns = timespec_to_nanos_saturated(interval_sec, interval_nsec);

            timer.interval_ns = new_interval_ns;

            let deadline = if new_value_ns == 0 {
                timer.deadline_ns = 0;
                None
            } else {
                let absolute = flags & 1 != 0; // TIMER_ABSTIME
                timer.deadline_clock_id = if absolute {
                    timer.clock_id
                } else {
                    CLOCK_MONOTONIC
                };
                timer.deadline_ns = if absolute {
                    new_value_ns
                } else {
                    clocks
                        .now(timer.deadline_clock_id)
                        .saturating_add(new_value_ns)
                        .min(MAX_TIMER_NANOS)
                };
                Some(timer.alarm_deadline())
            };

            let alarm_change = timer.alarm_slot.replace(deadline);
            self.publish_armed_state(&timers);
            ((old_interval, old_remaining), alarm_change)
        };

        // The alarm queue is a sleeping task-context boundary. Never enter it
        // while the per-process timer metadata is locked.
        alarm_change.apply(target);

        Ok(old)
    }

    /// Get the current timer state. Returns (interval_ns, remaining_ns).
    pub fn gettime(&self, id: i32) -> Result<(u64, u64), ()> {
        let clocks = TimerClockSnapshot::capture(clock_now_ns);
        let timers = self.timers.lock();
        let timer = timers.get(&id).ok_or(())?;

        let remaining = if timer.deadline_ns > 0 {
            let now = clocks.now(timer.deadline_clock_id);
            timer.deadline_ns.saturating_sub(now)
        } else {
            0
        };

        Ok((timer.interval_ns, remaining))
    }

    pub(crate) fn poll_expired_for(
        &self,
        target: AlarmTarget,
        token: &AlarmToken,
        mut emitter: impl FnMut(SignalInfo),
    ) {
        if !self.has_armed_timers() {
            return;
        }
        self.poll_expired_at(target, Some(token), clock_now_ns, &mut emitter);
    }

    fn poll_expired_at(
        &self,
        target: AlarmTarget,
        trigger: Option<&AlarmToken>,
        now_ns: impl FnMut(u32) -> u64,
        mut emitter: impl FnMut(SignalInfo),
    ) {
        let clocks = TimerClockSnapshot::capture(now_ns);
        let upper_id = {
            let timers = self.timers.lock();
            timers.last_key_value().map(|(&id, _)| id)
        };
        let Some(upper_id) = upper_id else {
            return;
        };

        let mut cursor = None;
        loop {
            let batch = self.collect_expiry_batch(cursor, upper_id, trigger, clocks);
            let complete = batch.complete;
            let next_cursor = batch.last_scanned_id;
            batch.apply(target.clone(), &mut emitter);
            if complete {
                break;
            }
            let Some(next_cursor) = next_cursor else {
                break;
            };
            cursor = Some(next_cursor);
        }
    }

    fn collect_expiry_batch(
        &self,
        start_after: Option<i32>,
        upper_id: i32,
        trigger: Option<&AlarmToken>,
        clocks: TimerClockSnapshot,
    ) -> ExpiryScanBatch {
        let mut batch = ExpiryScanBatch::new();
        let mut timers = self.timers.lock();
        {
            let lower_bound = start_after.map_or(Unbounded, Excluded);
            let mut candidates = timers.range_mut((lower_bound, Included(upper_id)));
            for _ in 0..EXPIRY_SCAN_BATCH_SIZE {
                let Some((&id, timer)) = candidates.next() else {
                    break;
                };
                batch.last_scanned_id = Some(id);
                if let Some(outcome) =
                    timer.poll_expiry(clocks.now(timer.deadline_clock_id), trigger)
                {
                    batch.push(outcome);
                }
            }
            batch.complete = candidates.next().is_none();
        }
        self.publish_armed_state(&timers);
        batch
    }
}

#[cfg(all(test, not(axtest)))]
fn posix_timer_clock_validation_rules_hold_for_test() -> bool {
    use linux_raw_sys::general::{
        CLOCK_BOOTTIME, CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, CLOCK_MONOTONIC_RAW,
        CLOCK_PROCESS_CPUTIME_ID, CLOCK_REALTIME, CLOCK_REALTIME_COARSE, CLOCK_THREAD_CPUTIME_ID,
    };

    // is_supported_timer_clock: only REALTIME, MONOTONIC, BOOTTIME are supported for timer_create.
    let supported = is_supported_timer_clock(CLOCK_REALTIME)
        && is_supported_timer_clock(CLOCK_MONOTONIC)
        && is_supported_timer_clock(CLOCK_BOOTTIME);
    let unsupported_raw = !is_supported_timer_clock(CLOCK_MONOTONIC_RAW);
    let unsupported_coarse = !is_supported_timer_clock(CLOCK_MONOTONIC_COARSE);
    let unsupported_coarse_rt = !is_supported_timer_clock(CLOCK_REALTIME_COARSE);
    let unknown = !is_supported_timer_clock(999);

    // is_valid_clock: broader set includes RAW/COARSE/CPU-time clocks.
    let valid_known = is_valid_clock(CLOCK_REALTIME)
        && is_valid_clock(CLOCK_REALTIME_COARSE)
        && is_valid_clock(CLOCK_MONOTONIC)
        && is_valid_clock(CLOCK_MONOTONIC_RAW)
        && is_valid_clock(CLOCK_MONOTONIC_COARSE)
        && is_valid_clock(CLOCK_BOOTTIME)
        && is_valid_clock(CLOCK_PROCESS_CPUTIME_ID)
        && is_valid_clock(CLOCK_THREAD_CPUTIME_ID);
    let invalid_unknown = !is_valid_clock(999);

    supported
        && unsupported_raw
        && unsupported_coarse
        && unsupported_coarse_rt
        && unknown
        && valid_known
        && invalid_unknown
}

#[cfg(axtest)]
fn posix_timer_active_gate_rules_hold_for_test() -> bool {
    let timers = PosixTimerTable::default();
    let Ok(id) = timers.create(CLOCK_MONOTONIC, SIGEV_NONE, 0, 0) else {
        return false;
    };
    if timers.has_armed_timers() {
        return false;
    }

    let armed = timers.settime(
        test_alarm_target(),
        id,
        0,
        TimerSpec {
            value_sec: 0,
            value_nsec: 1_000_000,
            interval_sec: 0,
            interval_nsec: 0,
        },
    );
    if armed.is_err() || !timers.has_armed_timers() {
        return false;
    }

    let disarmed = timers.settime(
        test_alarm_target(),
        id,
        0,
        TimerSpec {
            value_sec: 0,
            value_nsec: 0,
            interval_sec: 0,
            interval_nsec: 0,
        },
    );
    disarmed.is_ok() && !timers.has_armed_timers() && timers.delete(id)
}

#[cfg(axtest)]
fn posix_timer_clock_sampling_rules_hold_for_test() -> bool {
    use core::cell::Cell;

    let table = PosixTimerTable::default();
    {
        let mut timers = table.timers.lock();
        timers.insert(
            1,
            PosixTimer {
                clock_id: CLOCK_MONOTONIC,
                deadline_clock_id: CLOCK_MONOTONIC,
                signo: None,
                sigev_value: 0,
                interval_ns: 0,
                deadline_ns: 1,
                alarm_slot: AlarmSlot::new(),
            },
        );
        table.publish_armed_state(&timers);
    }

    let sampled_outside_metadata = Cell::new(false);
    table.poll_expired_at(
        test_alarm_target(),
        None,
        |_| {
            sampled_outside_metadata.set(table.timers.try_lock().is_some());
            2
        },
        |_| {},
    );
    sampled_outside_metadata.get()
}

#[cfg(axtest)]
fn posix_timer_saturating_timespec_rules_hold_for_test() -> bool {
    let table = PosixTimerTable::default();
    let Ok(id) = table.create(CLOCK_MONOTONIC, SIGEV_NONE, 0, 0) else {
        return false;
    };
    if table
        .settime(
            test_alarm_target(),
            id,
            1,
            TimerSpec {
                value_sec: i64::MAX,
                value_nsec: (NANOS_PER_SEC - 1) as i64,
                interval_sec: i64::MAX,
                interval_nsec: (NANOS_PER_SEC - 1) as i64,
            },
        )
        .is_err()
    {
        return false;
    }

    let timers = table.timers.lock();
    let Some(timer) = timers.get(&id) else {
        return false;
    };
    timer.deadline_ns == i64::MAX as u64 && timer.interval_ns == i64::MAX as u64
}

#[cfg(axtest)]
fn posix_timer_expiry_batch_rules_hold_for_test() -> bool {
    use core::cell::Cell;

    let table = PosixTimerTable::default();
    {
        let mut timers = table.timers.lock();
        for id in 0..=(EXPIRY_SCAN_BATCH_SIZE as i32) {
            timers.insert(
                id,
                PosixTimer {
                    clock_id: CLOCK_MONOTONIC,
                    deadline_clock_id: CLOCK_MONOTONIC,
                    signo: Some(Signo::SIGALRM),
                    sigev_value: id as i64,
                    interval_ns: 0,
                    deadline_ns: 1,
                    alarm_slot: AlarmSlot::new(),
                },
            );
        }
        table.publish_armed_state(&timers);
    }

    let emitted = Cell::new(0);
    let callbacks_outside_metadata = Cell::new(true);
    table.poll_expired_at(
        test_alarm_target(),
        None,
        |_| 2,
        |_| {
            callbacks_outside_metadata
                .set(callbacks_outside_metadata.get() && table.timers.try_lock().is_some());
            emitted.set(emitted.get() + 1);
        },
    );
    emitted.get() == EXPIRY_SCAN_BATCH_SIZE + 1
        && callbacks_outside_metadata.get()
        && !table.has_armed_timers()
}

#[cfg(axtest)]
fn posix_timer_stale_expiry_signal_is_suppressed_for_test() -> bool {
    use core::cell::Cell;

    let table = PosixTimerTable::default();
    {
        let mut timers = table.timers.lock();
        timers.insert(
            1,
            PosixTimer {
                clock_id: CLOCK_MONOTONIC,
                deadline_clock_id: CLOCK_MONOTONIC,
                signo: Some(Signo::SIGALRM),
                sigev_value: 7,
                interval_ns: 0,
                deadline_ns: 1,
                alarm_slot: AlarmSlot::new(),
            },
        );
        table.publish_armed_state(&timers);
    }

    let batch = table.collect_expiry_batch(
        None,
        1,
        None,
        TimerClockSnapshot {
            realtime: 2,
            monotonic: 2,
            boottime: 2,
        },
    );
    if batch.outcomes.len() != 1 {
        return false;
    }
    if table
        .settime(
            test_alarm_target(),
            1,
            0,
            TimerSpec {
                value_sec: 0,
                value_nsec: 0,
                interval_sec: 0,
                interval_nsec: 0,
            },
        )
        .is_err()
    {
        return false;
    }

    let emitted = Cell::new(0);
    batch.apply(test_alarm_target(), &mut |_| emitted.set(emitted.get() + 1));
    emitted.get() == 0
}

#[cfg(all(test, not(axtest)))]
mod tests {
    use super::{
        EXPIRY_SCAN_BATCH_SIZE, ExpiryOutcome, ExpiryScanBatch,
        posix_timer_clock_validation_rules_hold_for_test,
    };

    #[test]
    fn posix_timer_clock_validation_rules_hold() {
        assert!(posix_timer_clock_validation_rules_hold_for_test());
    }

    #[test]
    fn expiry_scan_uses_a_fixed_capacity_batch() {
        let batch = ExpiryScanBatch::new();
        let _: &heapless::Vec<ExpiryOutcome, { EXPIRY_SCAN_BATCH_SIZE }> = &batch.outcomes;
    }
}

#[cfg(all(test, axtest))]
mod axtests {
    #[axtest::axtest]
    fn posix_timer_active_gate_rules_hold() {
        assert!(super::posix_timer_active_gate_rules_hold_for_test());
    }

    #[axtest::axtest]
    fn posix_timer_clock_sampling_rules_hold() {
        assert!(super::posix_timer_clock_sampling_rules_hold_for_test());
    }

    #[axtest::axtest]
    fn posix_timer_saturating_timespec_rules_hold() {
        assert!(super::posix_timer_saturating_timespec_rules_hold_for_test());
    }

    #[axtest::axtest]
    fn posix_timer_expiry_batch_rules_hold() {
        assert!(super::posix_timer_expiry_batch_rules_hold_for_test());
    }

    #[axtest::axtest]
    fn posix_timer_stale_expiry_signal_is_suppressed() {
        assert!(super::posix_timer_stale_expiry_signal_is_suppressed_for_test());
    }
}