Skip to main content

vpp_plugin/vlib/main/
mod.rs

1//! VPP vlib main structure wrapper
2//!
3//! This module contains abstractions around VPP's `vlib_main_t` structure.
4//! It provides safe access to the main VPP library context.
5
6use std::{marker::PhantomData, ops::Deref, panic::Location};
7
8use crate::bindings::{
9    vlib_main_t, vlib_worker_thread_barrier_release, vlib_worker_thread_barrier_sync_int,
10};
11
12pub mod sync;
13
14/// Reference to VPP per-thread main library context
15///
16/// This is a safe wrapper around `vlib_main_t`, providing access to its fields.
17///
18/// A `&mut MainRef` is equivalent to a `vlib_main_t *` in C (a `*mut vlib_main_t` in Rust).
19///
20/// See also [`BarrierHeldMainRef`] for a variant that indicates the caller holds the
21/// main thread barrier.
22#[repr(transparent)]
23pub struct MainRef(foreign_types::Opaque);
24
25impl MainRef {
26    /// Creates a `&mut MainRef` directly from a pointer
27    ///
28    /// # Safety
29    /// - The pointer must be valid and a properly initialised `vlib_main_t` for the thread.
30    /// - The pointer must stay valid and the contents must not be mutated for the duration of the
31    ///   lifetime of the returned object.
32    /// - The `vlib_main_t` must have been created by VPP at startup and not manually by the
33    ///   caller, as many datastructures size the memory they allocate by the number of threads
34    ///   at startup and are subsequently indexed by thread index.
35    pub unsafe fn from_ptr_mut<'a>(ptr: *mut vlib_main_t) -> &'a mut Self {
36        // SAFETY: caller must ensure the safety requirements are met
37        unsafe { &mut *(ptr as *mut _) }
38    }
39
40    /// Returns the raw pointer to the underlying `vlib_main_t`
41    pub fn as_ptr(&self) -> *mut vlib_main_t {
42        self as *const _ as *mut _
43    }
44
45    /// Returns the 0-based thread index of this VPP main context
46    pub fn thread_index(&self) -> u16 {
47        // SAFETY: as long as `self` is a valid `MainRef`, so is the pointer dereference
48        unsafe { (*self.as_ptr()).thread_index }
49    }
50
51    /// Takes the VPP worker thread barrier, stopping all worker threads
52    ///
53    /// Returns an RAII guard which releases the barrier when dropped and which dereferences to a
54    /// [`BarrierHeldMainRef`] for use with APIs that require the barrier to be held.
55    ///
56    /// The barrier is recursive in VPP, so it is fine to call this when the barrier is already
57    /// held. If there are no worker threads then this is cheap.
58    ///
59    /// The returned guard must not be held across an async await.
60    ///
61    /// # Panics
62    ///
63    /// Panics if not called on the VPP main thread.
64    #[track_caller]
65    pub fn barrier_sync(&self) -> BarrierGuard<'_> {
66        assert_eq!(
67            self.thread_index(),
68            0,
69            "Barrier can only be taken on the VPP main thread"
70        );
71        // SAFETY: `self` is a valid main thread `vlib_main_t` and the file name is a
72        // `'static` nul-terminated string, since VPP stores the pointer for debugging/elog.
73        unsafe {
74            vlib_worker_thread_barrier_sync_int(
75                self.as_ptr(),
76                Location::caller().file_as_c_str().as_ptr(),
77            );
78        }
79        BarrierGuard {
80            vm: self,
81            _phantom: PhantomData,
82        }
83    }
84}
85
86/// RAII guard for the VPP worker thread barrier, returned by [`MainRef::barrier_sync`]
87///
88/// The barrier is released when this guard is dropped. Leaking the guard (e.g. via
89/// [`std::mem::forget`]) leaves the barrier held, which stalls workers but isn't unsound.
90#[must_use = "if unused the barrier will immediately be released"]
91pub struct BarrierGuard<'vm> {
92    vm: &'vm MainRef,
93    /// Prevent the type from being `Send` or `Sync`: the barrier must be released on the main
94    /// thread. Since `MainRef` isn't currently `Sync` this is defensive in case that changes in
95    /// the future.
96    _phantom: PhantomData<*mut ()>,
97}
98
99impl Deref for BarrierGuard<'_> {
100    type Target = BarrierHeldMainRef;
101
102    fn deref(&self) -> &Self::Target {
103        // SAFETY: the barrier is held for the lifetime of the guard, `BarrierHeldMainRef` is
104        // `repr(transparent)` over `MainRef`, and we only hand out a shared reference.
105        unsafe { &*(self.vm as *const MainRef as *const BarrierHeldMainRef) }
106    }
107}
108
109impl Drop for BarrierGuard<'_> {
110    fn drop(&mut self) {
111        // SAFETY: the barrier was taken by `barrier_sync` on this (main) thread and the guard
112        // can't have moved to another thread.
113        unsafe { vlib_worker_thread_barrier_release(self.vm.as_ptr()) }
114    }
115}
116
117/// Reference to VPP per-thread main library context with barrier held
118///
119/// This is a safe wrapper around `vlib_main_t`, providing access to its fields.
120///
121/// A `&mut BarrierHeldMainRef` is equivalent to a `vlib_main_t *` in C (a `*mut vlib_main_t` in
122/// Rust).
123///
124/// See also [`MainRef`] for a variant without the constraint that the caller holds the
125/// main thread barrier.
126#[repr(transparent)]
127pub struct BarrierHeldMainRef(MainRef);
128
129impl BarrierHeldMainRef {
130    /// Creates a `&mut BarrierHeldMainRef` directly from a pointer
131    ///
132    /// # Safety
133    /// - All the safety requirements of [`MainRef::from_ptr_mut`] apply.
134    /// - Additionally, the caller must that no other thread is concurrently accessing VPP data
135    ///   structures. This is typically ensured by holding the main thread barrier, but also
136    ///   applies during initialisation before worker threads are started or shutdown after
137    ///   worker threads are stopped.
138    pub unsafe fn from_ptr_mut<'a>(ptr: *mut vlib_main_t) -> &'a mut Self {
139        // SAFETY: caller must ensure the safety requirements are met, plus `BarrierHeldMainRef`
140        // is `repr(transparent)` over `MainRef`.
141        unsafe {
142            // Sanity check: barrier should only ever be held on main thread
143            debug_assert!((*ptr).thread_index == 0);
144            &mut *(ptr as *mut _)
145        }
146    }
147}
148
149impl Deref for BarrierHeldMainRef {
150    type Target = MainRef;
151
152    fn deref(&self) -> &Self::Target {
153        &self.0
154    }
155}