Skip to main content

ostd/cpu/
set.rs

1// SPDX-License-Identifier: MPL-2.0
2//! This module contains the implementation of the CPU set and atomic CPU set.
3use vstd::{
4    arithmetic::div_mod::lemma_fundamental_div_mod_converse,
5    assert_seqs_equal,
6    layout::size_of,
7    prelude::*,
8    set::Set,
9    std_specs::{bits::axiom_u64_count_ones, iter::IteratorSpec},
10};
11use vstd_extra::{
12    bits::{group_u64_bit_algebra, lemma_u64_and_zero, u64_bit_is_set},
13    external::smallvec::{axiom_smallvec_from_iter_ensures, group_smallvec_models, smallvec_view},
14    ownership::Inv,
15};
16
17use super::cpu_count;
18use core::sync::atomic::{AtomicU64, Ordering};
19
20use smallvec::SmallVec;
21
22use super::{CpuId, num_cpus};
23use crate::const_assert;
24
25/// A subset of all CPUs in the system.
26#[derive(Clone, Debug, Default)]
27#[verifier::allow(autoderive_clone_without_spec)]
28#[verus_verify]
29pub struct CpuSet {
30    // A bitset representing the CPUs in the system.
31    bits: SmallVec<[InnerPart; NR_PARTS_NO_ALLOC]>,
32}
33
34type InnerPart = u64;
35
36// Original exec: `const BITS_PER_PART: usize = core::mem::size_of::<InnerPart>() * 8;`
37// literalized to `64` inside `verus!` so Verus sees a known value (exec `% BITS_PER_PART` ↔ spec `% 64`).
38#[verus_verify]
39const BITS_PER_PART: usize = 64;
40
41#[verus_verify]
42const NR_PARTS_NO_ALLOC: usize = 2;
43
44#[verus_spec(
45    returns part_idx_spec(cpu_id@),
46)]
47const fn part_idx(cpu_id: CpuId) -> usize {
48    cpu_id.as_usize() / BITS_PER_PART
49}
50
51#[verus_verify]
52#[verus_spec(
53    returns bit_idx_spec(cpu_id@),
54)]
55const fn bit_idx(cpu_id: CpuId) -> usize {
56    cpu_id.as_usize() % BITS_PER_PART
57}
58
59#[verus_verify]
60#[verifier::when_used_as_spec(parts_for_cpus_spec)]
61#[verus_spec(
62    returns parts_for_cpus_spec(num_cpus),
63)]
64const fn parts_for_cpus(num_cpus: usize) -> usize {
65    num_cpus.div_ceil(BITS_PER_PART)
66}
67
68verus! {
69
70broadcast use {
71    group_smallvec_models,
72    axiom_smallvec_from_iter_ensures,
73    vstd::std_specs::iter::group_iter_axioms,
74    axiom_u64_count_ones,
75    group_u64_bit_algebra,
76    crate::cpu::axiom_cpu_count_bounds,
77    vstd::layout::layout_of_primitives,
78    vstd::set::group_set_lemmas,
79    vstd::set_lib::range_set_properties,
80};
81
82/// Bit `i` is set in the bit sequence `seq`.
83spec fn bit_at(seq: Seq<u64>, i: int) -> bool {
84    if 0 <= i < 64 * seq.len() {
85        u64_bit_is_set(seq[part_idx_spec(i) as int], i % 64)
86    } else {
87        false
88    }
89}
90
91impl View for CpuSet {
92    type V = Set<int>;
93
94    /// The set of CPU ids whose bit is set in `bits` (and below `cpu_count()`).
95    closed spec fn view(&self) -> Set<int> {
96        Set::range(0, cpu_count()).filter(|i: int| bit_at(smallvec_view(&self.bits), i))
97    }
98}
99
100impl CpuSet {
101    /// Number of set bits in the backing words.
102    pub closed spec fn count_spec(&self) -> int {
103        count_set_bits(smallvec_view(&self.bits))
104    }
105
106    /// Number of backing words.
107    pub closed spec fn num_parts(&self) -> nat {
108        smallvec_view(&self.bits).len()
109    }
110}
111
112impl Inv for CpuSet {
113    /// The backing vector holds exactly `parts_for_cpus(cpu_count)` words, the view
114    /// is bounded by `cpu_count`, and the unused tail bits (>= `cpu_count`) are clear.
115    closed spec fn inv(self) -> bool {
116        &&& smallvec_view(&self.bits).len() == parts_for_cpus(cpu_count() as usize)
117        &&& forall|j: int|
118            #![trigger bit_at(smallvec_view(&self.bits), j)]
119            cpu_count() <= j < 64 * smallvec_view(&self.bits).len() ==> !bit_at(
120                smallvec_view(&self.bits),
121                j,
122            )
123    }
124}
125
126} // verus!
127#[verus_verify]
128impl CpuSet {
129    /// Creates a new `CpuSet` with all CPUs in the system.
130    #[verus_spec(ret =>
131        ensures
132            ret@ == Set::range(0, cpu_count()),
133            ret.inv(),
134    )]
135    pub fn new_full() -> Self {
136        let mut ret = Self::with_capacity_val(num_cpus(), !0);
137        ret.clear_nonexistent_cpu_bits();
138        ret
139    }
140
141    /// Creates a new `CpuSet` with no CPUs in the system.
142    #[verus_spec(ret =>
143        ensures
144            ret@ == Set::empty(),
145            ret.inv(),
146    )]
147    pub fn new_empty() -> Self {
148        let ret = Self::with_capacity_val(num_cpus(), 0);
149        proof! {
150            lemma_empty_bits_imply_empty_set(&ret);
151            assert forall|j: int|
152                cpu_count() <= j < 64 * smallvec_view(&ret.bits).len() implies !bit_at(
153                    smallvec_view(&ret.bits),
154                    j,
155                ) by {
156                lemma_u64_and_zero(1u64 << bit_idx_spec(j));
157            }
158        }
159        ret
160    }
161
162    /// Adds a CPU to the set.
163    #[verus_spec(
164        requires
165            self.inv(),
166        ensures
167            final(self)@ == old(self)@.insert(cpu_id@),
168            final(self).inv(),
169    )]
170    pub fn add(&mut self, cpu_id: CpuId) {
171        proof! {
172            use_type_invariant(&cpu_id);
173        }
174        let part_idx = part_idx(cpu_id);
175        let bit_idx = bit_idx(cpu_id);
176        if part_idx >= self.bits.len() {
177            self.bits.resize(part_idx + 1, 0);
178        }
179        self.bits[part_idx] |= 1 << bit_idx;
180        proof! {
181            let old_seq = smallvec_view(&old(self).bits);
182            let new_seq = smallvec_view(&self.bits);
183            let len = old_seq.len();
184            assert forall|j: int| cpu_count() <= j < 64 * len implies !bit_at(new_seq, j) by {
185                assert(bit_at(new_seq, j) == bit_at(old_seq, j));
186            }
187        }
188    }
189
190    /// Removes a CPU from the set.
191    #[verus_spec(
192        requires
193            self.inv(),
194        ensures
195            final(self)@ == old(self)@.remove(cpu_id@),
196            final(self).inv(),
197    )]
198    pub fn remove(&mut self, cpu_id: CpuId) {
199        let part_idx = part_idx(cpu_id);
200        let bit_idx = bit_idx(cpu_id);
201        if part_idx < self.bits.len() {
202            self.bits[part_idx] &= !(1 << bit_idx);
203            proof! {
204                let old_seq = smallvec_view(&old(self).bits);
205                let new_seq = smallvec_view(&self.bits);
206                assert forall|j: int| cpu_count() <= j < 64 * old_seq.len() implies !bit_at(
207                    new_seq,
208                    j,
209                ) by {
210                    assert(bit_at(new_seq, j) == bit_at(old_seq, j));
211                }
212            }
213        }
214    }
215
216    /// Returns true if the set contains the specified CPU.
217    #[verus_spec(ret =>
218        requires
219            self.inv(),
220        returns self@.contains(cpu_id@),
221    )]
222    pub fn contains(&self, cpu_id: CpuId) -> bool {
223        proof! {
224            use_type_invariant(&cpu_id);
225        }
226        let part_idx = part_idx(cpu_id);
227        let bit_idx = bit_idx(cpu_id);
228        part_idx < self.bits.len() && (self.bits[part_idx] & (1 << bit_idx)) != 0
229    }
230
231    /// Returns the number of CPUs in the set.
232    #[verus_spec(
233        requires
234            self.inv(),
235        returns self.count_spec() as usize,
236    )]
237    pub fn count(&self) -> usize {
238        /* `Iterator::sum` has no model in the active vstd, so use an indexed loop with a
239         * prefix-sum invariant while preserving the same word order and arithmetic.
240         * Origin Rust: self.bits
241         *     .iter()
242         *     .map(|part| part.count_ones() as usize)
243         *     .sum()
244         */
245        let mut count = 0usize;
246        let mut idx = 0usize;
247        #[verus_spec(
248            invariant
249                self.inv(),
250                idx <= smallvec_view(&self.bits).len(),
251                count == smallvec_view(&self.bits)[..idx].fold_left(
252                    0,
253                    |count: int, word: u64| count + word.count_ones(),
254                ),
255                count <= 64 * idx,
256            decreases
257                smallvec_view(&self.bits).len() - idx,
258        )]
259        while idx < self.bits.len() {
260            let part = self.bits[idx];
261            let part_count = part.count_ones() as usize;
262            proof! {
263                let seq = smallvec_view(&self.bits);
264                assert_seqs_equal!(
265                    seq[..idx + 1].drop_last() == seq[..idx]
266                );
267            }
268            count += part_count;
269            idx += 1;
270        }
271        count
272    }
273
274    /// Returns true if the set is empty.
275    #[verus_spec(ret =>
276        requires
277            self.inv(),
278        returns self@ == Set::empty(),
279    )]
280    pub fn is_empty(&self) -> bool {
281        /* Bind the result as `ret` so the spec and the proof below can refer to it.
282         * Origin Rust: self.bits.iter().all(|part| *part == 0)
283         */
284        let ret = self.bits.iter().all(
285            #[verus_spec(ret: bool => ensures ret == (*part == 0u64))]
286            |part| *part == 0,
287        );
288        proof! {
289            let seq = smallvec_view(&self.bits);
290            if ret {
291                assert forall|i: int|
292                    0 <= i < smallvec_view(&self.bits).len() implies
293                        smallvec_view(&self.bits)[i] == 0u64 by {
294                    assert(*seq.as_ref()[i] == seq[i]);
295                }
296                lemma_empty_bits_imply_empty_set(self);
297            } else {
298                let idx = choose|i: int| 0 <= i < seq.len() && seq[i] != 0u64;
299                lemma_u64_nonzero_has_set_bit(seq[idx]);
300                let b = choose|b: int| 0 <= b < 64 && #[trigger] u64_bit_is_set(seq[idx], b);
301                let j = 64 * idx + b;
302                lemma_fundamental_div_mod_converse(j, 64, idx, b);
303                assert(bit_at(seq, j));
304                assert(self@.contains(j));
305            }
306        }
307        ret
308    }
309
310    /// Returns true if the set is full.
311    #[verus_spec(ret =>
312        requires
313            self.inv(),
314        returns self@ == Set::range(0, cpu_count()),
315    )]
316    pub fn is_full(&self) -> bool {
317        let num_cpus = num_cpus();
318        proof! {
319            let seq = smallvec_view(&self.bits);
320            if forall|i: int| 0 <= i < seq.len() ==> #[trigger] seq[i]
321                == full_set_word(cpu_count(), seq.len() as int, i) {
322                lemma_full_bits_imply_full_set(self);
323            } else {
324                let idx = choose|i: int| 0 <= i < seq.len()
325                    && #[trigger] seq[i] != full_set_word(cpu_count(), seq.len() as int, i);
326                lemma_mismatched_word_imply_not_full_set(self, idx);
327            }
328        }
329        self.bits.iter().enumerate().all(
330            #[verus_spec(ret: bool =>
331                ensures
332                    ret == (*part == full_set_word(
333                        cpu_count(), smallvec_view(&self.bits).len() as int, idx as int,
334                    )),
335            )]
336            |(idx, part): (usize, &InnerPart)| {
337                if idx == self.bits.len() - 1 && num_cpus % BITS_PER_PART != 0 {
338                    *part == (1 << (num_cpus % BITS_PER_PART)) - 1
339                } else {
340                    *part == !0
341                }
342            },
343        )
344    }
345
346    /// Adds all CPUs to the set.
347    #[verus_spec(
348        requires
349            self.inv(),
350        ensures
351            final(self)@ == Set::range(0, cpu_count()),
352            final(self).inv(),
353    )]
354    pub fn add_all(&mut self) {
355        self.bits.fill(!0);
356        self.clear_nonexistent_cpu_bits();
357    }
358
359    /// Removes all CPUs from the set.
360    #[verus_spec(
361        requires
362            self.inv(),
363        ensures
364            final(self)@ == Set::empty(),
365            final(self).inv(),
366    )]
367    pub fn clear(&mut self) {
368        self.bits.fill(0);
369        proof! {
370            lemma_empty_bits_imply_empty_set(self);
371            assert forall|j: int|
372                cpu_count() <= j < 64 * smallvec_view(&self.bits).len() implies !bit_at(
373                    smallvec_view(&self.bits),
374                    j,
375                ) by {
376                lemma_u64_and_zero(1u64 << bit_idx_spec(j));
377            }
378        }
379    }
380
381    /// Iterates over the CPUs in the set.
382    ///
383    /// The order of the iteration is guaranteed to be in ascending order.
384    #[verus_spec(ret =>
385        requires
386            self.inv(),
387        ensures
388            IteratorSpec::obeys_prophetic_iter_laws(&ret),
389            IteratorSpec::decrease(&ret) is Some,
390    )]
391    pub fn iter(&self) -> impl Iterator<Item = CpuId> + '_ {
392        /* `FlatMap` and `FilterMap` are not modeled by the active vstd, so scan
393         * the same bit positions with modeled `Filter` and `Map` adapters. The position order
394         * and selected CPU IDs are unchanged.
395         * Origin Rust: self.bits.iter().enumerate().flat_map(|(part_idx, &part)| {
396         *     (0..BITS_PER_PART).filter_map(move |bit_idx| {
397         *         if (part & (1 << bit_idx)) != 0 {
398         *             let id = part_idx * BITS_PER_PART + bit_idx;
399         *             Some(CpuId(id as u32))
400         *         } else {
401         *             None
402         *         }
403         *     })
404         * })
405         */
406        let end = self.bits.len() * BITS_PER_PART;
407        (0..end)
408            .filter(
409                #[verus_spec(ret: bool =>
410                    requires
411                        *id < end,
412                    ensures
413                        ret == bit_at(smallvec_view(&self.bits), *id as int),
414                )]
415                move |id| {
416                    let part_idx = *id / BITS_PER_PART;
417                    let bit_idx = *id % BITS_PER_PART;
418                    (self.bits[part_idx] & (1 << bit_idx)) != 0
419                },
420            )
421            .map(
422                #[verus_spec(ret: CpuId =>
423                    requires
424                        bit_at(smallvec_view(&self.bits), id as int),
425                    ensures
426                        ret == CpuId(id as u32),
427                )]
428                move |id| CpuId(id as u32),
429            )
430    }
431
432    /// Only for internal use. The set cannot contain non-existent CPUs.
433    #[verus_spec(ret =>
434        requires
435            num_cpus == cpu_count(),
436            2 * parts_for_cpus(num_cpus) * size_of::<u64>() <= isize::MAX,
437        ensures
438            smallvec_view(&ret.bits).len() == parts_for_cpus(num_cpus),
439        forall|i: int|
440            #![trigger smallvec_view(&ret.bits)[i]]
441            0 <= i < smallvec_view(&ret.bits).len() ==> smallvec_view(&ret.bits)[i]
442                == val,
443    )]
444    fn with_capacity_val(num_cpus: usize, val: InnerPart) -> Self {
445        let num_parts = parts_for_cpus(num_cpus);
446        let mut bits = SmallVec::with_capacity(num_parts);
447        bits.resize(num_parts, val);
448        Self { bits }
449    }
450
451    #[verus_spec(
452        requires
453            smallvec_view(&self.bits).len() == parts_for_cpus(cpu_count() as usize),
454            forall|j: int|
455                #![trigger bit_at(smallvec_view(&self.bits), j)]
456                0 <= j < cpu_count() ==> bit_at(smallvec_view(&self.bits), j),
457        ensures
458            final(self).inv(),
459            forall|j: int|
460                #![trigger bit_at(smallvec_view(&final(self).bits), j)]
461                0 <= j < cpu_count() ==> bit_at(smallvec_view(&final(self).bits), j),
462    )]
463    fn clear_nonexistent_cpu_bits(&mut self) {
464        let num_cpus = num_cpus();
465        if num_cpus % BITS_PER_PART != 0 {
466            let num_parts = parts_for_cpus(num_cpus);
467            self.bits[num_parts - 1] &= (1 << (num_cpus % BITS_PER_PART)) - 1;
468            proof! {
469                let n = cpu_count();
470                let old_seq = smallvec_view(&old(self).bits);
471                let new_seq = smallvec_view(&self.bits);
472                assert forall|j: int| 0 <= j < n implies
473                    bit_at(new_seq, j) == bit_at(old_seq, j) by {}
474            }
475        }
476    }
477}
478
479/* impl From<CpuId> for CpuSet {
480    fn from(cpu_id: CpuId) -> Self {
481        let mut set = Self::new_empty();
482        set.add(cpu_id);
483        set
484    }
485} */
486
487/// A subset of all CPUs in the system with atomic operations.
488///
489/// It provides atomic operations for each CPU in the system. When the
490/// operation contains multiple CPUs, the ordering is not guaranteed.
491#[derive(Debug)]
492#[verus_verify]
493pub struct AtomicCpuSet {
494    bits: SmallVec<[AtomicInnerPart; NR_PARTS_NO_ALLOC]>,
495}
496
497type AtomicInnerPart = AtomicU64;
498/* const_assert!(core::mem::size_of::<AtomicInnerPart>() * 8 == BITS_PER_PART); */
499
500verus! {
501
502impl AtomicCpuSet {
503    /// Number of backing words.
504    pub closed spec fn num_parts(&self) -> nat {
505        smallvec_view(&self.bits).len()
506    }
507
508    /// The word count always matches the system's CPU count.
509    #[verifier::type_invariant]
510    closed spec fn type_inv(self) -> bool {
511        Self::num_parts(&self) == parts_for_cpus(cpu_count() as usize)
512    }
513}
514
515} // verus!
516#[verus_verify]
517impl AtomicCpuSet {
518    /// Creates a new `AtomicCpuSet` with an initial value.
519    #[verus_spec(requires value.inv())]
520    pub fn new(value: CpuSet) -> Self {
521        let bits = value.bits.into_iter().map(AtomicU64::new).collect();
522        Self { bits }
523    }
524
525    /// Loads the value of the set with the given ordering.
526    ///
527    /// This operation is not atomic. When racing with a [`Self::store`]
528    /// operation, this load may return a set that contains a portion of the
529    /// new value and a portion of the old value. Load on each specific
530    /// word is atomic, and follows the specified ordering.
531    ///
532    /// Note that load with [`Ordering::Release`] is a valid operation, which
533    /// is different from the normal atomic operations. When coupled with
534    /// [`Ordering::Release`], it actually performs `fetch_or(0, Release)`.
535    #[verus_spec(ret =>
536        requires
537            ordering != Ordering::AcqRel,
538        ensures
539            ret.num_parts() == self.num_parts(),
540    )]
541    pub fn load(&self, ordering: Ordering) -> CpuSet {
542        let bits = self
543            .bits
544            .iter()
545            .map(|part| match ordering {
546                Ordering::Release => part.fetch_or(0, ordering),
547                _ => part.load(ordering),
548            })
549            .collect();
550        CpuSet { bits }
551    }
552
553    /// Stores a new value to the set with the given ordering.
554    ///
555    /// This operation is not atomic. When racing with a [`Self::load`]
556    /// operation, that load may return a set that contains a portion of the
557    /// new value and a portion of the old value. Load on each specific
558    /// word is atomic, and follows the specified ordering.
559    #[verus_spec(
560        requires
561            ordering != Ordering::Acquire,
562            ordering != Ordering::AcqRel,
563    )]
564    pub fn store(&self, value: &CpuSet, ordering: Ordering) {
565        #[verus_spec(
566            invariant
567                ordering != Ordering::Acquire,
568                ordering != Ordering::AcqRel,
569        )]
570        for (part, new_part) in self.bits.iter().zip(value.bits.iter()) {
571            part.store(*new_part, ordering);
572        }
573    }
574
575    /// Atomically adds a CPU with the given ordering.
576    pub fn add(&self, cpu_id: CpuId, ordering: Ordering) {
577        let part_idx = part_idx(cpu_id);
578        let bit_idx = bit_idx(cpu_id);
579        if part_idx < self.bits.len() {
580            self.bits[part_idx].fetch_or(1 << bit_idx, ordering);
581        }
582    }
583
584    /// Atomically removes a CPU with the given ordering.
585    pub fn remove(&self, cpu_id: CpuId, ordering: Ordering) {
586        let part_idx = part_idx(cpu_id);
587        let bit_idx = bit_idx(cpu_id);
588        if part_idx < self.bits.len() {
589            self.bits[part_idx].fetch_and(!(1 << bit_idx), ordering);
590        }
591    }
592
593    /// Atomically checks if the set contains the specified CPU.
594    #[verus_spec(ret =>
595        requires
596            ordering != Ordering::Release,
597            ordering != Ordering::AcqRel,
598        ensures
599            cpu_id@ / 64 >= self.num_parts() ==> ret == false,
600    )]
601    pub fn contains(&self, cpu_id: CpuId, ordering: Ordering) -> bool {
602        let part_idx = part_idx(cpu_id);
603        let bit_idx = bit_idx(cpu_id);
604        part_idx < self.bits.len() && (self.bits[part_idx].load(ordering) & (1 << bit_idx)) != 0
605    }
606}
607
608// Private auxiliary specifications and proof lemmas backing the implementations above. They are
609// collected at the end of the file so that the APIs and critical proofs stay in focus.
610
611verus! {
612
613/// `div_ceil(n, BITS_PER_PART)`: the number of 64-bit words needed to hold `n` bits.
614spec fn parts_for_cpus_spec(n: usize) -> usize {
615    if n == 0 {
616        0
617    } else {
618        ((n + 63) / 64) as usize
619    }
620}
621
622/// The 64-bit word holding bit `i`.
623spec fn part_idx_spec(i: int) -> usize {
624    (i / 64) as usize
625}
626
627/// The position of bit `i` within its 64-bit word.
628spec fn bit_idx_spec(i: int) -> usize {
629    (i % 64) as usize
630}
631
632/// Number of set bits in all words of `seq`.
633spec fn count_set_bits(seq: Seq<u64>) -> int {
634    seq.fold_left(0, |count: int, word: u64| count + word.count_ones())
635}
636
637/// Expected value of word `idx` in a full CPU set.
638spec fn full_set_word(num_cpus: int, len: int, idx: int) -> u64 {
639    if idx == len - 1 && bit_idx_spec(num_cpus) != 0 {
640        ((1u64 << bit_idx_spec(num_cpus)) - 1) as u64
641    } else {
642        !0u64
643    }
644}
645
646proof fn lemma_u64_nonzero_has_set_bit_aux(word: u64, n: int)
647    requires
648        word != 0,
649        0 <= n <= 64,
650        word >> (n as u32) == 0,
651    ensures
652        exists|b: int| 0 <= b < n && #[trigger] u64_bit_is_set(word, b),
653    decreases n,
654{
655    if n == 0 {
656        assert(word >> (0u32) == word) by (bit_vector);
657    } else if !u64_bit_is_set(word, 0) {
658        let shifted = word >> 1u32;
659        assert(shifted != 0) by (bit_vector)
660            requires
661                shifted == word >> 1u32,
662                word != 0,
663                (word & (1u64 << 0usize)) == 0u64,
664        ;
665        let prev: int = n - 1;
666        let nu: u32 = n as u32;
667        let prevu: u32 = (n - 1) as u32;
668        assert(shifted >> prevu == word >> nu) by (bit_vector)
669            requires
670                shifted == word >> 1u32,
671                nu == prevu + 1,
672                nu <= 64,
673        ;
674        lemma_u64_nonzero_has_set_bit_aux(shifted, prev);
675        let b = choose|b: int| 0 <= b < n - 1 && #[trigger] u64_bit_is_set(shifted, b);
676        let bu: u32 = b as u32;
677        let next: u32 = (b + 1) as u32;
678        assert(u64_bit_is_set(word, b + 1)) by {
679            assert((word & (1u64 << next)) != 0) by (bit_vector)
680                requires
681                    shifted == word >> 1u32,
682                    (shifted & (1u64 << bu)) != 0,
683                    next == bu + 1,
684                    bu < 63,
685            ;
686        };
687    }
688}
689
690proof fn lemma_u64_nonzero_has_set_bit(word: u64)
691    requires
692        word != 0,
693    ensures
694        exists|b: int| 0 <= b < 64 && #[trigger] u64_bit_is_set(word, b),
695{
696    assert(word >> 64u32 == 0) by (bit_vector);
697    lemma_u64_nonzero_has_set_bit_aux(word, 64);
698}
699
700/// A CPU set whose backing words are all zero has an empty abstract view.
701proof fn lemma_empty_bits_imply_empty_set(set: &CpuSet)
702    requires
703        smallvec_view(&set.bits).all(|w: u64| w == 0u64),
704    ensures
705        set@ == Set::empty(),
706{
707    let seq = smallvec_view(&set.bits);
708    assert forall|k: int| 0 <= k < seq.len() implies seq[k] == 0u64 by {
709        let p = |w: u64| w == 0u64;
710        assert(p(seq[k]));
711    }
712    assert forall|j: int| !set@.contains(j) by {
713        if 0 <= j < cpu_count() && j < 64 * seq.len() {
714            lemma_u64_and_zero(1u64 << bit_idx_spec(j));
715        }
716    }
717}
718
719/// If every backing word has the full-set value, every existing CPU bit is set.
720proof fn lemma_full_bits_imply_full_set(set: &CpuSet)
721    requires
722        set.inv(),
723        forall|i: int|
724            #![trigger smallvec_view(&set.bits)[i]]
725            0 <= i < smallvec_view(&set.bits).len() ==> smallvec_view(&set.bits)[i]
726                == full_set_word(cpu_count(), smallvec_view(&set.bits).len() as int, i),
727    ensures
728        set@ == Set::range(0, cpu_count()),
729{
730    let seq = smallvec_view(&set.bits);
731    let n = cpu_count();
732    let len = seq.len();
733    assert forall|a: int|
734        #![trigger set@.contains(a)]
735        set@.contains(a) == Set::range(0, n).contains(a) by {
736        if 0 <= a < n {
737            let p = a / 64;
738            let word = seq[p];
739            let b = (a % 64) as u32;
740            if p == len - 1 && n % 64 != 0 {
741                let k = (n % 64) as u32;
742                assert((word & (1u64 << b)) != 0) by (bit_vector)
743                    requires
744                        b < k,
745                        0 < k < 64,
746                        word == (1u64 << k) - 1,
747                ;
748            } else {
749                assert((word & (1u64 << b)) != 0) by (bit_vector)
750                    requires
751                        b < 64,
752                        word == !0u64,
753                ;
754            }
755        }
756    }
757}
758
759/// Two distinct `u64` words differ at some unit bit.
760proof fn lemma_u64_distinct_bits_differ(x: u64, y: u64)
761    requires
762        x != y,
763    ensures
764        exists|b: int|
765            0 <= b < 64 && (#[trigger] (x & (1u64 << (b as usize)))) != (y & (1u64 << (
766            b as usize))),
767{
768    let diff: u64 = x ^ y;
769    assert(diff != 0u64) by (bit_vector)
770        requires
771            diff == x ^ y,
772            x != y,
773    ;
774    lemma_u64_nonzero_has_set_bit(diff);
775    let b = choose|b: int| 0 <= b < 64 && #[trigger] u64_bit_is_set(diff, b);
776    let bu: u32 = b as u32;
777    assert((x & (1u64 << bu)) != (y & (1u64 << bu))) by (bit_vector)
778        requires
779            (diff & (1u64 << bu)) != 0,
780            diff == x ^ y,
781    ;
782}
783
784/// ANDing with the unit bit at `b` yields `0` or the unit bit itself.
785proof fn lemma_u64_unit_bit_projection(x: u64, b: int)
786    requires
787        0 <= b < 64,
788    ensures
789        !u64_bit_is_set(x, b) || ((x & (1u64 << (b as usize))) == (1u64 << (b as usize))),
790{
791    let bu: u32 = b as u32;
792    assert((x & (1u64 << bu)) == 0u64 || (x & (1u64 << bu)) == (1u64 << bu)) by (bit_vector);
793}
794
795/// If some backing word differs from its full-set value, the abstract view is not
796/// the full CPU range: the differing bit is either a missing CPU bit (below
797/// `cpu_count`), or a set nonexistent bit, which `inv` rules out.
798proof fn lemma_mismatched_word_imply_not_full_set(set: &CpuSet, p: int)
799    requires
800        set.inv(),
801        0 <= p < smallvec_view(&set.bits).len(),
802        smallvec_view(&set.bits)[p] != full_set_word(
803            cpu_count(),
804            smallvec_view(&set.bits).len() as int,
805            p,
806        ),
807    ensures
808        set@ != Set::range(0, cpu_count()),
809{
810    let seq = smallvec_view(&set.bits);
811    let n = cpu_count();
812    let len = seq.len() as int;
813    let k = n % 64;
814    let word = seq[p];
815    let expected = full_set_word(n, len, p);
816    lemma_u64_distinct_bits_differ(word, expected);
817    let b = choose|b: int|
818        0 <= b < 64 && (#[trigger] (word & (1u64 << (b as usize)))) != (expected & (1u64 << (
819        b as usize)));
820    assert(u64_bit_is_set(word, b) != u64_bit_is_set(expected, b)) by {
821        lemma_u64_unit_bit_projection(word, b);
822        lemma_u64_unit_bit_projection(expected, b);
823    }
824    let j = 64 * p + b;
825    assert(u64_bit_is_set(expected, b) == (j < n)) by {
826        let bu = b as u32;
827        if p == len - 1 && k != 0 {
828            let ku = k as u32;
829            assert((expected & (1u64 << bu) != 0) == (bu < ku)) by (bit_vector)
830                requires
831                    bu < 64,
832                    0 < ku < 64,
833                    expected == (1u64 << ku) - 1,
834            ;
835        } else {
836            assert((expected & (1u64 << bu)) != 0) by (bit_vector)
837                requires
838                    bu < 64,
839                    expected == !0u64,
840            ;
841        }
842    }
843    assert(j / 64 == p && j % 64 == b);
844    assert(bit_at(seq, j) == u64_bit_is_set(word, b));
845    assert(j < n);
846    assert(!set@.contains(j));
847    assert(Set::range(0, n).contains(j));
848}
849
850} // verus!
851#[cfg(ktest)]
852mod test {
853    use super::*;
854    use crate::{cpu::all_cpus, prelude::*};
855
856    #[ktest]
857    fn test_full_cpu_set_iter_is_all() {
858        let set = CpuSet::new_full();
859        let num_cpus = num_cpus();
860        let all_cpus = all_cpus().collect::<Vec<_>>();
861        let set_cpus = set.iter().collect::<Vec<_>>();
862
863        assert!(set_cpus.len() == num_cpus);
864        assert_eq!(set_cpus, all_cpus);
865    }
866
867    #[ktest]
868    fn test_full_cpu_set_contains_all() {
869        let set = CpuSet::new_full();
870        for cpu_id in all_cpus() {
871            assert!(set.contains(cpu_id));
872        }
873    }
874
875    #[ktest]
876    fn test_empty_cpu_set_iter_is_empty() {
877        let set = CpuSet::new_empty();
878        let set_cpus = set.iter().collect::<Vec<_>>();
879        assert!(set_cpus.is_empty());
880    }
881
882    #[ktest]
883    fn test_empty_cpu_set_contains_none() {
884        let set = CpuSet::new_empty();
885        for cpu_id in all_cpus() {
886            assert!(!set.contains(cpu_id));
887        }
888    }
889
890    #[ktest]
891    fn test_atomic_cpu_set_multiple_sizes() {
892        for test_num_cpus in [1usize, 3, 12, 64, 96, 99, 128, 256, 288, 1024] {
893            let test_all_iter = || (0..test_num_cpus).map(|id| CpuId(id as u32));
894
895            let set = CpuSet::with_capacity_val(test_num_cpus, 0);
896            let atomic_set = AtomicCpuSet::new(set);
897
898            for cpu_id in test_all_iter() {
899                assert!(!atomic_set.contains(cpu_id, Ordering::Relaxed));
900                if cpu_id.as_usize() % 3 == 0 {
901                    atomic_set.add(cpu_id, Ordering::Relaxed);
902                }
903            }
904
905            let loaded = atomic_set.load(Ordering::Relaxed);
906            for cpu_id in loaded.iter() {
907                if cpu_id.as_usize() % 3 == 0 {
908                    assert!(loaded.contains(cpu_id));
909                } else {
910                    assert!(!loaded.contains(cpu_id));
911                }
912            }
913
914            atomic_set.store(
915                &CpuSet::with_capacity_val(test_num_cpus, 0),
916                Ordering::Relaxed,
917            );
918
919            for cpu_id in test_all_iter() {
920                assert!(!atomic_set.contains(cpu_id, Ordering::Relaxed));
921                atomic_set.add(cpu_id, Ordering::Relaxed);
922            }
923        }
924    }
925}