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
//! Memory-mapped registers.
//!
//! # Mapping
//!
//! Most of registers should be already mapped by platform crates. These crates
//! should map registers with [`reg!`] macro as follows:
//!
//! ```
//! # #![feature(decl_macro)]
//! # fn main() {}
//! # use std as core;
//! use drone::reg;
//! use drone::reg::prelude::*;
//!
//! reg! {
//!   //! SysTick control and status register.
//!   0xE000_E010 // memory address
//!   0x20 // bit size
//!   Ctrl // register's name
//!   RReg WReg // list of marker traits to implement
//! }
//! ```
//!
//! # Binding
//!
//! It is strongly encouraged to bind registers with a single [`bind!`] block at
//! the very beginning of the application entry point.
//!
//! ```
//! # #![feature(decl_macro)]
//! # use std as core;
//! # mod stk {
//! #   use drone::reg;
//! #   use drone::reg::prelude::*;
//! #   reg!(0xE000_E010 0x20 Ctrl RReg WReg);
//! # }
//! # fn main() {
//! use drone::reg;
//! use drone::reg::prelude::*;
//! use core::mem::size_of_val;
//!
//! reg::bind! {
//!   stk_ctrl: stk::Ctrl<Lr>,
//! }
//!
//! // Use the bindings inside the current scope.
//! assert_eq!(size_of_val(&stk_ctrl), 0);
//! # }
//! ```
//!
//! [`bind!`]: ../macro.bind.html
//! [`reg!`]: ../macro.reg.html

pub mod prelude;

#[doc(hidden)] // FIXME https://github.com/rust-lang/rust/issues/45266
mod flavor;

pub use self::flavor::{Ar, Lr, RegFlavor};
pub use drone_macros::{bind_imp, reg_imp};

use core::fmt::Debug;
use core::mem::size_of;
use core::ops::{BitAnd, BitAndAssign, BitOrAssign, Not, Shl, Shr, Sub};
use core::ptr::{read_volatile, write_volatile};

/// Define a memory-mapped register.
///
/// See the [`module-level documentation`] for more details.
///
/// [`module-level documentation`]: reg/index.html
pub macro bind($($tokens:tt)*) {
  $crate::reg::bind_imp!($($tokens)*);
}

/// Define a memory-mapped register.
///
/// See the [`module-level documentation`] for more details.
///
/// [`module-level documentation`]: reg/index.html
pub macro reg($($tokens:tt)*) {
  $crate::reg::reg_imp!($($tokens)*);
}

/// Memory-mapped register binding. Types which implement this trait should be
/// zero-sized. This is a zero-cost abstraction for safely working with
/// memory-mapped registers.
pub trait Reg<T>
where
  Self: Sized,
  T: RegFlavor,
{
  /// Type that wraps a raw register value.
  type Value: RegValue;

  /// Memory address of the register.
  const ADDRESS: usize;

  /// Register binding constructor. All the safety of the memory-mapped
  /// registers interface is based on a contract that this method must be called
  /// no more than once for a particular register in the whole program.
  unsafe fn bind() -> Self;
}

/// Register that can read its value.
pub trait RReg<T>
where
  Self: Reg<T>,
  T: RegFlavor,
{
  /// Reads and wraps a register value from its memory address.
  #[inline]
  fn read(&self) -> Self::Value {
    Self::Value::new(self.read_raw())
  }

  /// Reads a raw register value from its memory address.
  #[inline]
  fn read_raw(&self) -> <Self::Value as RegValue>::Raw {
    unsafe { read_volatile(self.to_ptr()) }
  }

  /// Returns an unsafe constant pointer to the register's memory address.
  #[inline]
  fn to_ptr(&self) -> *const <Self::Value as RegValue>::Raw {
    Self::ADDRESS as *const <Self::Value as RegValue>::Raw
  }
}

/// Register that can write its value.
pub trait WReg<T>
where
  Self: Reg<T>,
  T: RegFlavor,
{
  /// Writes a wrapped register value to its memory address.
  #[inline]
  fn write_value(&self, value: &Self::Value) {
    self.write_raw(value.raw());
  }

  /// Calls `f` on a default value and writes the result to the register's
  /// memory address.
  #[inline]
  fn write<F>(&self, f: F)
  where
    F: FnOnce(&mut Self::Value) -> &Self::Value,
  {
    self.write_value(f(&mut Self::Value::default()));
  }

  /// Writes a raw register value to its memory address.
  #[inline]
  fn write_raw(&self, value: <Self::Value as RegValue>::Raw) {
    unsafe { write_volatile(self.to_mut_ptr(), value) };
  }

  /// Returns an unsafe mutable pointer to the register's memory address.
  #[inline]
  fn to_mut_ptr(&self) -> *mut <Self::Value as RegValue>::Raw {
    Self::ADDRESS as *mut <Self::Value as RegValue>::Raw
  }
}

