riscv-peripheral 0.5.1

Interfaces for standard RISC-V peripherals
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Common definitions for all the peripheral registers.

/// Read-only type state for `A` in [`Reg`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RO;

/// Write-only type state for `A` in [`Reg`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WO;

/// Read-write type state for `A` in [`Reg`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RW;

/// Generic trait for all the peripheral registers.
/// This trait is sealed and cannot be implemented by any external crate.
pub trait Access: sealed::Access + Copy {}
impl Access for RO {}
impl Access for WO {}
impl Access for RW {}

/// Trait for readable registers.
pub trait Read: Access {}
impl Read for RO {}
impl Read for RW {}

/// Trait for writable registers.
pub trait Write: Access {}
impl Write for WO {}
impl Write for RW {}

/// Generic register structure. `T` refers to the data type of the register.
/// Alternatively, `A` corresponds to the access level (e.g., read-only, read-write...).
///
/// # Note
///
/// This structure assumes that it points to a valid peripheral register.
/// If so, it is safe to read from or write to the register.
/// However, keep in mind that read-modify-write operations may lead to **wrong** behavior.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct Reg<T: Copy, A: Access> {
    ptr: *mut T,
    phantom: core::marker::PhantomData<A>,
}

unsafe impl<T: Copy + Send, A: Access> Send for Reg<T, A> {}
unsafe impl<T: Copy + Sync, A: Access> Sync for Reg<T, A> {}

impl<T: Copy, A: Access> Reg<T, A> {
    /// Creates a new register from a pointer.
    ///
    /// # Safety
    ///
    /// The pointer must be valid and must be correctly aligned.
    #[inline]
    pub const unsafe fn new(ptr: *mut T) -> Self {
        Self {
            ptr,
            phantom: core::marker::PhantomData,
        }
    }

    /// Returns a pointer to the register.
    #[inline]
    pub const fn get_ptr(self) -> *mut T {
        self.ptr
    }
}

impl<T: Copy, A: Read> Reg<T, A> {
    /// Performs a volatile read of the peripheral register with no side effects.
    ///
    /// # Note
    ///
    /// If you want to perform a read-modify-write operation, use [`Reg::modify`] instead.
    #[inline]
    pub fn read(self) -> T {
        // SAFETY: valid address and register is readable
        unsafe { self.ptr.read_volatile() }
    }
}

impl<T: Copy, A: Write> Reg<T, A> {
    /// Performs a volatile write of the peripheral register.
    ///
    /// # Note
    ///
    /// If you want to perform a read-modify-write operation, use [`Reg::modify`] instead.
    #[inline]
    pub fn write(self, val: T) {
        // SAFETY: valid address and register is writable
        unsafe { self.ptr.write_volatile(val) }
    }
}

impl<T: Copy, A: Read + Write> Reg<T, A> {
    /// It modifies the value of the register according to a given function `f`.
    /// After writing the new value to the register, it returns the value returned by `f`.
    ///
    /// # Note
    ///
    /// It performs a non-atomic read-modify-write operation, which may lead to **wrong** behavior.
    #[inline]
    pub fn modify<R>(self, f: impl FnOnce(&mut T) -> R) -> R {
        let mut val = self.read();
        let res = f(&mut val);
        self.write(val);
        res
    }
}

/// Macro to provide bit-wise operations to integer number registers.
macro_rules! bitwise_reg {
    ($TYPE: ty) => {
        impl<A: Read> Reg<$TYPE, A> {
            /// Reads the `n`th bit of the register.
            #[inline]
            pub fn read_bit(self, n: usize) -> bool {
                let mask = 1 << n;
                let val = self.read();
                val & mask == mask
            }

            /// Reads a range of bits of the register specified by the `start` and `end` indexes, both included.
            #[inline]
            pub fn read_bits(self, start: usize, end: usize) -> $TYPE {
                let n_bits = end - start + 1;
                let mask = ((1 << n_bits) - 1) << start;
                let val = self.read();
                (val & mask) >> start
            }
        }

        impl<A: Read + Write> Reg<$TYPE, A> {
            /// Clears the `n`th bit of the register.
            ///
            /// # Note
            ///
            /// It performs a non-atomic read-modify-write operation, which may lead to **wrong** behavior.
            #[inline]
            pub fn clear_bit(self, n: usize) {
                self.modify(|val| *val &= !(1 << n));
            }

            /// Sets the nth bit of the register.
            ///
            /// # Note
            ///
            /// It performs a non-atomic read-modify-write operation, which may lead to **wrong** behavior.
            #[inline]
            pub fn set_bit(self, n: usize) {
                self.modify(|val| *val |= 1 << n);
            }

            /// Writes a range of bits of the register specified by the `start` and `end` indexes, both included.
            #[inline]
            pub fn write_bits(self, start: usize, end: usize, val: $TYPE) {
                let n_bits = end - start + 1;
                let mask = ((1 << n_bits) - 1) << start;
                self.modify(|v| *v = (*v & !mask) | ((val << start) & mask));
            }
        }
    };
}
bitwise_reg!(u8);
bitwise_reg!(u16);
bitwise_reg!(u32);
bitwise_reg!(u64);
bitwise_reg!(u128);
bitwise_reg!(usize);
bitwise_reg!(i8);
bitwise_reg!(i16);
bitwise_reg!(i32);
bitwise_reg!(i64);
bitwise_reg!(i128);
bitwise_reg!(isize);

