hackndev / zinc

The bare metal stack for rust
zinc.rs
Apache License 2.0
1k stars 100 forks source link

Conventions for reference mutability of hardware resources #377

Open gsnoff opened 8 years ago

gsnoff commented 8 years ago

Currently, all methods in traits describing hardware classes (such as GPIO pins and SPI bus interfaces) use non-mutable &self pointers. This might cause problems with two or more consumers meddling with hardware state at the same time and getting into race conditions, for example, which are going to be very hard to diagnose at some point.

I have a suggestion to make the methods require &mut self pointers, except for those which are generally thread-safe and, more importantly, guaranteed to not change hardware state. What this means, is that operations such as send, receive (since it shifts buffer registers), write pin state, change pinmux configuration etc. should require mutability of the corresponding hardware resource. However peek (get buffer contents without shifting it), read pin state, get current time and similar operations may be made to work with non-mutable resources.

Also, in case of devices depending on underlying lower-level resources (for example, most real-time clocks and on-board sensors using buses such as I2C or SPI), the device driver owning mutable references to those resources may expose methods which don't require mutability - for operations which don't change the overall hardware state except for lower level bus registers etc., abstracted away by the driver. The driver, however, should ensure thread safety of those methods via locking mechanisms, atomicity guarantees and whatnot.

farcaller commented 8 years ago

That sounds like an overall good idea, but I'm not sure that the hardware is always used in exclusive mode, e.g. it's a valid, and often used scenario to have several devices on SPI bus, so you can't hold the &mut on it. This noted, it should be a scheduled exclusive access, so maybe it's actually a job for a mutex-like thing.

gsnoff commented 8 years ago

In case of SPI, I think it'd be reasonable to make the drivers provide separate chipselect resources which would abstract away their mutual exclusiveness with mutexing or spinlocking when needed.

farcaller commented 8 years ago

Sounds good.