|
| 1 | +pub use aya_common::SpinLock; |
| 2 | + |
| 3 | +use crate::helpers; |
| 4 | + |
| 5 | +/// An RAII implementation of a scope of a spin lock. When this structure is |
| 6 | +/// dropped (falls out of scope), the lock will be unlocked. |
| 7 | +#[must_use = "if unused the spin lock will immediately unlock"] |
| 8 | +pub struct SpinLockGuard<'a> { |
| 9 | + spin_lock: &'a mut SpinLock, |
| 10 | +} |
| 11 | + |
| 12 | +impl Drop for SpinLockGuard<'_> { |
| 13 | + fn drop(&mut self) { |
| 14 | + // SAFETY: Call to an eBPF helper. `self.spin_lock` is always |
| 15 | + // initialized. |
| 16 | + unsafe { |
| 17 | + helpers::bpf_spin_unlock(core::ptr::from_mut(self.spin_lock)); |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +mod sealed { |
| 23 | + use super::{SpinLock, SpinLockGuard, helpers}; |
| 24 | + |
| 25 | + pub trait EbpfSpinLock { |
| 26 | + fn lock(&mut self) -> SpinLockGuard<'_>; |
| 27 | + } |
| 28 | + |
| 29 | + impl EbpfSpinLock for SpinLock { |
| 30 | + fn lock(&mut self) -> SpinLockGuard<'_> { |
| 31 | + // SAFETY: Call to an eBPF helper. `self` is always initialized. |
| 32 | + unsafe { |
| 33 | + helpers::bpf_spin_lock(core::ptr::from_mut(self)); |
| 34 | + } |
| 35 | + SpinLockGuard { spin_lock: self } |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/// Extension trait for [`SpinLock`] exposing eBPF-only helpers. These helpers |
| 41 | +/// are not available in user-space. |
| 42 | +pub trait EbpfSpinLockExt: sealed::EbpfSpinLock { |
| 43 | + fn lock(&mut self) -> SpinLockGuard<'_>; |
| 44 | +} |
| 45 | + |
| 46 | +impl<T> EbpfSpinLockExt for T |
| 47 | +where |
| 48 | + T: sealed::EbpfSpinLock, |
| 49 | +{ |
| 50 | + /// Acquires a spin lock and returns a [`SpinLockGuard`]. The lock is |
| 51 | + /// acquired as long as the guard is alive. |
| 52 | + #[inline] |
| 53 | + fn lock(&mut self) -> SpinLockGuard<'_> { |
| 54 | + sealed::EbpfSpinLock::lock(self) |
| 55 | + } |
| 56 | +} |
0 commit comments