Module spin_lock::smplock

source ·
Expand description

SMP-supported spinlock.

Implementing spinlock for multiprocessor.

The implementing unicore spinlock uniprocessor is simple; it just requires preventing thread preemption while holding a lock. By disabling preemption of the lock-holding thread, other threads cannot access shared resource as they can’t be scheduled.

However, when it comes to multiprocessor, disabling preemption is not sufficient; as multiple threads run concurrently in different cores, they can access shared resource at the same time even when a core disable preemption. Therefore, to acquire a lock on multi-processor, a processor 1) polls a variable that represents a value is locked or not 2) set the variable when a thread holds the lock, and 3) unset the variable when the thread unlock.

The step 1 and 2 must be executed ATOMICALLY. Therefore, it is required to use atomic read-modify-write instructions supported by CPU. Rust supports abstraction for those instructions through core::sync::atomic module. You can implements atomic read-modify-write multiple ways through core::sync::atomic::Atomic*’s methods. However, we recommend to use fetch_or method for simplicity.

For the arguments that takes Ordering, just use Ordering::SeqCst. There exists more optimized Ordering but it is beyond the project’s scope. For those who want to know the details, see the https://en.wikipedia.org/wiki/Memory_ordering.

Getting started

When you runs following command lines in the spin_lock directory, you can see the test failed message.

$ cargo test --features=smp

...
thread '<unnamed>' panicked at 'not yet implemented', src/smplock.rs:204:9
thread '<unnamed>' panicked at 'not yet implemented', src/smplock.rs:204:9
...

If you go to the 204 line of src/smplock.rs, you can see the todo!() macro. You can start your implementation from there.

There are several todo!() macros, which will guide you about the implemenation order to run the test.

After implementing the multiprocessor spinlock, you can boot keos. Continue Project 1.

Structs

A mutual exclusion primitive useful for protecting shared data
An RAII implementation of a “scoped lock” of a spinlock. When this structure is dropped (falls out of scope), the lock will be unlocked.

Enums

An enumeration of possible errors associated while trying to acquire a lock, from the try_lock method on a SpinLock.