Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. regs/regs.rs

regs/
regs.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#![no_std]
16
17#[doc(hidden)]
18pub mod __private {
19    use core::ptr;
20
21    pub use paste::paste;
22
23    /// Read a raw value from the register
24    ///
25    /// # Safety
26    /// The caller must guarantee that provided `addr` is accessible.
27    #[inline]
28    #[must_use]
29    pub unsafe fn raw_read<T>(addr: usize) -> T {
30        let ptr = ptr::with_exposed_provenance::<T>(addr);
31        unsafe { ptr.read_volatile() }
32    }
33
34    /// Write a raw value to the specified register
35    ///
36    /// # Safety
37    /// The caller must guarantee that the value is valid for the provided `addr`
38    /// and the `addr` is accessible.
39    #[inline]
40    pub unsafe fn raw_write<T>(addr: usize, val: T) {
41        let ptr = ptr::with_exposed_provenance_mut::<T>(addr);
42        unsafe { ptr.write_volatile(val) }
43    }
44}
45
46pub trait BaseAddress {
47    fn base_address(&self) -> usize;
48}
49
50#[macro_export]
51macro_rules! ro_bool_field {
52    ($val_type:ty, $name:ident, $offset:literal, $desc:literal) => {
53        #[doc = "Extract "]
54        #[doc = $desc]
55        #[doc = "field"]
56        #[inline]
57        pub const fn $name(&self) -> bool {
58            $crate::ops::get_bool(self.0 as usize, $offset)
59        }
60    };
61}
62
63#[macro_export]
64macro_rules! rw_bool_field {
65    ($val_type:ty, $name:ident, $offset:literal, $desc:literal) => {
66        $crate::ro_bool_field!($val_type, $name, $offset, $desc);
67        $crate::__private::paste! {
68          #[doc = "Update "]
69          #[doc = $desc]
70          #[doc = "field"]
71          #[inline]
72          pub const fn [<with_ $name>](self, val: bool) -> Self {
73              Self($crate::ops::set_bool(self.0 as usize, $offset, val) as $val_type)
74          }
75        }
76    };
77}
78
79#[macro_export]
80macro_rules! ro_int_field {
81    ($val_type:ty, $name:ident, $start:literal, $end:literal, $ty:ty, $desc:literal) => {
82        #[doc = "Extract "]
83        #[doc = $desc]
84        #[doc = "field"]
85        #[inline]
86        pub const fn $name(&self) -> $ty {
87            $crate::ops::get_usize(self.0 as usize, $start, $end) as $ty
88        }
89    };
90}
91
92#[macro_export]
93macro_rules! rw_int_field {
94    ($val_type:ty, $name:ident, $start:literal, $end:literal, $ty:ty, $desc:literal) => {
95        $crate::ro_int_field!($val_type, $name, $start, $end, $ty, $desc);
96        $crate::__private::paste! {
97          #[doc = "Update "]
98          #[doc = $desc]
99          #[doc = "field"]
100          #[inline]
101          pub const fn [<with_ $name>](self, val: $ty) -> Self {
102              Self($crate::ops::set_usize(self.0 as usize, $start, $end, val as usize) as $val_type)
103          }
104        }
105    };
106}
107
108/// Safety: $enum must be fully specified for the value range of the field or
109/// marked as non-inclusive.
110#[macro_export]
111macro_rules! ro_enum_field {
112    ($val_type:ty, $name:ident, $start:literal, $end:literal, $enum:ty, $desc:literal) => {
113        #[doc = "Extract "]
114        #[doc = $desc]
115        #[doc = "field"]
116        #[inline]
117        pub const fn $name(&self) -> $enum {
118            let raw_val = $crate::ops::get_usize(self.0 as usize, $start, $end);
119            unsafe { core::mem::transmute::<$val_type, $enum>(raw_val as $val_type) }
120        }
121    };
122}
123
124/// Safety: $enum must be fully specified for the value range of the field or
125/// marked as non-inclusive.
126#[macro_export]
127macro_rules! rw_enum_field {
128    ($val_type:ty, $name:ident, $start:literal, $end:literal, $enum:ty, $desc:literal) => {
129        $crate::ro_enum_field!($val_type, $name, $start, $end, $enum, $desc);
130        $crate::__private::paste! {
131          #[doc = "Update "]
132          #[doc = $desc]
133          #[doc = "field"]
134          #[inline]
135          pub const fn [<with_ $name>](self, val: $enum) -> Self {
136            let raw_val = unsafe { core::mem::transmute::<$enum, $val_type>(val) };
137              Self($crate::ops::set_usize(self.0 as usize, $start, $end, raw_val as usize) as $val_type)
138          }
139        }
140    };
141}
142
143#[macro_export]
144macro_rules! ro_masked_field {
145    ($name:ident, $mask:expr, $ty:ty, $desc:literal) => {
146        #[doc = "Extract "]
147        #[doc = $desc]
148        #[doc = "field"]
149        #[inline]
150        pub const fn $name(&self) -> $ty {
151            self.0 & $mask
152        }
153    };
154}
155
156#[macro_export]
157macro_rules! rw_masked_field {
158    ($name:ident, $mask:expr, $ty:ty, $desc:literal) => {
159        $crate::ro_masked_field!($name, $mask, $ty, $desc);
160        $crate::__private::paste! {
161            #[doc = "Update "]
162            #[doc = $desc]
163            #[doc = "field"]
164            #[inline]
165            pub const fn [<with_ $name>](self, val: $ty) -> Self {
166              Self(self.0 & !$mask | (val & $mask))
167            }
168        }
169    };
170}
171
172#[macro_export]
173macro_rules! ro_reg {
174    ($name:ident, $val_type:ident, $ty:ty, $addr:expr, $doc:literal) => {
175        #[doc = $doc]
176        pub struct $name;
177        impl $name {
178            const ADDR: usize = $addr;
179            const _ASSERT_ALIGNED: () = assert!(
180                Self::ADDR.is_multiple_of(core::mem::align_of::<$ty>()),
181                "Register address must be aligned to register type size"
182            );
183
184            #[inline]
185            pub fn read(&self) -> $val_type {
186                let () = Self::_ASSERT_ALIGNED;
187                $val_type(unsafe { $crate::__private::raw_read::<$ty>(Self::ADDR) })
188            }
189        }
190    };
191}
192
193#[macro_export]
194macro_rules! rw_reg {
195    ($name:ident, $val_type:ident, $ty:ty, $addr:expr, $doc:literal) => {
196        #[doc = $doc]
197        pub struct $name;
198        impl $name {
199            const ADDR: usize = $addr;
200            const _ASSERT_ALIGNED: () = assert!(
201                Self::ADDR.is_multiple_of(core::mem::align_of::<$ty>()),
202                "Register address must be aligned to register type size"
203            );
204
205            #[inline]
206            pub fn read(&self) -> $val_type {
207                let () = Self::_ASSERT_ALIGNED;
208                $val_type(unsafe { $crate::__private::raw_read::<$ty>(Self::ADDR) })
209            }
210
211            #[inline]
212            pub fn write(&mut self, val: $val_type) {
213                let () = Self::_ASSERT_ALIGNED;
214                unsafe { $crate::__private::raw_write::<$ty>(Self::ADDR, val.0) }
215            }
216        }
217    };
218}
219
220#[macro_export]
221macro_rules! ro_block_reg {
222    ($name:ident, $val_type:ident, $ty:ty, $addr_trait:path, $offset:expr, $doc:literal) => {
223        #[doc = $doc]
224        pub struct $name;
225        impl $name {
226            const OFFSET: usize = $offset;
227            const _ASSERT_OFFSET_ALIGNED: () = assert!(
228                Self::OFFSET.is_multiple_of(core::mem::align_of::<$ty>()),
229                "Register offset must be aligned to register type size"
230            );
231
232            #[inline]
233            pub fn read<A: $addr_trait>(&self, addr: &A) -> $val_type {
234                let () = Self::_ASSERT_OFFSET_ALIGNED;
235                $val_type(unsafe {
236                    $crate::__private::raw_read::<$ty>(addr.base_address() + Self::OFFSET)
237                })
238            }
239        }
240    };
241}
242
243#[macro_export]
244macro_rules! rw_block_reg {
245    ($name:ident, $val_type:ident, $ty:ty, $addr_trait:path, $offset:expr, $doc:literal) => {
246        #[doc = $doc]
247        pub struct $name;
248        impl $name {
249            const OFFSET: usize = $offset;
250            const _ASSERT_OFFSET_ALIGNED: () = assert!(
251                Self::OFFSET.is_multiple_of(core::mem::align_of::<$ty>()),
252                "Register offset must be aligned to register type size"
253            );
254
255            #[inline]
256            pub fn read<A: $addr_trait>(&self, addr: &A) -> $val_type {
257                let () = Self::_ASSERT_OFFSET_ALIGNED;
258                $val_type(unsafe {
259                    $crate::__private::raw_read::<$ty>(addr.base_address() + Self::OFFSET)
260                })
261            }
262
263            #[inline]
264            pub fn write<A: $addr_trait>(&mut self, addr: &A, val: $val_type) {
265                let () = Self::_ASSERT_OFFSET_ALIGNED;
266                unsafe {
267                    $crate::__private::raw_write::<$ty>(addr.base_address() + Self::OFFSET, val.0)
268                }
269            }
270        }
271    };
272}
273
274pub mod ops {
275    #[must_use]
276    #[inline]
277    pub const fn mask(start: usize, end: usize) -> usize {
278        let length = end - start + 1;
279        if length == pw_cast::cast!(usize::BITS => usize) {
280            // Special case full mask to keep shifting logic below from overflowing.
281            usize::MAX
282        } else {
283            ((1usize << length) - 1) << start
284        }
285    }
286
287    #[must_use]
288    #[inline]
289    pub const fn mask_u32(start: u32, end: u32) -> u32 {
290        let length = end - start + 1;
291        if length == u32::BITS {
292            // Special case full mask to keep shifting logic below from overflowing.
293            u32::MAX
294        } else {
295            ((1u32 << length) - 1) << start
296        }
297    }
298
299    #[must_use]
300    #[inline]
301    pub const fn get_bool(value: usize, bit: usize) -> bool {
302        (value >> bit) & 0x1 == 0x1
303    }
304
305    #[must_use]
306    #[inline]
307    pub const fn set_bool(value: usize, bit: usize, field_value: bool) -> usize {
308        value & !(1 << bit) | (pw_cast::cast!(field_value => usize) << bit)
309    }
310
311    #[must_use]
312    #[inline]
313    pub const fn get_u32(value: u32, start: u32, end: u32) -> u32 {
314        (value & mask_u32(start, end)) >> start
315    }
316
317    #[must_use]
318    #[inline]
319    pub const fn set_u32(value: u32, start: u32, end: u32, field_value: u32) -> u32 {
320        let mask = mask_u32(start, end);
321        (value & !mask) | ((field_value << start) & mask)
322    }
323
324    #[must_use]
325    #[inline]
326    pub const fn get_usize(value: usize, start: usize, end: usize) -> usize {
327        (value & mask(start, end)) >> start
328    }
329
330    #[must_use]
331    #[inline]
332    pub const fn set_usize(value: usize, start: usize, end: usize, field_value: usize) -> usize {
333        let mask = mask(start, end);
334        (value & !mask) | ((field_value << start) & mask)
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use unittest::test;
341
342    use super::*;
343
344    #[test]
345    fn mask_calculated_correctly() -> unittest::Result<()> {
346        unittest::assert_eq!(ops::mask(8, 15), 0x0000_ff00);
347        Ok(())
348    }
349
350    #[test]
351    fn get_bool_extracts_correct_value() -> unittest::Result<()> {
352        unittest::assert_false!(ops::get_bool(0x0000_0100, 7));
353        unittest::assert_true!(ops::get_bool(0x0000_0100, 8));
354        unittest::assert_false!(ops::get_bool(0x0000_0100, 9));
355        Ok(())
356    }
357
358    #[test]
359    fn set_bool_preserved_unmasked_value() -> unittest::Result<()> {
360        unittest::assert_eq!(ops::set_bool(0xffff_ffff, 16, false), 0xfffe_ffff);
361        Ok(())
362    }
363
364    #[test]
365    fn get_u32_extracts_correct_value() -> unittest::Result<()> {
366        unittest::assert_eq!(ops::get_u32(0x5555_aa55, 8, 15), 0xaa);
367        Ok(())
368    }
369
370    #[test]
371    fn set_u32_preserves_unmasked_value() -> unittest::Result<()> {
372        unittest::assert_eq!(ops::set_u32(0x5555_5555, 8, 15, 0xaa), 0x5555_aa55);
373        Ok(())
374    }
375
376    #[test]
377    fn single_bit_get_u32_extracts_correct_value() -> unittest::Result<()> {
378        unittest::assert_eq!(ops::get_u32(0x0001_0000, 16, 16), 0b1);
379        Ok(())
380    }
381
382    #[test]
383    fn single_bit_set_u32_sets_correct_value() -> unittest::Result<()> {
384        unittest::assert_eq!(ops::set_u32(0xffff_ffff, 16, 16, 0b0), 0xfffe_ffff);
385        Ok(())
386    }
387
388    #[test]
389    fn get_usize_extracts_correct_value() -> unittest::Result<()> {
390        #[cfg(target_pointer_width = "64")]
391        unittest::assert_eq!(ops::get_usize(0x5555_aa55_5555_5555, 8 + 32, 15 + 32), 0xaa);
392        #[cfg(target_pointer_width = "32")]
393        unittest::assert_eq!(ops::get_usize(0x5555_aa55, 8, 15), 0xaa);
394        Ok(())
395    }
396
397    #[test]
398    fn set_usize_preserves_unmasked_value() -> unittest::Result<()> {
399        #[cfg(target_pointer_width = "64")]
400        unittest::assert_eq!(
401            ops::set_usize(0x5555_5555_5555_5555, 8 + 32, 15 + 32, 0xaa),
402            0x5555_aa55_5555_5555
403        );
404        #[cfg(target_pointer_width = "32")]
405        unittest::assert_eq!(ops::set_usize(0x5555_5555, 8, 15, 0xaa), 0x5555_aa55);
406        Ok(())
407    }
408
409    #[test]
410    fn single_bit_get_usize_extracts_correct_value() -> unittest::Result<()> {
411        #[cfg(target_pointer_width = "64")]
412        unittest::assert_eq!(ops::get_usize(0x0001_0000_0000_0000, 48, 48), 0b1);
413        #[cfg(target_pointer_width = "32")]
414        unittest::assert_eq!(ops::get_usize(0x0001_0000, 16, 16), 0b1);
415        Ok(())
416    }
417
418    #[test]
419    fn single_bit_set_usize_sets_correct_value() -> unittest::Result<()> {
420        #[cfg(target_pointer_width = "64")]
421        unittest::assert_eq!(
422            ops::set_usize(0xffff_ffff_ffff_ffff, 48, 48, 0b0),
423            0xfffe_ffff_ffff_ffff
424        );
425        #[cfg(target_pointer_width = "32")]
426        unittest::assert_eq!(ops::set_usize(0xffff_ffff, 16, 16, 0b0), 0xfffe_ffff);
427        Ok(())
428    }
429}