mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
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
//! Placement readings: special user-mode APCs that report the processor a thread runs on.
//!
//! An APC queued with `QueueUserAPC2(QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC)` runs on the target
//! thread at any point of its user-mode code, like a signal, or when the thread next returns
//! to user mode. It cannot be cancelled once queued, and it may run after the sampler stopped.
//! So its context is never heap memory: it is an index into a static table of atomics, and a
//! slot of that table is never handed out again while an APC aimed at it may still run.
//!
//! The invariant, per slot: at most one APC is outstanding (queued and not yet delivered), and
//! only that APC writes the slot's `tsc` and `word`. A slot becomes free again when its APC
//! delivered (`word` carries the queued sequence number), or when the thread it was queued to
//! has exited (an exited thread runs no APC). Until then the slot is quarantined: it keeps the
//! thread handle so a later sampler can see the exit, and no sampler leases it.
//!
//! Sequence numbers come from one process-wide counter that never resets, so a late APC from
//! an earlier run can never be mistaken for the current one. A slot that settles forgets its
//! last sequence number, so the next thread to lease it cannot inherit a reading.
//!
//! The APC routine and the table live in the module that holds this crate, which may be a DLL
//! the host could unload while an APC is still queued. Before the first APC is queued that
//! module is pinned for the life of the process (`GET_MODULE_HANDLE_EX_FLAG_PIN`); if the pin
//! fails, placement is reported unavailable and no APC is ever queued.

use std::ffi::c_void;
use std::os::windows::io::{IntoRawHandle, OwnedHandle};
use std::ptr::null_mut;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use windows_sys::Win32::Foundation::{GetLastError, HANDLE, HMODULE, PAPCFUNC};
use windows_sys::Win32::System::Kernel::PROCESSOR_NUMBER;
use windows_sys::Win32::System::LibraryLoader::{
    GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN, GetModuleHandleExW,
};
use windows_sys::Win32::System::SystemInformation::GetSystemCpuSetInformation;
use windows_sys::Win32::System::Threading::{
    GetCurrentProcessorNumberEx, QUEUE_USER_APC_FLAGS, QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC,
};
use windows_sys::Win32::System::WindowsProgramming::QueryThreadCycleTime;
use windows_sys::core::BOOL;

use super::{Target, sys};
use crate::placement::placement_stride;
use crate::{Config, PlacedThread, Placement, Reading, parse_cpu_sets};

/// Placement slots: at most this many threads are read at once (fits the 8-bit slot field).
pub(super) const SLOTS: usize = 128;
/// Sequence numbers are 48 bits: `seq << 16 | processor` fills a `u64`. At 128 slots and
/// 200 readings a second each they last for centuries.
const SEQ_MASK: u64 = (1 << 48) - 1;
/// How long a stopping sampler waits for readings still in flight.
const DRAIN: Duration = Duration::from_millis(25);

struct Slot {
    /// `seq << 16 | processor`, written last by the APC (release).
    word: AtomicU64,
    /// The time stamp counter, written by the APC before `word`.
    tsc: AtomicU64,
    /// The sequence number of the last APC queued to this slot (0: none yet).
    queued: AtomicU64,
    /// Held by a target of the running sampler.
    leased: AtomicBool,
    /// While quarantined: the thread the outstanding APC was queued to (an owned handle).
    thread: AtomicPtr<c_void>,
}

static TABLE: [Slot; SLOTS] = [const {
    Slot {
        word: AtomicU64::new(0),
        tsc: AtomicU64::new(0),
        queued: AtomicU64::new(0),
        leased: AtomicBool::new(false),
        thread: AtomicPtr::new(null_mut()),
    }
}; SLOTS];

static NEXT_SEQ: AtomicU64 = AtomicU64::new(1);

fn next_seq() -> u64 {
    loop {
        let seq = NEXT_SEQ.fetch_add(1, Ordering::Relaxed) & SEQ_MASK;
        if seq != 0 {
            return seq;
        }
    }
}

fn slot(index: usize) -> Option<&'static Slot> {
    TABLE.get(index)
}

/// Whether the slot's last APC delivered (or none was queued).
fn delivered(slot: &Slot) -> bool {
    let queued = slot.queued.load(Ordering::Acquire);
    queued == 0 || slot.word.load(Ordering::Acquire) >> 16 == queued
}

