Skip to main content

ostd/task/scheduler/
info.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Scheduling related information in a task.
3use vstd::{
4    atomic::{PAtomicU32, PermissionU32},
5    prelude::*,
6};
7
8use crate::cpu::{axiom_cpu_count_bounds, cpu_count, lemma_cpu_id_model, lemma_type_inv_range};
9
10// use core::sync::atomic::{AtomicU32, Ordering};
11
12use crate::{cpu::CpuId /*, task::Task */};
13
14/// Fields of a task that OSTD will never touch.
15///
16/// The type ought to be defined by the OSTD user and injected into the task.
17/// They are not part of the dynamic task data because it's slower there for
18/// the user-defined scheduler to access. The better ways to let the user
19/// define them, such as
20/// [existential types](https://github.com/rust-lang/rfcs/pull/2492) do not
21/// exist yet. So we decide to define them in OSTD.
22/* Origin Rust: #[derive(Debug)] (dropped: PAtomicU32 has no Debug impl) */
23#[verus_verify]
24pub struct TaskScheduleInfo {
25    /// The CPU that the task would like to be running on.
26    pub cpu: AtomicCpuId,
27}
28
29/// An atomic CPUID container.
30/* Origin Rust: #[derive(Debug)] pub struct AtomicCpuId(AtomicU32); */
31#[verus_verify]
32pub struct AtomicCpuId(PAtomicU32);
33
34verus! {
35
36impl AtomicCpuId {
37    /// The null value of CPUID.
38    ///
39    /// An `AtomicCpuId` with `AtomicCpuId::NONE` as its inner value is empty.
40    /* `pub` is required by Verus since public contracts refer to it. */
41    pub const NONE: u32 = u32::MAX;
42
43    /// Sets the inner value of an `AtomicCpuId` if it's empty.
44    ///
45    /// The return value is a result indicating whether the new value was written
46    /// and containing the previous value. If the previous value is empty, it returns
47    /// `Ok(())`. Otherwise, it returns `Err(previous_value)` which the previous
48    /// value is a valid CPU ID.
49    #[verus_spec(
50        ret =>
51        with
52            Tracked(perm): Tracked<&mut PermissionU32>,
53        requires
54            old(perm).view().patomic == self.patomic_id(),
55            Self::inv_value(old(perm).view().value),
56        ensures
57            self.patomic_id() == final(perm).view().patomic,
58            ret is Ok <==> old(perm).view().value == Self::NONE,
59            ret is Ok ==> final(perm).view().value == cpu_id.as_usize() as u32,
60            ret matches Err(prev) ==> prev@ == old(perm).view().value
61                && final(perm).view().value == old(perm).view().value,
62            Self::inv_value(final(perm).view().value),
63    )]
64    pub fn set_if_is_none(&self, cpu_id: CpuId) -> core::result::Result<(), CpuId> {
65        proof! {
66            broadcast use {
67                axiom_cpu_count_bounds,
68                lemma_cpu_id_model,
69                lemma_type_inv_range,
70            };
71            use_type_invariant(&cpu_id);
72            assert(Self::inv_value(cpu_id.as_usize() as u32));
73        }
74        /* PAtomicU32::compare_exchange takes the tracked permission and hardcodes
75         * `SeqCst`, so the call drops the two `Ordering::Relaxed` arguments; the
76         * `map_err` closure needs its own spec to carry the `unwrap` precondition.
77         * Origin Rust: self.0.compare_exchange(Self::NONE, cpu_id.as_usize() as u32, Ordering::Relaxed, Ordering::Relaxed).map(|_| ()).map_err(|prev| (prev as usize).try_into().unwrap())
78         */
79        self.0.compare_exchange(Tracked(perm), Self::NONE, cpu_id.as_usize() as u32).map(
80            |_| (),
81        ).map_err(
82            |prev: u32| -> (payload: CpuId)
83                requires
84                    cpu_count() > prev,
85                ensures
86                    payload@ == prev,
87                { (prev as usize).try_into().unwrap() },
88        )
89    }
90
91    /// Sets the inner value of an `AtomicCpuId` anyway.
92    #[verus_spec(
93        with
94            Tracked(perm): Tracked<&mut PermissionU32>,
95        requires
96            old(perm).view().patomic == self.patomic_id(),
97        ensures
98            self.patomic_id() == final(perm).view().patomic,
99            final(perm).view().value == cpu_id.as_usize() as u32,
100            Self::inv_value(final(perm).view().value),
101    )]
102    pub fn set_anyway(&self, cpu_id: CpuId) {
103        proof! {
104            broadcast use {
105                axiom_cpu_count_bounds,
106                lemma_cpu_id_model,
107                lemma_type_inv_range,
108            };
109            use_type_invariant(&cpu_id);
110            assert(Self::inv_value(cpu_id.as_usize() as u32));
111        }
112        /* Origin Rust: self.0.store(cpu_id.as_usize() as u32, Ordering::Relaxed); */
113        self.0.store(Tracked(perm), cpu_id.as_usize() as u32);
114    }
115
116    /// Sets the inner value of an `AtomicCpuId` to `AtomicCpuId::NONE`, i.e. makes
117    /// an `AtomicCpuId` empty.
118    #[verus_spec(
119        with
120            Tracked(perm): Tracked<&mut PermissionU32>,
121        requires
122            old(perm).view().patomic == self.patomic_id(),
123        ensures
124            self.patomic_id() == final(perm).view().patomic,
125            final(perm).view().value == Self::NONE,
126            Self::inv_value(final(perm).view().value),
127    )]
128    pub fn set_to_none(&self) {
129        /* Origin Rust: self.0.store(Self::NONE, Ordering::Relaxed); */
130        self.0.store(Tracked(perm), Self::NONE);
131    }
132
133    /// Gets the inner value of an `AtomicCpuId`.
134    #[verus_spec(
135        ret =>
136        with
137            Tracked(perm): Tracked<&PermissionU32>,
138        requires
139            perm.view().patomic == self.patomic_id(),
140            Self::inv_value(perm.view().value),
141        ensures
142            ret is None == (perm.view().value == Self::NONE),
143            ret matches Some(id) ==> id@ == perm.view().value,
144    )]
145    pub fn get(&self) -> Option<CpuId> {
146        /* Origin Rust: let val = self.0.load(Ordering::Relaxed); */
147        let val = self.0.load(Tracked(perm));
148        if val == Self::NONE {
149            None
150        } else {
151            Some((val as usize).try_into().ok()?)
152        }
153    }
154
155    /// The identity of the inner atomic cell, for tying permissions to `self`.
156    /// A closed helper, since a `pub` contract cannot use the private field.
157    pub closed spec fn patomic_id(&self) -> int {
158        self.0.id()
159    }
160
161    /// The trace invariant of the CPUID cell: the stored word is the null
162    /// constant `NONE` or encodes a valid CPU ID (below the CPU count).
163    pub open spec fn inv_value(v: u32) -> bool {
164        v == Self::NONE || 0 <= v < cpu_count()
165    }
166}
167
168} // verus!
169impl Default for AtomicCpuId {
170    fn default() -> Self {
171        Self(PAtomicU32::new(Self::NONE).0)
172    }
173}
174
175/* impl CommonSchedInfo for Task {
176    fn cpu(&self) -> &AtomicCpuId {
177        &self.schedule_info().cpu
178    }
179} */
180
181/// Trait for fetching common scheduling information.
182pub trait CommonSchedInfo {
183    /// Gets the CPU that the task is running on or lately ran on.
184    fn cpu(&self) -> &AtomicCpuId;
185}