
Recall first from The spin mutex
- UnsafeCell permits interior mutation, and the mutex enforces exclusive access.
- A successful compare-exchange grants ownership of the lock in one atomic operation.
- Dropping the guard clears the flag with release ordering.
When an interrupt takes the same lock
3 min readThe last lesson built the lock. Now you make it interrupt-safe, release it through a Guard's Drop, and initialize global statics once with lazy_static or OnceCell.
The Linux kernel locking guide describes a concrete failure when task context and hard interrupt context share data. The task takes a spin lock and then a local interrupt arrives. The handler tries to take the same lock and spins. The task can resume only after the handler returns, and the handler can return only after the task releases the lock. This can happen on a machine with a single hardware thread. In the course kernel, a task printing through a locked console and a timer handler trying to print through that same console would create exactly this dependency. Linux kernel locking guide
A routine that runs directly in response to a hardware interrupt, before returning to the interrupted execution can enter while a task is anywhere in its critical section. Imagine the UART is ready to accept its next byte and the task needs only one more instruction before it can continue. Once the handler starts spinning, the task still cannot execute that instruction. The duration of the critical section matters for interrupt latency, but even a very short section can deadlock if the handler enters at the wrong time.
For a lock shared with that handler, mask local interrupts before trying to acquire the spin lock. Keep them masked until after releasing it. If you acquire first and mask second, the handler can enter between those operations. If you restore interrupts first during release, a pending interrupt can enter while the lock is still held. On the course's RISC-V kernel, the local mask concerns supervisor interrupts while executing in S-mode. Other harts can keep running, so the spin lock still provides mutual exclusion across harts. Synchronous exceptions can still occur, so a fault or panic path that tries to acquire the same lock needs its own design.
Preemption is a separate scheduling concern. The current task must stay runnable on its hart while it owns a spinning lock, and the kernel must avoid scheduling away from it inside the critical section. In a course kernel where involuntary task switches happen through the local timer interrupt, masking that interrupt prevents timer-driven preemption. The holder must also avoid voluntarily yielding or blocking. If your scheduler has another preemption path, its preemption control must cover acquisition through release as well. Ordinary Linux spin locks disable kernel preemption on non-PREEMPT_RT kernels, and spin_lock_irqsave() also saves and masks local interrupts. Linux's raw_spin_lock_irqsave() retains strict spinning and interrupt masking semantics on PREEMPT_RT. The Rust kernel in this lesson implements its own equivalent behavior for the locks shared with hard interrupt handlers. Linux kernel lock types
Release the lock through the guard
3 min readHave lock() return a MutexGuard only after acquisition succeeds. The guard borrows the mutex and represents the held lock. Its Deref implementation exposes &T, so you can read the protected value through the guard. Its DerefMut implementation exposes &mut T through a mutable guard, so you can update the value while holding the lock. The lifetime of a reference obtained through the guard prevents safe code from keeping that reference after releasing the guard.
For example, a console write routine can bind let mut guard = console().lock(); and then call guard.write_str(message) if its console implements core::fmt::Write and that trait is in scope. The caller can return the result of the write. The guard drops as the function exits, whether the write returned success or an error. An inner scope can end the guard's lifetime sooner if the routine has other work to do. An explicit drop(guard) also ends the hold immediately.
This is tying cleanup of a resource to the lifetime of an object that owns it. Put the unlock in MutexGuard::drop, so each normal exit, including an early return or a ? that returns an error, releases the lock when it drops the guard. The same cleanup happens during a panic that unwinds through the guard's scope. A kernel that halts or uses panic = "abort" has no such unwinding. Its panic handler cannot assume the guard has run Drop. If a panic arose while writing through the console, trying that same locked console from the panic handler can hang. An emergency diagnostic path can use the existing low-level output path without acquiring the normal console lock.
Keep the guard on the hart that acquired it. The local interrupt state belongs to that hart, and a Drop on a different hart would restore the wrong state. Make the interrupt-safe guard non-Send, and enforce the scheduling rules while it is held. Keep the critical section short. In particular, prepare any data that needs allocation or another subsystem before acquiring the console lock, so writing the message does not accidentally enter that subsystem with interrupts masked.
Going deeperExplore the mechanism
A nested interrupt mask needs both a depth counter and the previous interrupt-enable state, stored per hart. In a push_off/pop_off design, push_off reads the previous local interrupt state and disables interrupts before updating the counter. On the transition from zero to one, it saves that previous state. Each nested call increments the counter and keeps the original saved state. The spin lock acquisition follows push_off.
On release, the guard unlocks the mutex first, then calls pop_off. This decrements the counter while interrupts are still masked. A positive remaining depth means some critical section still needs the mask. At depth zero, restore the state that was saved on the first entry. If the outermost caller already had interrupts disabled, they remain disabled. This is what lets the same locking routine be used from task context and from a handler that entered with local interrupts already disabled.
Suppose a task starts with interrupts enabled, acquires lock A, and then acquires lock B. Dropping B releases B while keeping interrupts masked. Dropping A releases A and restores the enabled state. A depth counter supports nested masking for distinct locks. Acquiring A twice from the same execution context still spins forever on a non-reentrant mutex. If the mutex exposes a nonblocking acquisition, a failed attempt must balance its own push_off immediately because there is no guard to perform that cleanup.
Initialize the console once
4 min readA static can reserve storage for a global console at compile time. Configuring the UART takes executable code and must wait until the registers are accessible. building a value on first use and keeping that value for subsequent users gives you both properties. The shared container starts empty or holds an initializer. The first caller that claims initialization constructs the value and publishes it only after construction completes. If another caller arrives during construction, a synchronized implementation waits for completion. Later callers get a reference to the same object. The console mutex then controls access to that object each time someone writes.
lazy_static! defines a static whose initializer runs on first dereference. It provides a spin_no_std feature for freestanding builds. once_cell::sync::Lazy provides a similar interface through a declared Lazy type, but the default once_cell configuration uses std. For the course kernel you can use a synchronized OnceCell by enabling once_cell's critical-section feature with default features disabled and providing a suitable target critical-section implementation. On a single hart, a backend can exclude interrupts by masking and restoring the local state. If several harts can execute concurrently, the backend must also provide exclusion between them. For the lab, spin::Once supplies a freestanding once cell directly. Enable its once feature if you turned off the crate's default features. The example below was built against spin 0.9.9.
The following example assumes Console::init_polled() is your kernel's UART constructor and IrqSpinMutex::new wraps a value in the interrupt-safe mutex from this lesson. Substitute the names from your tree. The constructor must do the actual UART setup without allocating or calling the normal console output routine.
use spin::Once;
static CONSOLE: Once<IrqSpinMutex<Console>> = Once::new();
fn console() -> &'static IrqSpinMutex<Console> {
CONSOLE.call_once(|| IrqSpinMutex::new(Console::init_polled()))
}
call_once runs the closure for the successful initialization and gives each caller a shared reference to the stored mutex. A static container has storage for the entire kernel run, which is why the accessor can return a 'static reference. The mutex inside the cell still has to be locked before accessing the driver. The cell controls construction and publication. The mutex controls subsequent access to mutable state.
In this freestanding kernel, “before main” means before entering the normal kernel workload. There is no hosted runtime that calls the initializer automatically. Call console() in early boot after the UART is accessible and before enabling any interrupt whose handler can use the console. A spinning initializer can otherwise have the same problem as a spinning lock. If the handler reaches the cell while the interrupted task is constructing its value on that hart, the handler may wait for the very task it suspended. Calling console() from its own initializer would cause a similar dependency. For example, a constructor must avoid logging through a macro that calls console().
A global allocator has a related boot dependency. Keep the registered #[global_allocator] object in a static and use one-time initialization for its runtime heap state. The heap range must already be valid and mapped as required. Initialize that state before the first allocation, even if the first allocation happens before normal kernel entry. In particular, building the heap state must never require that same heap. Computing its start address and writing initial metadata into the reserved region can work without allocating a collection.
To verify exactly-once behavior, count entries into the console constructor itself. For the single-hart early-boot test, a separate spin::Mutex<usize> can hold the counter if both increment and inspection happen before interrupts are enabled and no handler touches it. Increment inside the closure, then call the accessor twice from boot code. After both calls return, assert that the count is 1 and compare the returned references with core::ptr::eq. The address comparison shows that the calls returned the same stored instance. The counter catches an implementation that reconstructs the value in the same storage. Read both results before reporting them through the initialized console or the existing in-kernel test runner. In a host run with spin::Once and spin::Mutex, this check gave a count of 1 and equal references.
When you review a console access path, ask whether the value is already initialized when a handler can first reach it, and whether every holder drops the guard before interrupts are restored. The next lesson, “Atomics and read-write locks,” examines how atomic operations support synchronization and when shared read access can replace exclusive access.
Key takeaways
- Mask local interrupts before acquiring a spin lock shared with a hard interrupt handler.
- Release the spin lock before restoring the saved interrupt state.
- A guard releases the lock when dropped, including during panic unwinding.
- A synchronized once cell publishes a completed value and reuses it on subsequent calls.
Reflect
- Explain to a colleague, in two sentences: trace a same-hart deadlock between a task and an interrupt handler.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationLinux kernel locking: locking between contexts
- Kernel documentationLinux kernel lock types: spin locks and PREEMPT_RT
Official documentation first. Links checked when the lesson was published.