/// Close the quarantine handle, if any.
fn forget_thread(slot: &Slot) {
    let handle = slot.thread.swap(null_mut(), Ordering::AcqRel);
    // SAFETY: a non-null value was stored by `release` from `OwnedHandle::into_raw_handle`
    // and the swap takes it out exactly once.
    drop(unsafe { sys::owned(handle) });
}

/// Whether no APC aimed at the slot can still run; settles a quarantined slot whose APC
/// delivered or whose thread exited. A settled slot holds no sequence number, so a delivered
/// reading of its last thread is never taken by the next one.
fn settle(slot: &Slot) -> bool {
    let handle = slot.thread.load(Ordering::Acquire);
    if delivered(slot) || (!handle.is_null() && sys::has_exited(handle)) {
        forget_thread(slot);
        slot.queued.store(0, Ordering::Release);
        return true;
    }
    false
}

/// Lease a slot no APC can still write. Only the running sampler leases (there is one).
pub(super) fn lease() -> Option<usize> {
    TABLE.iter().enumerate().find_map(|(index, slot)| {
        let free = !slot.leased.load(Ordering::Acquire) && settle(slot);
        (free
            && slot
                .leased
                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                .is_ok())
        .then_some(index)
    })
}

/// Give a slot back with the handle of the thread it served. With an APC still outstanding
/// on a live thread the slot is quarantined and keeps the handle.
pub(super) fn release(index: usize, thread: OwnedHandle) {
    let Some(slot) = slot(index) else { return };
    if delivered(slot) || sys::has_exited(sys::raw(&thread)) {
        slot.queued.store(0, Ordering::Release);
    } else {
        slot.thread
            .store(thread.into_raw_handle(), Ordering::Release);
    }
    slot.leased.store(false, Ordering::Release);
}

/// Whether the slot's APC is still outstanding.
pub(super) fn outstanding(index: usize) -> bool {
    slot(index).is_some_and(|slot| !delivered(slot))
}

/// The reading delivered to the slot since `seen`, as `(processor, tsc)`; `seen` advances.
fn take(index: usize, seen: &mut u64) -> Option<(u32, u64)> {
    let slot = slot(index)?;
    let queued = slot.queued.load(Ordering::Acquire);
    if queued == 0 || queued == *seen {
        return None;
    }
    let word = slot.word.load(Ordering::Acquire);
    if word >> 16 != queued {
        return None;
    }
    // The APC stored `tsc` before its release store of `word`, and no other writer exists
    // until the next APC is queued (after this read).
    let tsc = slot.tsc.load(Ordering::Relaxed);
    *seen = queued;
    Some((u32::try_from(word & 0xffff).unwrap_or(u32::MAX), tsc))
}

fn read_tsc() -> u64 {
    // SAFETY: RDTSC has no preconditions on x86-64.
    unsafe { std::arch::x86_64::_rdtsc() }
}

/// The APC. It runs on the watched thread wherever that thread was, so it reads the
/// processor number and the counter and stores two atomics of a static slot: no lock, no
/// allocation, no panic, no reference to anything a sampler owns.
extern "system" fn report_processor(data: usize) {
    let Some(slot) = slot(data & 0xff) else {
        return;
    };
    let seq = (data as u64 >> 8) & SEQ_MASK;
    let mut number = PROCESSOR_NUMBER {
        Group: 0,
        Number: 0,
        Reserved: 0,
    };
    // SAFETY: `number` is a writable PROCESSOR_NUMBER.
    unsafe { GetCurrentProcessorNumberEx(&raw mut number) };
    let processor = u64::from(number.Group) * 64 + u64::from(number.Number);
    slot.tsc.store(read_tsc(), Ordering::Relaxed);
    slot.word
        .store((seq << 16) | (processor & 0xffff), Ordering::Release);
}

