[][src]Crate ruspiro_lock

Atomic locks for Raspberry Pi baremetal systems

This crate provides two options of locks and a data access guard. Spinlock, Semaphore, DataLock. They provide mechanisms to secure cross core access to shared data like MMIO registers of peripherals. As the locks depend on low level atomics they do only work on the Raspberry Pi if the MMU is properly configured. Otherwise using either of the lock functions will hang the core it has been used on.

Usage

Using a Spinlock to ensure exclusive access.

use ruspiro_lock::Spinlock;

static SPIN: Spinlock = Spinlock::new();

fn main() {
    SPIN.aquire();
    // following code is only executed if the lock could be aquired, the executing core pause till then
    let _ = 10 + 3;
    SPIN.release();
}

Using a Semaphore to specify how often specific access is valid.

use ruspiro_lock::Semaphore;

static mut SEMA: Semaphore = Semaphore::new(1);

fn main() {
    unsafe { // unsafe necessary as accessing mut static's is unsafe
        if SEMA.try_down().is_ok() {
            // we gained access to the semaphore, do something
            let _ = 20 /4;
            SEMA.up();
        }
    }
}

Using/accessing data with atmic lock guard.

use ruspiro_lock::DataLock;

static DATA: DataLock<u32> = DataLock::new(0);

fn main() {
    if let Some(mut data) = DATA.try_lock() {
        *data = 20;
    }
    // once the data goes ot of scope the lock will be released
    if let Some(data) = DATA.try_lock() {
        println!("data: {}", *data);
     
        // another lock should fail inside this scope
        assert!(DATA.try_lock().is_none());
    }
     
    // a blocking lock on the data will block the current execution until the lock get's available
    let mut data = DATA.lock();
    *data = 12;
}

Structs

DataLock

An exclusive access lock around the given data

Semaphore

Simple counting blocking or non-blocking lock

Spinlock

A blocking cross core lock to guarantee mutual exclusive access. While this lock might block other cores to continue processing this lock should be held as short as possible. Also care shall be taken while using this lock within interrupt handlers, as this might lead to deadlock situations if the lock holding core is interrupted and the interrupt is also trying to aquire the same lock.

TryDataLock

Result of trying to access the data using try_lock or lock on the data lock. If the result goes out of scope the lock is released.