rust-embedded-community / tm4c-hal

An Embedded HAL and general chip support for the TM4C123/LM4F120. Replaces the old lm4f120 crate.
Apache License 2.0
40 stars 27 forks source link

Move out the bit-banding code #9

Open chrysn opened 6 years ago

chrysn commented 6 years ago

The bb module in this HAL is well usable for other chips, I'd like to suggest splitting it out for easier re-use. (Right now I've copy-pasted it to the efm32gg-hal crate).

Not only is the code generic over various chips, but also for memory regions. The comments to ref_to_bitband say it can be used only things slightly above 0x2000_000, but actually works for the peripheral registers at 0x4000_0000 just as well.

I expect the challenge to be the characterization of where the resulting bit-banding crate could be applicable. The most generic document I found that describes this very mechanism is 2.2. Memory Model of the Cortex-M4 Generic User Guide, but it appears to be applicable to M3 (at least EFM32) as well.

thejpster commented 6 years ago

Humm. So I think how I'd propose to make this generic, is to create a Bitband object which represents each region:

pub struct Bitband {
    start_addr: usize,
    bitband_addr: usize,
    len: usize
}

impl Bitband {
    pub unsafe fn new(start: usize, bitband: usize, len: usize) -> Bitband { .. }
    pub fn read_bit<T>(&self, address: *const T, bit: u8) -> bool  { ... }
    ...
}

The various XXX-hal implementations (or even cortex-m) can then do the unsafe bit and make you an object that's safe to use. I agree the Cortex-M4 spec gives the two regions, but the size of the first region will depend on the amount of SRAM you have on-chip.

chrysn commented 6 years ago

With this Bitband struct, constant propagation and LTO would ensure that bitband access is the single-static-address-no-runtime-checks operation I'd want for most cases. Do we want/need to consider use cases with less optimization (eg. by encoding addresses and sizes in the type rather than in struct members)? ("No" is a perfectly good answer just as well, just want to make sure we considered it.)

thejpster commented 6 years ago

Sorry, this one dropped off my radar. In response to your last comment, that sounds interesting, but I'd add that as an additional variant later and working out how that would work shouldn't hold up the basic case outlined at the top.