/// Pin the module holding the APC routine and the slot table for the life of the process,
/// once. The error says why it could not be pinned.
fn pin_module() -> Result<(), String> {
    static PINNED: OnceLock<Result<(), u32>> = OnceLock::new();
    let result = *PINNED.get_or_init(|| {
        let routine: extern "system" fn(usize) = report_processor;
        let mut module: HMODULE = null_mut();
        // SAFETY: with GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS the name argument is only an
        // address inside the module to find (the APC routine's), never read as a string;
        // `module` is a writable out-pointer. GET_MODULE_HANDLE_EX_FLAG_PIN keeps the module
        // loaded until the process ends, so no handle is owned or freed here.
        let ok = unsafe {
            GetModuleHandleExW(
                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
                (routine as *const ()).cast::<u16>(),
                &raw mut module,
            )
        } != 0;
        if ok && !module.is_null() {
            Ok(())
        } else {
            // SAFETY: no arguments; reads this thread's last error.
            Err(unsafe { GetLastError() })
        }
    });
    result.map_err(|code| {
        format!("the module holding the placement APC could not be pinned (error {code})")
    })
}

/// `kernel32!QueueUserAPC2` (Windows 11 and later), looked up at run time so the crate still
/// loads on older systems.
type QueueApc2 = unsafe extern "system" fn(PAPCFUNC, HANDLE, usize, QUEUE_USER_APC_FLAGS) -> BOOL;

fn queue_apc2() -> Option<QueueApc2> {
    let address = sys::export("kernel32.dll", c"QueueUserAPC2")?;
    // SAFETY: kernel32 exports QueueUserAPC2(PAPCFUNC, HANDLE, ULONG_PTR, QUEUE_USER_APC_FLAGS)
    // -> BOOL with the system calling convention; function pointers have one size.
    Some(unsafe { std::mem::transmute::<unsafe extern "system" fn() -> isize, QueueApc2>(address) })
}

/// Queue the next APC to the slot's thread, if the last one delivered and its reading was
/// taken: `seen` is the sequence number of the last reading the target took. An APC can deliver
/// after the pass collected and before it queues; its reading waits for the next pass.
fn queue(apc: QueueApc2, index: usize, thread: HANDLE, seen: u64) -> bool {
    let Some(slot) = slot(index) else {
        return false;
    };
    let last = slot.queued.load(Ordering::Acquire);
    if !delivered(slot) || (last != 0 && last != seen) {
        return false;
    }
    let seq = next_seq();
    // 48 bits, so the shift below keeps it whole in a 64-bit usize.
    #[allow(clippy::cast_possible_truncation)]
    let seq_bits = seq as usize;
    // SAFETY: `report_processor` touches only the static table and has no preconditions;
    // `thread` has THREAD_SET_CONTEXT; a failed call queues nothing. The slot index (< 128)
    // fits the low 8 bits and the sequence number the 48 above them.
    let queued = unsafe {
        apc(
            Some(report_processor),
            thread,
            (seq_bits << 8) | index,
            QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC,
        )
    } != 0;
    if queued {
        // Stored after the call: until now the slot showed delivered, and only this thread
        // reads `queued`.
        slot.queued.store(seq, Ordering::Release);
    }
    queued
}

/// The logical processors (empty if the query fails).
fn cpu_sets() -> Vec<crate::Cpu> {
    let mut length = 0_u32;
    // SAFETY: a null buffer of length 0 asks for the size, written to `length`.
    unsafe { GetSystemCpuSetInformation(null_mut(), 0, &raw mut length, null_mut(), 0) };
    if length == 0 {
        return Vec::new();
    }
    // u64 words keep the entries 8-byte aligned.
    let mut buffer = vec![0_u64; (length as usize).div_ceil(8)];
    // SAFETY: `buffer` holds at least `length` writable bytes, aligned for the entries.
    let ok = unsafe {
        GetSystemCpuSetInformation(
            buffer.as_mut_ptr().cast(),
            length,
            &raw mut length,
            null_mut(),
            0,
        )
    } != 0;
    if !ok {
        return Vec::new();
    }
    let bytes: Vec<u8> = buffer.iter().flat_map(|word| word.to_le_bytes()).collect();
    parse_cpu_sets(bytes.get(..length as usize).unwrap_or_default())
}

/// The placement state of the sampler thread.
pub(super) struct Placer {
    queue: QueueApc2,
    /// Readings are asked for every `stride` passes.
    stride: u64,
    placement: Placement,
    /// The time and counter at the first and the latest pass that asked (the readings span
    /// this, so a sampling window is honoured).
    first: Option<(Instant, u64)>,
    latest: Option<(Instant, u64)>,
}