/// Macro to provide atomic bit-wise operations to integer number registers.
#[cfg(any(
    target_has_atomic = "8",
    target_has_atomic = "16",
    target_has_atomic = "32",
    target_has_atomic = "64",
    target_has_atomic = "ptr"
))]
macro_rules! bitwise_atomic_reg {
    ($TYPE: ty, $ATOMIC: ty) => {
        impl<A: Read + Write> Reg<$TYPE, A> {
            /// Creates a new atomic reference to the register.
            ///
            /// # Safety
            ///
            /// * Register must be properly aligned **for atomic operations**.
            /// * The register must not be accessed through non-atomic operations for the whole lifetime `'a`.
            pub unsafe fn as_atomic<'a>(&self) -> &'a $ATOMIC {
                // SAFETY: guaranteed by the caller
                unsafe { &*self.ptr.cast() }
            }

            /// Clears the `n`th bit of the register atomically.
            ///
            /// # Safety
            ///
            /// * Register must be properly aligned **for atomic operations**.
            /// * The register must not be accessed through non-atomic operations until this function returns.
            #[inline]
            pub unsafe fn atomic_clear_bit(&self, n: usize, order: core::sync::atomic::Ordering) {
                // SAFETY: guaranteed by the caller
                unsafe { self.as_atomic() }.fetch_and(!(1 << n), order);
            }

            /// Sets the `n`th bit of the register atomically.
            ///
            /// # Safety
            ///
            /// * Register must be properly aligned **for atomic operations**.
            /// * The register must not be accessed through non-atomic operations until this function returns.
            #[inline]
            pub unsafe fn atomic_set_bit(&self, n: usize, order: core::sync::atomic::Ordering) {
                // SAFETY: guaranteed by the caller
                unsafe { self.as_atomic() }.fetch_or(1 << n, order);
            }
        }
    };
}

#[cfg(target_has_atomic = "8")]
bitwise_atomic_reg!(u8, core::sync::atomic::AtomicU8);
#[cfg(target_has_atomic = "16")]
bitwise_atomic_reg!(u16, core::sync::atomic::AtomicU16);
#[cfg(target_has_atomic = "32")]
bitwise_atomic_reg!(u32, core::sync::atomic::AtomicU32);
#[cfg(target_has_atomic = "64")]
bitwise_atomic_reg!(u64, core::sync::atomic::AtomicU64);
#[cfg(target_has_atomic = "ptr")]
bitwise_atomic_reg!(usize, core::sync::atomic::AtomicUsize);
#[cfg(target_has_atomic = "8")]
bitwise_atomic_reg!(i8, core::sync::atomic::AtomicI8);
#[cfg(target_has_atomic = "16")]
bitwise_atomic_reg!(i16, core::sync::atomic::AtomicI16);
#[cfg(target_has_atomic = "32")]
bitwise_atomic_reg!(i32, core::sync::atomic::AtomicI32);
#[cfg(target_has_atomic = "64")]
bitwise_atomic_reg!(i64, core::sync::atomic::AtomicI64);
#[cfg(target_has_atomic = "ptr")]
bitwise_atomic_reg!(isize, core::sync::atomic::AtomicIsize);

