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
/***********************************************************************************************************************
 * Copyright (c) 2019 by the authors
 *
 * Author: André Borrmann <pspwizard@gmx.de>
 * License: Apache License 2.0 / MIT
 **********************************************************************************************************************/
#![doc(html_root_url = "https://docs.rs/ruspiro-mmio-register/0.1.0")]
// we require to run with 'std' in unit tests and doc tests to have an allocator in place
#![cfg_attr(not(any(test, doctest)), no_std)]
#![feature(const_fn)]

//! # RusPiRo MMIO Register
//!
//! This crate provides a macro to conveniently define memory mapped I/O registers.
//!
//! ```no_run
//! # use ruspiro_mmio_register::*;
//! define_mmio_register!(
//!     /// FOO Register with read/write access, 32 bit wide and mapped at memory
//!     /// address 0x3F20_0000
//!     FOO<ReadWrite<u32>@(0x3F20_0000)> {
//!         /// This register provides a field BAR at offset 0 covering 1 Bit
//!         BAR OFFSET(0),
//!         /// There is another field BAZ at offset 1 covering 3 Bits
//!         BAZ OFFSET(1) BITS(3),
//!         /// The third field BAL also has specific predefined values
//!         BAL OFFSET(4) BITS(2) [
//!             /// Field Value 1
//!             VAL1 = 0b01,
//!             /// Field Value 2
//!             VAL2 = 0b10
//!         ]
//!     }
//! );
//! 
//! fn main() {
//!     // write a specific value to a field of the register
//!     FOO::Register.write_value( FOO::BAL::VAL1 );
//! 
//!     // combine two field values with logical OR
//!     FOO::Register.write_value( FOO::BAL::VAL1 | FOO::BAL::VAL2 );
//! 
//!     // if there is no field defined for the MMIO register or raw value storage
//!     // is preffered the raw value could be written
//!     FOO::Register.write_value(FOO::BAZ::with_value(0b101));
//!     FOO::Register.write(FOO::BAZ, 0b101);
//!     FOO::Register.set(0x1F);
//! 
//!     // reading from the MMIO register works in a simmilar way
//!     let baz_val = FOO::Register.read(FOO::BAL); // return 0b01 or 0b10 eg.
//!     let baz_field = FOO::Register.read_value(FOO::BAL); // returns a FieldValue
//!     let raw_val = FOO::Register.get();
//! }
//! ```
//!

use core::cmp::PartialEq;
use core::ops::{BitAnd, BitOr, Not, Shl, Shr};
use core::ptr::{read_volatile, write_volatile};

pub mod macros;

/// This trait is used to describe the register size/length as type specifier. The trait is only implemented for the
/// internal types **u8**, **u16**, **u32** and **u64** to ensure safe register access sizes with compile time checking
pub trait RegisterType:
    Copy
    + Clone
    + PartialEq
    + BitOr<Output = Self>
    + BitAnd<Output = Self>
    + Not<Output = Self>
    + Shl<Self, Output = Self>
    + Shr<Self, Output = Self>
{
}

// Internal macro to ease the assignment of the custom trait to supported register sizes
#[doc(hidden)]
macro_rules! registertype_impl {
    // invoke the macro for a given type t as often as types are provided when invoking the macro
    ($( $t:ty ),*) => ($(
        impl RegisterType for $t { }
    )*)
}

// implement the type trait for specific unsigned types to enable only those register types/sizes
registertype_impl![u8, u16, u32, u64];

/// This struct allows read only access to a register.
#[derive(Clone, Debug)]
pub struct ReadOnly<T: RegisterType> {
    ptr: *mut T, // base address for the register
}

/// This struct allows write only access to a register.
#[derive(Clone, Debug)]
pub struct WriteOnly<T: RegisterType> {
    ptr: *mut T, // base address for the register
}

/// This struct allows read/write access to a register.
#[derive(Clone, Debug)]
pub struct ReadWrite<T: RegisterType> {
    ptr: *mut T, // base address for the register
}

/*************** internal used macros to ease implementation ******************/
macro_rules! registernew_impl {
    () => {
        /// Create a new instance of the register access struct.
        #[allow(dead_code)]
        pub const fn new(addr: u32) -> Self {
            Self {
                ptr: addr as *mut T,
            }
        }
    };
}

macro_rules! registerget_impl {
    () => {
        /// Read raw content of a register.
        #[inline]
        #[allow(dead_code)]
        pub fn get(&self) -> T {
            unsafe { read_volatile(self.ptr) }
        }

        /// Read the value of a specific register field
        #[inline]
        #[allow(dead_code)]
        pub fn read(&self, field: RegisterField<T>) -> T {
            let val = self.get();
            (val >> field.shift) & field.mask
        }

        /// Read the value of the register into a RegisterFieldValue structure
        #[inline]
        #[allow(dead_code)]
        pub fn read_value(&self, field: RegisterField<T>) -> RegisterFieldValue<T> {
            RegisterFieldValue {
                field,
                value: self.read(field),
            }
        }
    };
}