impl Placer {
    pub(super) fn new(config: &Config) -> Result<Self, String> {
        let queue = queue_apc2().ok_or("QueueUserAPC2 is missing (Windows 11 or later needed)")?;
        // Before any APC can be queued: a queued APC may run after this module would unload.
        pin_module()?;
        let cpus = cpu_sets();
        if cpus.is_empty() {
            return Err("GetSystemCpuSetInformation gave no processors".to_owned());
        }
        let mut placement = Placement {
            cpus,
            ..Placement::default()
        };
        placement.highlight_threads = config.highlight_threads().to_vec();
        placement.busiest_threads = config.busiest_threads();
        Ok(Self {
            queue,
            stride: placement_stride(config.hz()),
            placement,
            first: None,
            latest: None,
        })
    }

    /// Lease slots for targets without one; a target read for the first time gets its own
    /// entry in the placement's thread list.
    pub(super) fn assign(&mut self, targets: &mut [Target]) {
        for target in targets.iter_mut().filter(|target| target.slot.is_none()) {
            let Some(index) = lease() else {
                break;
            };
            target.slot = Some(index);
            target.seen = 0;
            if target.placed.is_none() {
                target.placed = Some(self.placement.threads.len());
                self.placement
                    .threads
                    .push(PlacedThread::new(target.name.clone(), target.tid));
            }
        }
    }

    fn collect(&mut self, target: &mut Target) {
        if let (Some(index), Some(thread)) = (target.slot, target.placed)
            && let Some((cpu, tsc)) = take(index, &mut target.seen)
        {
            self.placement.readings.push(Reading { thread, cpu, tsc });
        }
    }

    /// Collect the delivered readings and queue the next APCs (every `stride` passes).
    pub(super) fn pass(&mut self, pass: u64, targets: &mut [Target]) {
        if !pass.is_multiple_of(self.stride) {
            return;
        }
        let now = (Instant::now(), read_tsc());
        self.first.get_or_insert(now);
        self.latest = Some(now);
        for target in targets.iter_mut() {
            let Some(index) = target.slot else { continue };
            self.collect(target);
            let mut cycles = 0_u64;
            // SAFETY: the handle has THREAD_QUERY_LIMITED_INFORMATION; `cycles` is writable.
            if unsafe { QueryThreadCycleTime(target.raw, &raw mut cycles) } != 0 {
                if let (Some(previous), Some(thread)) = (target.place_cycles, target.placed) {
                    let used = self.placement.cycles.entry(thread).or_default();
                    *used = used.saturating_add(cycles.saturating_sub(previous));
                }
                target.place_cycles = Some(cycles);
            }
            queue(self.queue, index, target.raw, target.seen);
        }
    }

    /// Wait briefly for readings in flight, collect them, and return the placement. The
    /// targets' slots are released (or quarantined) when the targets drop.
    pub(super) fn finish(mut self, targets: &mut [Target]) -> Placement {
        let deadline = Instant::now() + DRAIN;
        while Instant::now() < deadline
            && targets
                .iter()
                .any(|target| target.slot.is_some_and(outstanding) && !sys::has_exited(target.raw))
        {
            std::thread::sleep(Duration::from_millis(1));
        }
        for target in targets.iter_mut() {
            self.collect(target);
        }
        self.placement.pending_at_stop = targets
            .iter()
            .filter(|target| target.slot.is_some_and(outstanding))
            .count();
        let (seconds, ticks) = match (self.first, self.latest) {
            (Some((t0, c0)), Some((t1, c1))) => (
                t1.saturating_duration_since(t0).as_secs_f64(),
                c1.saturating_sub(c0),
            ),
            _ => (0.0, 0),
        };
        self.placement.wall = seconds;
        self.placement.tsc_hz = if seconds > 0.0 {
            ticks as f64 / seconds
        } else {
            0.0
        };
        self.placement
    }
}