/// Register that can read and write its value in a single-threaded context.
pub trait RwLocalReg
where
  Self: RReg<Lr> + WReg<Lr>,
{
  /// Atomically modifies a register's value.
  #[inline]
  fn modify<F>(&self, f: F)
  where
    F: FnOnce(&mut Self::Value) -> &Self::Value;
}

/// Wrapper for a corresponding register's value.
pub trait RegValue
where
  Self: Sized + Default,
{
  /// Raw integer type.
  type Raw: RegRaw;

  /// Constructs a wrapper from the raw register `value`.
  fn new(value: Self::Raw) -> Self;

  /// Returns the raw integer value.
  fn raw(&self) -> Self::Raw;

  /// Returns a mutable reference to the raw integer value.
  fn raw_mut(&mut self) -> &mut Self::Raw;

  /// Checks the set state of the bit of the register's value by `offset`.
  ///
  /// # Panics
  ///
  /// If `offset` is greater than or equals to the platform's word size in bits.
  #[inline]
  fn bit(&self, offset: Self::Raw) -> bool {
    assert!(offset < Self::Raw::size_in_bits());
    self.raw() & Self::Raw::one() << offset != Self::Raw::zero()
  }

  /// Sets or clears the bit of the register's value by `offset`.
  ///
  /// # Panics
  ///
  /// If `offset` is greater than or equals to the platform's word size in bits.
  #[inline]
  fn set_bit(&mut self, offset: Self::Raw, value: bool) -> &mut Self {
    assert!(offset < Self::Raw::size_in_bits());
    let mask = Self::Raw::one() << offset;
    if value {
      *self.raw_mut() |= mask;
    } else {
      *self.raw_mut() &= !mask;
    }
    self
  }

  /// Reads the `width` number of low order bits at the `offset` position from
  /// the raw interger value.
  ///
  /// # Panics
  ///
  /// * If `offset` is greater than or equals to the platform's word size in
  ///   bits.
  /// * If `width + offset` is greater than the platform's word size in bits.
  #[inline]
  fn bits(&self, offset: Self::Raw, width: Self::Raw) -> Self::Raw {
    assert!(offset < Self::Raw::size_in_bits());
    assert!(width <= Self::Raw::size_in_bits() - offset);
    self.raw() >> offset & (Self::Raw::one() << width) - Self::Raw::one()
  }

  /// Copies the `width` number of low order bits from the `value` into the same
  /// number of adjacent bits at the `offset` position at the raw integer value.
  ///
  /// # Panics
  ///
  /// * If `offset` is greater than or equals to the platform's word size in
  ///   bits.
  /// * If `width + offset` is greater than the platform's word size in bits.
  /// * If `value` contains bits outside the width range.
  #[inline]
  fn set_bits(
    &mut self,
    offset: Self::Raw,
    width: Self::Raw,
    value: Self::Raw,
  ) -> &mut Self {
    assert!(offset < Self::Raw::size_in_bits());
    assert!(width <= Self::Raw::size_in_bits() - offset);
    if width != Self::Raw::size_in_bits() {
      assert_eq!(
        value & !((Self::Raw::one() << width) - Self::Raw::one()),
        Self::Raw::zero()
      );
      *self.raw_mut() &=
        !((Self::Raw::one() << width) - Self::Raw::one() << offset);
      *self.raw_mut() |= value << offset;
    } else {
      *self.raw_mut() = value;
    }
    self
  }
}

/// Raw register value type.
pub trait RegRaw
where
  Self: Debug
    + Copy
    + Default
    + PartialOrd
    + BitAndAssign
    + BitOrAssign
    + BitAnd<Output = Self>
    + Not<Output = Self>
    + Sub<Output = Self>
    + Shl<Self, Output = Self>
    + Shr<Self, Output = Self>,
{
  /// Size of the type in bits.
  fn size_in_bits() -> Self;

  /// Returns zero.
  fn zero() -> Self;

  /// Returns one.
  fn one() -> Self;
}

impl<T> RwLocalReg for T
where
  T: RReg<Lr> + WReg<Lr>,
{
  #[inline]
  fn modify<F>(&self, f: F)
  where
    F: FnOnce(&mut Self::Value) -> &Self::Value,
  {
    self.write_value(f(&mut self.read()));
  }
}

macro impl_reg_raw($type:ty) {
  impl RegRaw for $type {
    #[inline]
    fn size_in_bits() -> $type {
      size_of::<$type>() as $type * 8
    }

    #[inline]
    fn zero() -> $type {
      0
    }

    #[inline]
    fn one() -> $type {
      1
    }
  }
}

impl_reg_raw!(u64);
impl_reg_raw!(u32);
impl_reg_raw!(u16);
impl_reg_raw!(u8);