/// Macro to define the archetypal behavior of registers.
macro_rules! peripheral {
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident) => {
        /// Peripheral register.
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        #[repr(transparent)]
        pub struct $REGISTER {
            register: $crate::common::Reg<$TYPE, $crate::common::$ACCESS>,
        }

        impl $REGISTER {
            /// Creates a new register from an address.
            ///
            /// # Safety
            ///
            /// The address assigned must be valid and must be correctly aligned.
            #[inline]
            pub const unsafe fn new(address: usize) -> Self {
                Self {
                    register: $crate::common::Reg::new(address as _),
                }
            }
        }
    };
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident, $GENERIC: ident) => {
        /// Peripheral register.
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        #[repr(transparent)]
        pub struct $REGISTER<$GENERIC> {
            register: $crate::common::Reg<$TYPE, $crate::common::$ACCESS>,
            _marker: core::marker::PhantomData<$GENERIC>,
        }

        impl<$GENERIC> $REGISTER<$GENERIC> {
            /// Creates a new register from an address.
            ///
            /// # Safety
            ///
            /// The address assigned must be valid and must be correctly aligned.
            #[inline]
            pub const unsafe fn new(address: usize) -> Self {
                Self {
                    register: $crate::common::Reg::new(address as _),
                    _marker: core::marker::PhantomData,
                }
            }
        }
    };
}

/// Macro to define the archetypal behavior of *safe* registers.
/// You must specify the register name, its data type, and its access level.
///
/// # Note
///
/// Safe peripheral registers implement [`core::ops::Deref`] to [`Reg`].
/// You can safely use the dereferenced [`Reg::read`], [`Reg::write`], and/or [`Reg::modify`] methods.
macro_rules! safe_peripheral {
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident) => {
        $crate::common::peripheral!($REGISTER, $TYPE, $ACCESS);

        impl $REGISTER {
            /// Returns the underlying raw register.
            #[inline]
            pub const fn get_register(self) -> $crate::common::Reg<$TYPE, $crate::common::$ACCESS> {
                self.register
            }
        }

        impl core::ops::Deref for $REGISTER {
            type Target = $crate::common::Reg<$TYPE, $crate::common::$ACCESS>;

            fn deref(&self) -> &Self::Target {
                &self.register
            }
        }
    };
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident, $GENERIC: ident) => {
        $crate::common::peripheral!($REGISTER, $TYPE, $ACCESS, $GENERIC);

        impl $REGISTER {
            /// Returns the underlying raw register.
            #[inline]
            pub const fn get_register(self) -> $crate::common::Reg<$TYPE, $crate::common::$ACCESS> {
                self.register
            }
        }

        impl<$GENERIC> core::ops::Deref for $REGISTER<$GENERIC> {
            type Target = $crate::common::Reg<$TYPE, $crate::common::$ACCESS>;

            fn deref(&self) -> &Self::Target {
                &self.register
            }
        }
    };
}

/// Macro to define the archetypal behavior of *unsafe* registers.
/// You must specify the register name, its data type, and its access level.
///
/// # Note
///
/// Unsafe peripheral registers need special care when reading and/or writing.
/// They usually provide additional methods to perform safe (or unsafe) operations.
/// Nevertheless, you can still access the underlying register using the `unsafe get_register(self)` method.
macro_rules! unsafe_peripheral {
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident) => {
        $crate::common::peripheral!($REGISTER, $TYPE, $ACCESS);

        impl $REGISTER {
            /// Returns a raw pointer to the register.
            #[inline]
            pub const fn get_ptr(self) -> *mut $TYPE {
                self.register.get_ptr()
            }

            /// Returns the underlying raw register.
            ///
            /// # Safety
            ///
            /// This register is not supposed to be used directly.
            /// Use the other provided methods instead. Otherwise, use this method at your own risk.
            #[inline]
            pub const unsafe fn get_register(
                self,
            ) -> $crate::common::Reg<$TYPE, $crate::common::$ACCESS> {
                self.register
            }
        }
    };
    ($REGISTER: ident, $TYPE: ty, $ACCESS: ident, $GENERIC: ident) => {
        $crate::common::peripheral!($REGISTER, $TYPE, $ACCESS, $GENERIC);

        impl<$GENERIC> $REGISTER<$GENERIC> {
            /// Returns a raw pointer to the register.
            #[inline]
            pub const fn get_ptr(self) -> *mut $TYPE {
                self.register.get_ptr()
            }

            /// Returns the underlying register.
            ///
            /// # Safety
            ///
            /// This register is not supposed to be used directly.
            /// Use the other provided methods instead. Otherwise, use this method at your own risk.
            #[inline]
            pub const unsafe fn get_register(
                self,
            ) -> $crate::common::Reg<$TYPE, $crate::common::$ACCESS> {
                self.register
            }
        }
    };
}

pub(crate) use {peripheral, safe_peripheral, unsafe_peripheral};

mod sealed {
    use super::*;
    pub trait Access {}
    impl Access for RO {}
    impl Access for WO {}
    impl Access for RW {}
}