/// The handle a quarantined slot keeps, if any.
#[cfg(test)]
fn quarantined_handle(index: usize) -> Option<HANDLE> {
    slot(index)
        .map(|slot| slot.thread.load(Ordering::Acquire))
        .filter(|handle| !handle.is_null())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::windows::io::{AsRawHandle, FromRawHandle};
    use std::sync::Arc;
    use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle};
    use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThread};

    /// Tests that use the slot table run one at a time.
    static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn one() -> std::sync::MutexGuard<'static, ()> {
        ONE.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn duplicate(handle: HANDLE) -> OwnedHandle {
        let mut copy: HANDLE = null_mut();
        // SAFETY: duplicates a live handle of this process into a writable out-pointer.
        let ok = unsafe {
            DuplicateHandle(
                GetCurrentProcess(),
                handle,
                GetCurrentProcess(),
                &raw mut copy,
                0,
                0,
                DUPLICATE_SAME_ACCESS,
            )
        };
        assert_ne!(ok, 0);
        // SAFETY: a fresh handle this test owns.
        unsafe { sys::owned(copy) }.unwrap()
    }

    fn current_thread() -> OwnedHandle {
        // SAFETY: the pseudo-handle of the calling thread is always valid.
        duplicate(unsafe { GetCurrentThread() })
    }

    #[test]
    fn sequence_numbers_skip_zero_and_stay_in_48_bits() {
        for _ in 0..1000 {
            let seq = next_seq();
            assert_ne!(seq, 0);
            assert_eq!(seq & !SEQ_MASK, 0);
        }
    }

    #[test]
    fn the_apc_body_writes_only_its_slot() {
        let _one = one();
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        slot.queued.store(77, Ordering::Release);
        assert!(outstanding(index));
        report_processor((77 << 8) | index);
        assert!(!outstanding(index));
        let mut seen = 0;
        let (cpu, _) = take(index, &mut seen).unwrap();
        assert!(cpu < 64 * 32);
        assert_eq!(seen, 77);
        assert_eq!(take(index, &mut seen), None, "a reading is taken once");
        // Data naming a slot outside the table is ignored.
        report_processor(0xff);
        release(index, current_thread());
    }

    #[test]
    fn a_stale_reading_is_not_taken() {
        let _one = one();
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        slot.queued.store(500, Ordering::Release);
        // An APC from an earlier queue (sequence 499) arrives late.
        report_processor((499 << 8) | index);
        let mut seen = 0;
        assert_eq!(take(index, &mut seen), None);
        assert!(outstanding(index));
        report_processor((500 << 8) | index);
        assert!(take(index, &mut seen).is_some());
        release(index, current_thread());
    }

    #[test]
    fn an_outstanding_slot_is_quarantined_until_its_thread_exits() {
        let _one = one();
        let stop = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&stop);
        let worker = std::thread::spawn(move || {
            while !flag.load(Ordering::Acquire) {
                std::thread::sleep(Duration::from_millis(1));
            }
        });
        let handle = duplicate(worker.as_raw_handle());
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        // An APC was queued and has not delivered.
        slot.queued.store(next_seq(), Ordering::Release);
        release(index, handle);
        assert!(
            quarantined_handle(index).is_some(),
            "the thread handle is kept"
        );
        assert!(!settle(slot));
        // Not leased again while quarantined.
        let mut leased = Vec::new();
        while let Some(other) = lease() {
            assert_ne!(other, index);
            leased.push(other);
        }
        stop.store(true, Ordering::Release);
        worker.join().unwrap();
        // Exited: the APC can never run, so the slot settles and the handle is closed.
        assert!(settle(slot));
        assert!(quarantined_handle(index).is_none());
        for other in leased {
            release(other, current_thread());
        }
        let again = lease().unwrap();
        release(again, current_thread());
    }

    #[test]
    fn a_reclaimed_slot_hands_no_reading_to_its_next_thread() {
        let _one = one();
        let stop = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&stop);
        let worker = std::thread::spawn(move || {
            while !flag.load(Ordering::Acquire) {
                std::thread::sleep(Duration::from_millis(1));
            }
        });
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        let seq = next_seq();
        slot.queued.store(seq, Ordering::Release);
        // The first thread stops being watched with its APC still outstanding: quarantined.
        release(index, duplicate(worker.as_raw_handle()));
        assert!(quarantined_handle(index).is_some());
        // The late APC delivers a reading for the first thread.
        report_processor((usize::try_from(seq).unwrap() << 8) | index);
        // The slot is reclaimed for another thread, which starts from nothing seen.
        assert!(settle(slot));
        assert_eq!(slot.queued.load(Ordering::Acquire), 0);
        assert!(quarantined_handle(index).is_none());
        let mut seen = 0;
        assert_eq!(
            take(index, &mut seen),
            None,
            "the old reading stays with the old thread"
        );
        // The same through lease: settle a delivered quarantined slot, lease, take nothing.
        let again = lease().unwrap();
        let mut seen = 0;
        assert_eq!(take(again, &mut seen), None);
        release(again, current_thread());
        stop.store(true, Ordering::Release);
        worker.join().unwrap();
    }

    #[test]
    fn the_apc_module_is_pinned_once() {
        assert_eq!(pin_module(), Ok(()));
        assert_eq!(pin_module(), Ok(()), "cached");
    }

    #[test]
    fn a_delivered_slot_is_free_at_once() {
        let _one = one();
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        slot.queued.store(next_seq(), Ordering::Release);
        let seq = slot.queued.load(Ordering::Acquire);
        report_processor((usize::try_from(seq).unwrap() << 8) | index);
        release(index, current_thread());
        assert!(quarantined_handle(index).is_none());
        assert!(settle(slot));
    }

    /// Stands in for `QueueUserAPC2`: accepts the APC and queues nothing.
    extern "system" fn accept(_: PAPCFUNC, _: HANDLE, _: usize, _: QUEUE_USER_APC_FLAGS) -> BOOL {
        1
    }

    #[test]
    fn a_reading_delivered_between_collect_and_queue_is_kept() {
        let _one = one();
        let index = lease().unwrap();
        let slot = slot(index).unwrap();
        let thread = current_thread();
        let mut seen = 0;
        assert!(queue(accept, index, sys::raw(&thread), seen));
        let first = slot.queued.load(Ordering::Acquire);
        // The pass collects while the APC is still pending.
        assert_eq!(take(index, &mut seen), None);
        // The APC delivers, say during the cycle-time query that follows.
        report_processor((usize::try_from(first).unwrap() << 8) | index);
        // The pass then queues: the reading nobody took yet must not be replaced.
        assert!(!queue(accept, index, sys::raw(&thread), seen));
        assert_eq!(slot.queued.load(Ordering::Acquire), first);
        // The next pass takes it, then queues again.
        assert!(take(index, &mut seen).is_some());
        assert_eq!(seen, first);
        assert!(queue(accept, index, sys::raw(&thread), seen));
        let second = slot.queued.load(Ordering::Acquire);
        assert_ne!(second, first);
        assert_eq!(take(index, &mut seen), None, "the new one is pending");
        report_processor((usize::try_from(second).unwrap() << 8) | index);
        assert!(take(index, &mut seen).is_some());
        release(index, thread);
        assert!(quarantined_handle(index).is_none());
    }

    #[test]
    fn the_cpu_set_query_matches_this_machine() {
        let cpus = cpu_sets();
        assert_ne!(cpus.len(), 0);
        let logical = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
        assert!(cpus.len() >= logical.min(64), "{} < {logical}", cpus.len());
    }

    /// A special APC queued to a spinning thread runs on it and reports a processor this
    /// machine has.
    #[test]
    fn apc_reports_the_running_processor() {
        let _one = one();
        let Some(apc) = queue_apc2() else {
            // Older than Windows 11: placement reports itself unavailable.
            return;
        };
        let cpus = cpu_sets();
        let stop = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&stop);
        let worker = std::thread::spawn(move || {
            while !flag.load(Ordering::Acquire) {
                std::hint::spin_loop();
            }
        });
        let handle = duplicate(worker.as_raw_handle());
        let index = lease().unwrap();
        assert!(queue(apc, index, sys::raw(&handle), 0));
        assert!(
            !queue(apc, index, sys::raw(&handle), 0),
            "one in flight, and its reading not yet taken"
        );
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut seen = 0;
        let mut reading = None;
        while reading.is_none() && Instant::now() < deadline {
            reading = take(index, &mut seen);
            std::thread::yield_now();
        }
        stop.store(true, Ordering::Release);
        worker.join().unwrap();
        release(index, handle);
        let (cpu, tsc) = reading.expect("the APC ran");
        assert!(tsc > 0);
        assert!(
            cpus.iter().any(|known| known.index == cpu),
            "processor {cpu}"
        );
    }

    #[test]
    fn owned_handles_round_trip() {
        let handle = current_thread();
        let raw = handle.into_raw_handle();
        // SAFETY: `raw` was just released from an OwnedHandle.
        let back = unsafe { OwnedHandle::from_raw_handle(raw) };
        assert!(!sys::has_exited(sys::raw(&back)));
    }
}