macro_rules! registerset_impl {
    () => {
        /// Write raw content value to the register.
        #[inline]
        #[allow(dead_code)]
        pub fn set(&self, value: T) {
            unsafe { write_volatile(self.ptr, value) }
        }

        /// Write the value of a specific register field
        #[inline]
        #[allow(dead_code)]
        pub fn write(&self, field: RegisterField<T>, value: T) {
            let val = (value & field.mask) << field.shift;
            self.set(val);
        }

        /// Write the value of a given RegisterFieldValue to the register
        #[inline]
        #[allow(dead_code)]
        pub fn write_value(&self, fieldvalue: RegisterFieldValue<T>) {
            self.write(fieldvalue.field, fieldvalue.value);
        }
    };
}

impl<T: RegisterType> ReadOnly<T> {
    registernew_impl!();
    registerget_impl!();
}

impl<T: RegisterType> WriteOnly<T> {
    registernew_impl!();
    registerset_impl!();
}

impl<T: RegisterType> ReadWrite<T> {
    registernew_impl!();
    registerget_impl!();
    registerset_impl!();

    /// Udate a register field with a given value
    #[inline]
    #[allow(dead_code)]
    pub fn modify(&self, field: RegisterField<T>, value: T) -> T {
        let old_val = self.get();
        let new_val =
            (old_val & !(field.mask << field.shift)) | ((value & field.mask) << field.shift);

        self.set(new_val);
        new_val
    }

    #[inline]
    #[allow(dead_code)]
    pub fn modify_value(&self, fieldvalue: RegisterFieldValue<T>) -> RegisterFieldValue<T> {
        let new_val = self.modify(fieldvalue.field, fieldvalue.value);
        RegisterFieldValue {
            field: fieldvalue.field,
            value: new_val,
        }
    }
}

/// Definition of a field contained inside of a register. Each field is defined by a mask and the bit shift value
/// when constructing the field definition the stored mask is already shifted by the shift value
#[derive(Copy, Clone, Debug)]
pub struct RegisterField<T: RegisterType> {
    mask: T,
    shift: T,
}

/// Definition of a specific fieldvalue of a regiser. This structure allows to combine field values with bit operators
/// like ``|`` and ``&`` to build the final value that should be written to a register
#[derive(Copy, Clone, Debug)]
pub struct RegisterFieldValue<T: RegisterType> {
    /// register field definition
    field: RegisterField<T>,
    /// register field value
    value: T,
}

// Internal helper macro to implement:
// - ``RegisterField``struct for all relevant basic types
// - ``FieldValue`` struct for all relevant basic types
// - the operators for ``FieldValue``struct for all relevant basic types
#[doc(hidden)]
macro_rules! registerfield_impl {
    ($($t:ty),*) => ($(
        impl RegisterField<$t> {
            /// Create a new register field definition with the mask and the shift offset for this
            /// mask. The offset is the bit offset this field begins.
            #[inline]
            #[allow(dead_code)]
            pub const fn new(mask: $t, shift: $t) -> RegisterField<$t> {
                Self {
                    mask,
                    shift,
                }
            }

            /// retrieve the current mask of the field shifted to its correct position
            #[inline]
            #[allow(dead_code)]
            pub fn mask(&self) -> $t {
                self.mask.checked_shl(self.shift as u32).unwrap_or(0)
            }

            /// retrieve the current shift of the field
            #[allow(dead_code)]
            #[inline]
            pub fn shift(&self) -> $t {
                self.shift
            }
        }

        impl RegisterFieldValue<$t> {
            /// Create a new fieldvalue based on the field definition and the value given
            #[inline]
            #[allow(dead_code)]
            pub const fn new(field: RegisterField<$t>, value: $t) -> Self {
                RegisterFieldValue {
                    field,
                    value: value & field.mask //<< field.shift
                }
            }

            /// Retrieve the register field value
            #[inline]
            #[allow(dead_code)]
            pub fn value(&self) -> $t {
                self.value //>> self.field.shift()
            }

            /// Retrieve the register field raw value, means the value is returned in it's position
            /// as it appears in the register when read with the field mask applied but not
            /// shifted
            #[inline]
            #[allow(dead_code)]
            pub fn raw_value(&self) -> $t {
                self.value.checked_shl(self.field.shift as u32).unwrap_or(0)
            }

            /// Retrieve the field mask used with this register field. The mask is shifted to it's
            /// corresponding field position
            #[inline]
            #[allow(dead_code)]
            pub fn mask(&self) -> $t {
                self.field.mask()
            }
        }

        impl BitOr for RegisterFieldValue<$t> {
            type Output = RegisterFieldValue<$t>;

            #[inline]
            #[allow(dead_code)]
            fn bitor(self, rhs: RegisterFieldValue<$t>) -> Self {
                let field = RegisterField::<$t>::new( self.field.mask() | rhs.field.mask(), 0);
                RegisterFieldValue {
                    field,
                    value: (self.raw_value() | rhs.raw_value()),
                }
            }
        }

        impl BitAnd for RegisterFieldValue<$t> {
            type Output = RegisterFieldValue<$t>;
            #[inline]
            #[allow(dead_code)]
            fn bitand(self, rhs: RegisterFieldValue<$t>) -> Self {
                let field = RegisterField::<$t>::new( self.field.mask() & rhs.field.mask(), 0);
                RegisterFieldValue {
                    field,
                    value: (self.raw_value() & rhs.raw_value()),
                }
            }
        }
    )*);
}

registerfield_impl![u8, u16, u32, u64];