regio 0.3.0

High level abstractions for register access of all sorts
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// Copyright (c) 2026 Joshua Seaton
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#![no_std]

pub mod riscv;

use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr;

use zerocopy::{FromBytes, IntoBytes};

/// Associates a type as being a register addressed at a fixed offset.
///
/// Requires that the type implements `core::ops::Deref` and
/// `From<<Self as core::ops::Deref>::Target>`. Implements
/// [`Register`] (with `Base = <Self as core::ops::Deref>::Target` and
/// `Addr = regio::Offset`), [`FixedAddr`], and the appropriate access marker
/// traits ([`Readable`] and/or [`Writable`]).
///
/// ## Parameters
///
/// Comma-separated and positional:
///
///   - *Required:* the register offset as a `usize` expression.
///     <br><br>
///   - *Optional:* one of `ro`, `rw`, or `wo`, indicating read-only,
///     read-write, or write-only access, respectively.
///
///     *Default:* `rw`
///
pub use regio_macro::offset;

/// An abstract means of register access.
pub trait IoBackend {
    /// The underlying value type for register reads and writes.
    type Base;

    /// The type used to address registers.
    type Addr;

    /// Read a value at the given address.
    fn read_at(&self, addr: Self::Addr) -> Self::Base;

    /// Write a value to the given address.
    fn write_at(&self, value: Self::Base, addr: Self::Addr);
}

/// An [`IoBackend`] extension supporting atomic read-modify-write operations.
pub trait AtomicIoBackend: IoBackend {
    /// Atomically swap the value at the given address, returning the original.
    fn atomic_swap_at(&self, value: Self::Base, addr: Self::Addr) -> Self::Base;

    /// Atomically set the indicated bits at the given address, returning the
    /// original value.
    fn atomic_set_bits_at(&self, bits: Self::Base, addr: Self::Addr) -> Self::Base;

    /// Atomically clear the indicated bits at the given address, returning the
    /// original value.
    fn atomic_clear_bits_at(&self, bits: Self::Base, addr: Self::Addr) -> Self::Base;
}

/// A marker trait for registers permitting reads.
pub trait Readable {}

/// A marker trait for registers permitting writes.
pub trait Writable {}

/// A register with a fixed, known address.
pub trait FixedAddr: Register {
    const ADDR: Self::Addr;
}

/// A register with no fixed address.
pub trait UnfixedAddr: Register {}

/// A register with a default (and default-constructible) I/O backend.
pub trait DefaultIo: Register {
    type Io: Default + IoBackend<Base = Self::Base, Addr = Self::Addr>;
}

/// A register type, with flexibly abstracted I/O and addressing.
pub trait Register: From<Self::Base> + Deref<Target = Self::Base> {
    /// The underlying type of the register (expected to be an unsigned integral
    /// type).
    type Base: Copy;

    /// An abstract register addressing scheme, which need not represent a
    /// conventional address in memory.
    type Addr: Copy;

    /// Only enabled if the register is readable with an unfixed address, this
    /// method reads the register value from any compatible backend at a given
    /// address.
    #[inline]
    fn read_from_at<Io>(io: &Io, addr: Self::Addr) -> Self
    where
        Self: Readable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
    {
        Self::from(io.read_at(addr))
    }

    /// Only enabled if the register is readable with a fixed address, this
    /// method reads the register value from any compatible I/O backend at its
    /// associated address.
    #[inline]
    fn read_from<Io>(io: &Io) -> Self
    where
        Self: Readable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
    {
        Self::from(io.read_at(Self::ADDR))
    }

    /// Only enabled if the register is readable with an unfixed address and a
    /// default I/O backend, this reads the register from its associated backend
    /// at the given address.
    #[inline]
    fn read_at(addr: Self::Addr) -> Self
    where
        Self: Readable + UnfixedAddr + DefaultIo,
    {
        Self::from(Self::Io::default().read_at(addr))
    }

    /// Only enabled if the register is readable with a fixed address and a
    /// default I/O backend, this method reads the register value from its
    /// associated backend at its associated address.
    #[inline]
    fn read() -> Self
    where
        Self: Readable + FixedAddr + DefaultIo,
    {
        Self::from(Self::Io::default().read_at(Self::ADDR))
    }

    /// Only enabled if the register is writable with an unfixed address, this
    /// method writes the register value to any compatible I/O backend at a
    /// given address.
    #[inline]
    fn write_to_at<Io>(self, io: &Io, addr: Self::Addr)
    where
        Self: Writable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
    {
        io.write_at(*self, addr)
    }

    /// Only enabled if the register is writable with a fixed address, this
    /// method writes the register value to any compatible I/O backend at its
    /// associated address.
    #[inline]
    fn write_to<Io>(self, io: &Io)
    where
        Self: Writable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
    {
        io.write_at(*self, Self::ADDR)
    }

