garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/sync.rs

raw

//! Sharing kernel state between cores and with interrupt handlers.

use crate::smp::MAX_CORES;
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};

/// A spin lock that also masks IRQs on the core holding it, so an
/// interrupt handler on that core cannot spin on it forever. Taking it is
/// one swap; a waiter reads until it looks free, backing off, and whichever
/// core finds it free first has it.
///
/// Not a ticket lock, which serves cores in the order they asked: on cores
/// that share their hardware (a hypervisor's, QEMU's) the next in line may
/// be paused, and every other core then waits for it. Sixteen cores
/// emulated on a six-thread host took 44 ms to 25 s for 45 000 increments
/// of one counter with tickets, 39 to 171 ms with this; six cores, 39 to
/// 90 ms either way (2026-11-24). Unfair in principle, which with sections
/// as short as the kernel's has not shown.
pub struct SpinLock<T> {
    locked: AtomicBool,
    value: UnsafeCell<T>,
}

// SAFETY: the lock hands out one guard at a time.
unsafe impl<T: Send> Sync for SpinLock<T> {}

impl<T> SpinLock<T> {
    pub const fn new(value: T) -> Self {
        Self {
            locked: AtomicBool::new(false),
            value: UnsafeCell::new(value),
        }
    }

    pub fn lock(&self) -> Guard<'_, T> {
        let masked = crate::irq::Masked::new();
        let mut backoff = 1u32;
        while self.locked.swap(true, Ordering::Acquire) {
            // Reads only, so the line stays shared until it is let go;
            // YIELD gives a shared core's time to the holder. (WFE and SEV
            // instead lost a wakeup now and then: a boot stalled on six
            // cores.)
            while self.locked.load(Ordering::Relaxed) {
                for _ in 0..backoff {
                    // YIELD on ARM (`spin_loop` would be an ISB), PAUSE on x86.
                    #[cfg(target_arch = "aarch64")]
                    // SAFETY: YIELD is only a hint.
                    unsafe {
                        core::arch::asm!("yield", options(nomem, nostack))
                    };
                    #[cfg(not(target_arch = "aarch64"))]
                    core::hint::spin_loop();
                }
                backoff = (backoff * 2).min(64);
            }
        }
        Guard {
            lock: self,
            _masked: masked,
        }
    }

    /// The lock if it is free now, else None: for what must never wait
    /// (drawing a panic, which may have come from inside the holder).
    pub fn try_lock(&self) -> Option<Guard<'_, T>> {
        let masked = crate::irq::Masked::new();
        (!self.locked.swap(true, Ordering::Acquire)).then(|| Guard {
            lock: self,
            _masked: masked,
        })
    }
}

pub struct Guard<'a, T> {
    lock: &'a SpinLock<T>,
    _masked: crate::irq::Masked,
}

impl<T> Deref for Guard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        // SAFETY: the guard is the one holder.
        unsafe { &*self.lock.value.get() }
    }
}

impl<T> DerefMut for Guard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        // SAFETY: the guard is the one holder.
        unsafe { &mut *self.lock.value.get() }
    }
}

impl<T> Drop for Guard<'_, T> {
    fn drop(&mut self) {
        self.lock.locked.store(false, Ordering::Release);
    }
}

/// A lock a task sleeps for: held across work that waits for a device (a
/// disk's file system), which a [`SpinLock`], masking interrupts, could not
/// be. Uncontended, taking it is a spin lock's cost; a task that finds it
/// held registers itself and sleeps until the holder lets go. The boot task,
/// which cannot sleep, waits for an interrupt and looks again.
pub struct Mutex<T> {
    state: SpinLock<MutexState>,
    value: UnsafeCell<T>,
}

struct MutexState {
    held: bool,
    /// Tasks asleep until it is free, in the order they asked.
    waiters: alloc::vec::Vec<usize>,
}

// SAFETY: the lock hands out one guard at a time.
unsafe impl<T: Send> Sync for Mutex<T> {}

impl<T> Mutex<T> {
    pub const fn new(value: T) -> Self {
        Self {
            state: SpinLock::new(MutexState {
                held: false,
                waiters: alloc::vec::Vec::new(),
            }),
            value: UnsafeCell::new(value),
        }
    }

    pub fn lock(&self) -> MutexGuard<'_, T> {
        let me = crate::sched::current();
        loop {
            {
                let mut state = self.state.lock();
                if !state.held {
                    state.held = true;
                    return MutexGuard { lock: self };
                }
                if me >= MAX_CORES && !state.waiters.contains(&me) {
                    state.waiters.push(me);
                }
            }
            // A wake that came between registering and here makes the sleep
            // return at once, so none is lost.
            if me < MAX_CORES {
                crate::arch::wait_for_interrupt();
            } else {
                crate::sched::sleep();
            }
        }
    }
}

pub struct MutexGuard<'a, T> {
    lock: &'a Mutex<T>,
}

impl<T> Deref for MutexGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        // SAFETY: the guard is the one holder.
        unsafe { &*self.lock.value.get() }
    }
}

impl<T> DerefMut for MutexGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        // SAFETY: the guard is the one holder.
        unsafe { &mut *self.lock.value.get() }
    }
}

impl<T> Drop for MutexGuard<'_, T> {
    fn drop(&mut self) {
        let next = {
            let mut state = self.lock.state.lock();
            state.held = false;
            (!state.waiters.is_empty()).then(|| state.waiters.remove(0))
        };
        if let Some(task) = next {
            crate::sched::wake(task);
        }
    }
}

/// State whose exclusion is somebody else's: touched only under another
/// lock, which its uses name, or only before the other cores start.
#[repr(transparent)]
pub struct Global<T>(UnsafeCell<T>);

// SAFETY: see `get`.
unsafe impl<T> Sync for Global<T> {}

impl<T> Global<T> {
    pub const fn new(value: T) -> Self {
        Self(UnsafeCell::new(value))
    }

    /// # Safety
    /// The exclusion the value's documentation names is held, and no other
    /// reference to it is alive.
    #[allow(clippy::mut_from_ref)]
    pub unsafe fn get(&self) -> &mut T {
        unsafe { &mut *self.0.get() }
    }
}

/// One value per core, each touched only by its own core with IRQs masked:
/// no lock, and each on a cache line of its own so cores never contend.
pub struct PerCore<T>([CacheLine<T>; MAX_CORES]);

#[repr(align(64))]
struct CacheLine<T>(UnsafeCell<T>);

// SAFETY: each core touches only its own value.
unsafe impl<T> Sync for PerCore<T> {}

impl<T: Copy> PerCore<T> {
    pub const fn new(value: T) -> Self {
        let mut lines = [const { MaybeUninit::<CacheLine<T>>::uninit() }; MAX_CORES];
        let mut i = 0;
        while i < MAX_CORES {
            lines[i] = MaybeUninit::new(CacheLine(UnsafeCell::new(value)));
            i += 1;
        }
        // SAFETY: every element was just written.
        Self(unsafe { core::ptr::read((&raw const lines).cast::<[CacheLine<T>; MAX_CORES]>()) })
    }
}

impl<T> PerCore<T> {
    /// This core's value.
    ///
    /// # Safety
    /// IRQs masked (the core cannot be left mid-use), and no other reference
    /// to this core's value alive.
    #[allow(clippy::mut_from_ref)]
    pub unsafe fn get(&self) -> &mut T {
        unsafe { &mut *self.0[crate::arch::core_id()].0.get() }
    }
}