Skip to main content

strat9_bus_drivers/
mmio.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use core::sync::atomic::Ordering;
24
25pub struct MmioRegion {
26    base: usize,
27    size: usize,
28}
29
30impl MmioRegion {
31    /// Creates a new instance.
32    pub const fn new() -> Self {
33        Self { base: 0, size: 0 }
34    }
35
36    /// Performs the init operation.
37    pub fn init(&mut self, base: usize, size: usize) {
38        self.base = base;
39        self.size = size;
40    }
41
42    /// Performs the base operation.
43    pub fn base(&self) -> usize {
44        self.base
45    }
46
47    /// Returns whether valid.
48    pub fn is_valid(&self) -> bool {
49        self.base != 0
50    }
51
52    /// Bounds + alignment check for a would-be access of `width` bytes at
53    /// `offset`, without performing it.
54    ///
55    /// Drivers exposing user-controllable offsets (e.g. `/bus/<drv>/reg/<hex>`)
56    /// must call this before touching MMIO so an out-of-range request fails
57    /// with a clean error instead of tripping the panic backstop in
58    /// [`Self::checked_addr`] and taking the kernel down.
59    pub fn contains(&self, offset: usize, width: usize) -> bool {
60        if width == 0 {
61            return false;
62        }
63        match offset.checked_add(width) {
64            Some(end) => self.base != 0 && end <= self.size && offset % width == 0,
65            None => false,
66        }
67    }
68    /// Validate a caller-supplied 32-bit register offset (bounds + natural
69    /// alignment), mapping failures to [`BusError::InvalidAddress`] instead
70    /// of tripping the panic backstop inside the accessors.
71    pub fn check_user_offset(&self, offset: usize) -> Result<(), crate::BusError> {
72        if self.contains(offset, core::mem::size_of::<u32>()) {
73            Ok(())
74        } else {
75            Err(crate::BusError::InvalidAddress)
76        }
77    }
78
79    /// Performs the checked addr operation.
80    ///
81    /// Enforces region bounds AND natural alignment for the access width:
82    /// `read_volatile`/`write_volatile` on a misaligned pointer is UB on
83    /// several supported architectures (strict-alignment ARM/MIPS), not
84    /// just a slow access.
85    fn checked_addr(&self, offset: usize, width: usize) -> usize {
86        let base = self.base();
87        assert!(base != 0, "mmio access on uninitialized MmioRegion");
88        let end = offset.checked_add(width).expect("mmio offset overflow");
89        assert!(
90            end <= self.size,
91            "mmio access out of bounds (offset={:#x}, width={}, size={:#x})",
92            offset,
93            width,
94            self.size
95        );
96        assert!(
97            offset % width == 0,
98            "misaligned mmio access (offset={:#x}, width={})",
99            offset,
100            width
101        );
102        base.checked_add(offset).expect("mmio address overflow")
103    }
104
105    /// Performs the read8 operation.
106    pub fn read8(&self, offset: usize) -> u8 {
107        let addr = self.checked_addr(offset, core::mem::size_of::<u8>());
108        // SAFETY: caller guarantees this address is a valid MMIO region
109        unsafe { core::ptr::read_volatile(addr as *const u8) }
110    }
111
112    /// Performs the read16 operation.
113    pub fn read16(&self, offset: usize) -> u16 {
114        let addr = self.checked_addr(offset, core::mem::size_of::<u16>());
115        // SAFETY: caller guarantees this address is a valid MMIO region
116        unsafe { core::ptr::read_volatile(addr as *const u16) }
117    }
118
119    /// Performs the read32 operation.
120    pub fn read32(&self, offset: usize) -> u32 {
121        let addr = self.checked_addr(offset, core::mem::size_of::<u32>());
122        // SAFETY: caller guarantees this address is a valid MMIO region
123        unsafe { core::ptr::read_volatile(addr as *const u32) }
124    }
125
126    /// Performs the read64 operation.
127    pub fn read64(&self, offset: usize) -> u64 {
128        let addr = self.checked_addr(offset, core::mem::size_of::<u64>());
129        // SAFETY: caller guarantees this address is a valid MMIO region
130        unsafe { core::ptr::read_volatile(addr as *const u64) }
131    }
132
133    /// Performs the write8 operation.
134    pub fn write8(&self, offset: usize, val: u8) {
135        let addr = self.checked_addr(offset, core::mem::size_of::<u8>());
136        // SAFETY: caller guarantees this address is a valid MMIO region
137        unsafe { core::ptr::write_volatile(addr as *mut u8, val) }
138    }
139
140    /// Performs the write16 operation.
141    pub fn write16(&self, offset: usize, val: u16) {
142        let addr = self.checked_addr(offset, core::mem::size_of::<u16>());
143        // SAFETY: caller guarantees this address is a valid MMIO region
144        unsafe { core::ptr::write_volatile(addr as *mut u16, val) }
145    }
146
147    /// Performs the write32 operation.
148    pub fn write32(&self, offset: usize, val: u32) {
149        let addr = self.checked_addr(offset, core::mem::size_of::<u32>());
150        // SAFETY: caller guarantees this address is a valid MMIO region
151        unsafe { core::ptr::write_volatile(addr as *mut u32, val) }
152    }
153
154    /// Performs the write64 operation.
155    pub fn write64(&self, offset: usize, val: u64) {
156        let addr = self.checked_addr(offset, core::mem::size_of::<u64>());
157        // SAFETY: caller guarantees this address is a valid MMIO region
158        unsafe { core::ptr::write_volatile(addr as *mut u64, val) }
159    }
160
161    /// Sets bits32.
162    pub fn set_bits32(&self, offset: usize, bits: u32) {
163        let val = self.read32(offset);
164        self.write32(offset, val | bits);
165    }
166
167    /// Performs the clear bits32 operation.
168    pub fn clear_bits32(&self, offset: usize, bits: u32) {
169        let val = self.read32(offset);
170        self.write32(offset, val & !bits);
171    }
172
173    /// Performs the modify32 operation.
174    pub fn modify32(&self, offset: usize, clear: u32, set: u32) {
175        let val = self.read32(offset);
176        self.write32(offset, (val & !clear) | set);
177    }
178
179    /// Reads field32.
180    pub fn read_field32(&self, offset: usize, mask: u32, shift: u32) -> u32 {
181        (self.read32(offset) & mask) >> shift
182    }
183
184    /// Writes field32.
185    ///
186    /// `value` is masked to the field width *before* shifting so that a
187    /// caller passing an unshifted field value can never trigger a shift
188    /// overflow (`value` may be up to u32::MAX when `shift > 0`). Bits of
189    /// `value` outside the field width are ignored by contract.
190    pub fn write_field32(&self, offset: usize, mask: u32, shift: u32, value: u32) {
191        let width_mask = mask >> shift;
192        let field = ((value & width_mask) << shift) & mask;
193        self.modify32(offset, mask, field);
194    }
195}
196
197// SAFETY: MmioRegion contains only an atomic base address and a size.
198// Access to the MMIO region itself requires the caller to ensure
199// the mapping is valid and not concurrently mutated.
200unsafe impl Send for MmioRegion {}
201unsafe impl Sync for MmioRegion {}
202
203/// Performs the memory barrier operation.
204pub fn memory_barrier() {
205    core::sync::atomic::fence(Ordering::SeqCst);
206}