    /// Only enabled if the register is writable with an unfixed address and a
    /// default I/O backend, this method writes the register value to the
    /// associated backend at a given address.
    #[inline]
    fn write_at(self, addr: Self::Addr)
    where
        Self: Writable + UnfixedAddr + DefaultIo,
    {
        Self::Io::default().write_at(*self, addr)
    }

    /// Only enabled if the register is writable with a fixed address and a
    /// default I/O backend, this method writes the register value to the
    /// associated backend at the associated address.
    #[inline]
    fn write(self)
    where
        Self: Writable + FixedAddr + DefaultIo,
    {
        Self::Io::default().write_at(*self, Self::ADDR)
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address, this method performs a read-modify-write on any compatible
    /// I/O backend at a given address.
    #[inline]
    fn modify_with_at<Io, F>(io: &Io, mutate: F, addr: Self::Addr)
    where
        Self: Readable + Writable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
        F: FnOnce(&mut Self),
    {
        let mut value = Self::read_from_at(io, addr);
        mutate(&mut value);
        value.write_to_at(io, addr)
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address, this method performs a read-modify-write on any compatible
    /// I/O backend at its associated address.
    #[inline]
    fn modify_with<Io, F>(io: &Io, mutate: F)
    where
        Self: Readable + Writable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr>,
        F: FnOnce(&mut Self),
    {
        let mut value = Self::read_from(io);
        mutate(&mut value);
        value.write_to(io)
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address and a default I/O backend, this method performs a
    /// read-modify-write with its associated backend at a given address.
    #[inline]
    fn modify_at<F>(mutate: F, addr: Self::Addr)
    where
        Self: Readable + Writable + UnfixedAddr + DefaultIo,
        F: FnOnce(&mut Self),
    {
        let mut value = Self::read_at(addr);
        mutate(&mut value);
        value.write_at(addr)
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address and a default I/O backend, this method performs a
    /// read-modify-write with its associated backend at its associated address.
    #[inline]
    fn modify<F>(mutate: F)
    where
        Self: Readable + Writable + FixedAddr + DefaultIo,
        F: FnOnce(&mut Self),
    {
        let mut value = Self::read();
        mutate(&mut value);
        value.write()
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address, this method atomically swaps the current register value with a
    /// new one on any compatible atomic I/O backend at a given address,
    /// returning the original value.
    #[inline]
    fn atomic_swap_with_at<Io>(value: Self, io: &Io, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_swap_at(*value, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address, this method atomically swaps the current register value with a
    /// new one on any compatible atomic I/O backend at its associated address,
    /// returning the original value.
    #[inline]
    fn atomic_swap_with<Io>(value: Self, io: &Io) -> Self
    where
        Self: Readable + Writable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_swap_at(*value, Self::ADDR))
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address and a default atomic I/O backend, this method atomically swaps
    /// the current register value with a new one at a given address, returning
    /// the original value.
    #[inline]
    fn atomic_swap_at(value: Self, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_swap_at(*value, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address and a default atomic I/O backend, this method atomically swaps
    /// the current register value with a new one at its associated address,
    /// returning the original value.
    #[inline]
    fn atomic_swap(value: Self) -> Self
    where
        Self: Readable + Writable + FixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_swap_at(*value, Self::ADDR))
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address, this method atomically sets the indicated bits in the current
    /// register value on any compatible atomic I/O backend at a given address,
    /// returning the original value.
    #[inline]
    fn atomic_set_bits_with_at<Io>(bits: Self, io: &Io, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_set_bits_at(*bits, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address, this method atomically sets the indicated bits in the current
    /// register value on any compatible atomic I/O backend at its associated
    /// address, returning the original value.
    #[inline]
    fn atomic_set_bits_with<Io>(bits: Self, io: &Io) -> Self
    where
        Self: Readable + Writable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_set_bits_at(*bits, Self::ADDR))
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address and a default atomic I/O backend, this method atomically sets
    /// the indicated bits in the current register value at a given address,
    /// returning the original value.
    #[inline]
    fn atomic_set_bits_at(bits: Self, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_set_bits_at(*bits, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address and a default atomic I/O backend, this method atomically sets
    /// the indicated bits in the current register value at its associated
    /// address, returning the original value.
    #[inline]
    fn atomic_set_bits(bits: Self) -> Self
    where
        Self: Readable + Writable + FixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_set_bits_at(*bits, Self::ADDR))
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address, this method atomically clears the indicated bits in the current
    /// register value on any compatible atomic I/O backend at a given address,
    /// returning the original value.
    #[inline]
    fn atomic_clear_bits_with_at<Io>(bits: Self, io: &Io, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_clear_bits_at(*bits, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address, this method atomically clears the indicated bits in the current
    /// register value on any compatible atomic I/O backend at its associated
    /// address, returning the original value.
    #[inline]
    fn atomic_clear_bits_with<Io>(bits: Self, io: &Io) -> Self
    where
        Self: Readable + Writable + FixedAddr,
        Io: IoBackend<Base = Self::Base, Addr = Self::Addr> + AtomicIoBackend,
    {
        Self::from(io.atomic_clear_bits_at(*bits, Self::ADDR))
    }

    /// Only enabled if the register is readable and writable with an unfixed
    /// address and a default atomic I/O backend, this method atomically clears
    /// the indicated bits in the current register value at a given address,
    /// returning the original value.
    #[inline]
    fn atomic_clear_bits_at(bits: Self, addr: Self::Addr) -> Self
    where
        Self: Readable + Writable + UnfixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_clear_bits_at(*bits, addr))
    }

    /// Only enabled if the register is readable and writable with a fixed
    /// address and a default atomic I/O backend, this method atomically clears
    /// the indicated bits in the current register value at its associated
    /// address, returning the original value.
    #[inline]
    fn atomic_clear_bits(bits: Self) -> Self
    where
        Self: Readable + Writable + FixedAddr + DefaultIo<Io: AtomicIoBackend>,
    {
        Self::from(Self::Io::default().atomic_clear_bits_at(*bits, Self::ADDR))
    }
}

/// An offset into an MMIO aperture at some context-defined stride.
#[derive(Clone, Copy, Debug)]
pub struct Offset(pub usize);

impl Deref for Offset {
    type Target = usize;

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

mod internal {
    pub trait FitsIn<Access> {
        fn widen(self) -> Access;
        fn truncate(access: Access) -> Self;
    }

    macro_rules! fits_in {
        ($narrow:ty, $wide:ty) => {
            impl FitsIn<$wide> for $narrow {
                fn widen(self) -> $wide {
                    self as $wide
                }
                fn truncate(wide: $wide) -> Self {
                    wide as Self
                }
            }
        };
    }

    fits_in!(u8, u8);
    fits_in!(u8, u16);
    fits_in!(u8, u32);
    fits_in!(u8, u64);
    fits_in!(u16, u16);
    fits_in!(u16, u32);
    fits_in!(u16, u64);
    fits_in!(u32, u32);
    fits_in!(u32, u64);
    fits_in!(u64, u64);
}
/// Represents an aperture of memory-mapped I/O.
///
/// Implements an [`IoBackend`] parameterized by the logical register width
/// (`Reg`) and the physical bus width (`Access`, defaulting to `Reg`),
/// addressed by register offset ([`Offset`]).
///
/// ```
/// use regio::Mmio;
///
/// // An 8-bit register space at 0x1000'0000 spanning 8 bytes.
/// let io = Mmio::<u8>::new(0x1000_0000, 8);
///
/// // 8-bit registers accessed at 0x1000'0000 over a 32-bit bus, spanning
/// // sizeof(u32) * 8 bytes.
/// let io = Mmio::<u8, u32>::new(0x1000_0000, 8);
/// ```
///
/// `Reg` is bounded by an internal trait representing a register value type
/// that can be widened to and truncated from a type representing a wider bus
/// width. This trait is implemented for for all pairs of unsigned integer types
/// up to u64 where `Self` is no wider than `Access`.
pub struct Mmio<Reg, Access = Reg>
where
    Reg: internal::FitsIn<Access>,
    Access: FromBytes + IntoBytes,
{
    base: *mut Access,
    size: usize,
    phantom: PhantomData<Reg>,
}

impl<Reg, Access> Mmio<Reg, Access>
where
    Reg: internal::FitsIn<Access>,
    Access: FromBytes + IntoBytes,
{
    /// Creates an MMIO backend over the given aperture.
    pub fn new(base: usize, size: usize) -> Self {
        Self {
            base: ptr::without_provenance_mut(base),
            size,
            phantom: PhantomData {},
        }
    }
}

impl<Reg, Access> IoBackend for Mmio<Reg, Access>
where
    Reg: internal::FitsIn<Access>,
    Access: FromBytes + IntoBytes,
{
    type Addr = Offset;
    type Base = Reg;

    fn read_at(&self, offset: Offset) -> Reg {
        debug_assert!(*offset < self.size);
        unsafe {
            let ptr = self.base.add(*offset);
            Reg::truncate(ptr::read_volatile(ptr))
        }
    }

    fn write_at(&self, value: Reg, offset: Offset) {
        debug_assert!(*offset < self.size);
        unsafe {
            let ptr = self.base.add(*offset);
            ptr::write_volatile(ptr, value.widen())
        }
    }
}