Skip to main content

ostd/io/io_port/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! I/O port and its allocator that allocates port I/O (PIO) to device drivers.
3use vstd::{prelude::*, resource::set::GhostSubset};
4use vstd_extra::external::{group_io_port_models, obeys_io_port_access_spec, valid_io_port_access};
5
6use crate::arch::io::MAX_IO_PORT;
7
8use crate::arch::device::io_port::{IoPortReadAccess, IoPortWriteAccess, PortRead, PortWrite};
9mod allocator;
10
11use core::{marker::PhantomData, mem::size_of};
12
13pub(super) use self::allocator::{init, io_port_allocator_initialized};
14use crate::{Error, prelude::*};
15
16verus! {
17
18broadcast use group_io_port_models;
19
20} // verus!
21/// An I/O port, representing a specific address in the I/O address of x86.
22///
23/// The following code shows and example to read and write u32 value to an I/O port:
24///
25/// ```rust
26/// static PORT: IoPort<u32, ReadWriteAccess> = unsafe { IoPort::new(0x12) };
27///
28/// fn port_value_increase(){
29///     PORT.write(PORT.read() + 1)
30/// }
31/// ```
32///
33#[verus_verify]
34#[derive(Debug)]
35pub struct IoPort<T, A> {
36    port: u16,
37    is_overlapping: bool,
38    value_marker: PhantomData<T>,
39    access_marker: PhantomData<A>,
40    // Erased allocator ownership; statically reserved ports carry no claim.
41    #[cfg(verus_keep_ghost_body)]
42    tracked_claim: Tracked<Option<GhostSubset<usize>>>,
43}
44
45verus! {
46
47impl<T, A> View for IoPort<T, A> {
48    type V = u16;
49
50    closed spec fn view(&self) -> u16 {
51        self.port
52    }
53}
54
55impl<T, A> IoPort<T, A> {
56    /// The complete byte range occupied by this typed port lies in the x86 PIO address space.
57    #[verifier::type_invariant]
58    pub closed spec fn type_inv(self) -> bool {
59        &&& obeys_io_port_access_spec::<T>()
60        &&& valid_io_port_access::<T>(self@)
61        &&& self.tracked_claim@ matches Some(claim) ==> {
62            &&& allocator::io_port_allocator_initialized()
63            &&& self.claim_matches_set(claim@)
64            &&& claim.id() == allocator::io_port_allocator_instance_id()
65        }
66    }
67
68    /// Whether this port owns a claim minted by the allocator.
69    pub closed spec fn is_allocated(self) -> bool {
70        self.tracked_claim@ is Some
71    }
72
73    pub closed spec fn is_overlapping(self) -> bool {
74        self.is_overlapping
75    }
76
77    /// Whether `claim` is the allocator-issued ownership token for this port's occupied range:
78    /// the complete typed range, or only the first port if the port was acquired as
79    /// overlapping.
80    pub open spec fn claim_matches_set(self, claim: Set<usize>) -> bool {
81        claim == Set::<usize>::range(
82            self@ as usize,
83            if self.is_overlapping() {
84                (self@ + 1) as usize
85            } else {
86                (self@ + size_of::<T>()) as usize
87            },
88        )
89    }
90}
91
92} // verus!
93/// Returns the initialized global PIO allocator.
94///
95/// This helper is trusted only because Verus cannot connect an `exec static` to
96/// a spec-level boot-state predicate.
97#[verifier::external_body]
98#[verus_spec(
99    requires allocator::io_port_allocator_initialized(),
100)]
101fn initialized_allocator() -> &'static allocator::IoPortAllocator {
102    allocator::IO_PORT_ALLOCATOR.get().unwrap()
103}
104
105#[verus_verify]
106impl<T, A> IoPort<T, A> {
107    /// Acquires an `IoPort` instance for the given range.
108    ///
109    /// This method will mark all ports in the PIO range as occupied.
110    #[verus_spec(result =>
111        requires
112            size_of::<T>() == 1 || size_of::<T>() == 2 || size_of::<T>() == 4,
113            obeys_io_port_access_spec::<T>(),
114            allocator::io_port_allocator_initialized(),
115        ensures
116            port + size_of::<T>() > MAX_IO_PORT + 1 ==> result is Err,
117            result matches Ok(io_port) ==> {
118                &&& io_port@ == port
119                &&& !io_port.is_overlapping()
120                &&& io_port.is_allocated()
121            },
122    )]
123    pub fn acquire(port: u16) -> Result<IoPort<T, A>> {
124        /* Original Rust: allocator::IO_PORT_ALLOCATOR
125        .get()
126        .unwrap()
127        .acquire(port, false)
128        .ok_or(Error::AccessDenied) */
129        initialized_allocator()
130            .acquire(port, false)
131            .ok_or(Error::AccessDenied)
132    }
133
134    /// Acquires an `IoPort` instance that may overlap with other `IoPort`s.
135    ///
136    /// This method will only mark the first port in the PIO range as occupied.
137    #[verus_spec(result =>
138        requires
139            size_of::<T>() == 1 || size_of::<T>() == 2 || size_of::<T>() == 4,
140            obeys_io_port_access_spec::<T>(),
141            allocator::io_port_allocator_initialized(),
142        ensures
143            port + size_of::<T>() > MAX_IO_PORT + 1 ==> result is Err,
144            result matches Ok(io_port) ==> {
145                &&& io_port@ == port
146                &&& io_port.is_overlapping()
147                &&& io_port.is_allocated()
148            },
149    )]
150    pub fn acquire_overlapping(port: u16) -> Result<IoPort<T, A>> {
151        /* Original Rust: allocator::IO_PORT_ALLOCATOR
152        .get()
153        .unwrap()
154        .acquire(port, true)
155        .ok_or(Error::AccessDenied) */
156        initialized_allocator()
157            .acquire(port, true)
158            .ok_or(Error::AccessDenied)
159    }
160
161    /// Returns the port number.
162    #[verus_spec(returns self@)]
163    pub const fn port(&self) -> u16 {
164        self.port
165    }
166
167    /// Returns the size of the I/O port.
168    #[verus_spec(returns size_of::<T>() as u16)]
169    pub const fn size(&self) -> u16 {
170        size_of::<T>() as u16
171    }
172
173    /// Creates an I/O port.
174    ///
175    /// # Safety
176    ///
177    /// Reading from or writing to the I/O port may have side effects. Those side effects must
178    /// not cause soundness problems (e.g., they must not corrupt the kernel memory).
179    #[verus_spec(ret =>
180        requires
181            obeys_io_port_access_spec::<T>(),
182            valid_io_port_access::<T>(port),
183        ensures
184            ret@ == port,
185            !ret.is_overlapping(),
186    )]
187    pub(crate) const unsafe fn new(port: u16) -> Self {
188        proof_with! { tracked_claim: Tracked(None)}
189        Self {
190            port,
191            is_overlapping: false,
192            value_marker: PhantomData,
193            access_marker: PhantomData,
194        }
195    }
196
197    /// Creates an I/O port.
198    ///
199    /// See [`allocator::IoPortAllocator::acquire`] for an explanation of the `is_overlapping`
200    /// argument.
201    ///
202    /// # Safety
203    ///
204    /// Reading from or writing to the I/O port may have side effects. Those side effects must
205    /// not cause soundness problems (e.g., they must not corrupt the kernel memory).
206    /* Verus retains the body of the unverified twin of a const function, where
207     * the tracked input is unavailable.
208     * Origin Rust: const unsafe fn new_overlapping(port: u16, is_overlapping: bool) -> Self
209     */
210    #[verus_spec(ret =>
211        with Tracked(claim): Tracked<GhostSubset<usize>>,
212        requires
213            obeys_io_port_access_spec::<T>(),
214            valid_io_port_access::<T>(port),
215            allocator::io_port_allocator_initialized(),
216            claim.id() == allocator::io_port_allocator_instance_id(),
217            claim@ == Set::<usize>::range(
218                port as usize,
219                if is_overlapping {
220                    (port + 1) as usize
221                } else {
222                    (port + size_of::<T>()) as usize
223                },
224            ),
225        ensures
226            ret@ == port,
227            ret.is_overlapping() == is_overlapping,
228            ret.is_allocated(),
229    )]
230    unsafe fn new_overlapping(port: u16, is_overlapping: bool) -> Self {
231        proof_with! { tracked_claim: Tracked(Some(claim))}
232        Self {
233            port,
234            is_overlapping,
235            value_marker: PhantomData,
236            access_marker: PhantomData,
237        }
238    }
239
240    /// Releases this dynamically acquired port's allocator claim.
241    ///
242    /// # Verified Properties
243    ///
244    /// ## Preconditions
245    /// - The port owns an allocator-issued claim from `acquire` or `acquire_overlapping`.
246    /* VERUS LIMITATION: Verus cannot verify a lock-taking `Drop` implementation under
247     * `opens_invariants none`.
248     * Origin Rust:
249     * impl<T, A> Drop for IoPort<T, A> {
250     *     fn drop(&mut self) {
251     *         let port = self.port as usize;
252     *         let range = if !self.is_overlapping {
253     *             port..port + size_of::<T>()
254     *         } else {
255     *             port..port + 1
256     *         };
257     *
258     *         // SAFETY: We have ownership of the PIO region.
259     *         unsafe { allocator::IO_PORT_ALLOCATOR.get().unwrap().recycle(range) };
260     *     }
261     * }
262     */
263    #[verus_spec(requires self.is_allocated())]
264    pub fn drop(self) {
265        proof! {
266            use_type_invariant(&self);
267            let claim = self.tracked_claim@.unwrap()@;
268        }
269        let port = self.port as usize;
270        let range = if !self.is_overlapping {
271            port..port + size_of::<T>()
272        } else {
273            port..port + 1
274        };
275
276        proof_decl! {
277            let tracked claim = self.tracked_claim.get().tracked_unwrap();
278        }
279        unsafe {
280            #[verus_spec(with Tracked(claim))]
281            initialized_allocator().recycle(range);
282        }
283    }
284}
285
286#[verus_verify]
287#[verifier::allow(undeclared_external_trait)]
288impl<T: PortRead, A: IoPortReadAccess> IoPort<T, A> {
289    /// Reads from the I/O port
290    pub fn read(&self) -> T {
291        proof! { use_type_invariant(self); }
292        unsafe { PortRead::read_from_port(self.port) }
293    }
294}
295
296#[verus_verify]
297#[verifier::allow(undeclared_external_trait)]
298impl<T: PortWrite, A: IoPortWriteAccess> IoPort<T, A> {
299    /// Writes to the I/O port
300    pub fn write(&self, value: T) {
301        proof! { use_type_invariant(self); }
302        unsafe { PortWrite::write_to_port(self.port, value) }
303    }
304}
305
306/// Reserves an I/O port range which may refer to the port I/O range used by the
307/// system device driver.
308///
309/// # Example
310/// ```
311/// reserve_io_port_range!(0x60..0x64);
312/// ```
313macro_rules! reserve_io_port_range {
314    ($range:expr) => {
315        crate::const_assert!(
316            $range.start < $range.end,
317            "I/O port range must be valid (start < end)"
318        );
319
320        const _: () = {
321            #[used]
322            // SAFETY: This is properly handled in the linker script.
323            #[unsafe(link_section = ".sensitive_io_ports")]
324            static _RANGE: crate::io::RawIoPortRange = crate::io::RawIoPortRange {
325                begin: $range.start,
326                end: $range.end,
327            };
328        };
329    };
330}
331
332/// Declares one or multiple sensitive I/O ports.
333///
334/// # Safety
335///
336/// User must ensures that:
337/// - The I/O port is valid and doesn't overlap with other sensitive I/O ports.
338/// - The I/O port is used by the target system device driver.
339///
340/// # Example
341/// ```no_run
342/// sensitive_io_port! {
343///     unsafe {
344///         /// Master PIC command port
345///         static MASTER_CMD: IoPort<u8, WriteOnlyAccess> = IoPort::new(0x20);
346///         /// Master PIC data port
347///         static MASTER_DATA: IoPort<u8, WriteOnlyAccess> = IoPort::new(0x21);
348///     }
349/// }
350/// ```
351macro_rules! sensitive_io_port {
352    (unsafe { $(
353        $(#[$meta:meta])*
354        $vis:vis static $name:ident: IoPort<$size:ty, $access:ty> = IoPort::new($port:expr);
355    )* }) => {
356        $(
357            $(#[$meta])*
358            $vis static $name: IoPort<$size, $access> = {
359                #[used]
360                // SAFETY: This is properly handled in the linker script.
361                #[unsafe(link_section = ".sensitive_io_ports")]
362                static _RESERVED_IO_PORT_RANGE: crate::io::RawIoPortRange = crate::io::RawIoPortRange {
363                    begin: $name.port(),
364                    end: $name.port() + $name.size(),
365                };
366
367                unsafe { IoPort::new($port) }
368            };
369        )*
370    };
371}
372
373pub(crate) use reserve_io_port_range;
374pub(crate) use sensitive_io_port;
375
376#[verus_verify]
377#[doc(hidden)]
378#[repr(C)]
379#[derive(Clone, Copy, Debug)]
380pub(crate) struct RawIoPortRange {
381    pub(crate) begin: u16,
382    pub(crate) end: u16,
383}