2024-06-22 19:28:26 +00:00
|
|
|
//! jemalloc allocator
|
|
|
|
|
|
2025-01-16 08:58:40 +00:00
|
|
|
use std::{
|
2026-11-21 00:20:27 +00:00
|
|
|
any::Any,
|
2026-11-21 00:29:10 +00:00
|
|
|
ffi::{CStr, CString, c_char, c_uint, c_void},
|
2025-01-18 01:32:37 +00:00
|
|
|
fmt::Debug,
|
2026-11-21 00:20:27 +00:00
|
|
|
panic::{self, AssertUnwindSafe},
|
2026-11-21 00:20:05 +00:00
|
|
|
ptr,
|
|
|
|
|
sync::OnceLock,
|
2025-01-16 08:58:40 +00:00
|
|
|
};
|
2024-04-27 04:50:20 -07:00
|
|
|
|
2025-01-16 08:58:40 +00:00
|
|
|
use arrayvec::ArrayVec;
|
|
|
|
|
use tikv_jemalloc_ctl as mallctl;
|
2024-04-27 04:50:20 -07:00
|
|
|
use tikv_jemalloc_sys as ffi;
|
|
|
|
|
use tikv_jemallocator as jemalloc;
|
|
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
use crate::{
|
2025-07-19 22:20:26 +01:00
|
|
|
Result, SyncRwLock, err, is_equal_to, is_nonzero,
|
2025-01-18 01:30:41 +00:00
|
|
|
utils::{math, math::Tried},
|
|
|
|
|
};
|
2025-01-16 08:58:40 +00:00
|
|
|
|
|
|
|
|
#[cfg(feature = "jemalloc_conf")]
|
2026-11-21 00:19:42 +00:00
|
|
|
#[repr(transparent)]
|
|
|
|
|
struct MallocConf(*const c_char);
|
|
|
|
|
|
|
|
|
|
// SAFETY: MallocConf points to static immutable NUL-terminated bytes.
|
|
|
|
|
#[cfg(feature = "jemalloc_conf")]
|
|
|
|
|
unsafe impl Sync for MallocConf {}
|
|
|
|
|
|
|
|
|
|
#[cfg(feature = "jemalloc_conf")]
|
|
|
|
|
const MALLOC_CONF_BYTES: &[u8] = const_str::concat_bytes!(
|
2025-01-29 06:36:14 +00:00
|
|
|
"lg_extent_max_active_fit:4",
|
|
|
|
|
",oversize_threshold:16777216",
|
|
|
|
|
",tcache_max:2097152",
|
|
|
|
|
",dirty_decay_ms:16000",
|
|
|
|
|
",muzzy_decay_ms:144000",
|
2026-11-21 00:19:42 +00:00
|
|
|
MALLOC_CONF_PLATFORM,
|
2025-01-29 06:36:14 +00:00
|
|
|
MALLOC_CONF_PROF,
|
|
|
|
|
0
|
|
|
|
|
);
|
|
|
|
|
|
2026-11-21 00:19:42 +00:00
|
|
|
#[cfg(all(feature = "jemalloc_conf", target_os = "linux"))]
|
|
|
|
|
const MALLOC_CONF_PLATFORM: &str = ",percpu_arena:percpu,metadata_thp:always,background_thread:true";
|
|
|
|
|
#[cfg(all(feature = "jemalloc_conf", not(target_os = "linux")))]
|
|
|
|
|
const MALLOC_CONF_PLATFORM: &str = "";
|
|
|
|
|
|
|
|
|
|
// Targets match `NO_UNPREFIXED_MALLOC_TARGETS` in `tikv-jemalloc-sys` when
|
|
|
|
|
// `unprefixed_malloc_on_supported_platforms` is enabled.
|
|
|
|
|
#[cfg(feature = "jemalloc_conf")]
|
|
|
|
|
#[used]
|
|
|
|
|
#[allow(non_upper_case_globals)]
|
|
|
|
|
#[cfg_attr(
|
|
|
|
|
any(
|
|
|
|
|
target_vendor = "apple",
|
|
|
|
|
target_env = "musl",
|
|
|
|
|
target_os = "android",
|
|
|
|
|
target_os = "dragonfly",
|
|
|
|
|
),
|
|
|
|
|
unsafe(export_name = "_rjem_malloc_conf")
|
|
|
|
|
)]
|
|
|
|
|
#[cfg_attr(
|
|
|
|
|
not(any(
|
|
|
|
|
target_vendor = "apple",
|
|
|
|
|
target_env = "musl",
|
|
|
|
|
target_os = "android",
|
|
|
|
|
target_os = "dragonfly",
|
|
|
|
|
)),
|
|
|
|
|
unsafe(no_mangle)
|
|
|
|
|
)]
|
|
|
|
|
static malloc_conf: MallocConf = MallocConf(MALLOC_CONF_BYTES.as_ptr().cast());
|
|
|
|
|
|
2025-01-29 06:36:14 +00:00
|
|
|
#[cfg(all(feature = "jemalloc_conf", feature = "jemalloc_prof"))]
|
|
|
|
|
const MALLOC_CONF_PROF: &str = ",prof_active:false";
|
|
|
|
|
#[cfg(all(feature = "jemalloc_conf", not(feature = "jemalloc_prof")))]
|
|
|
|
|
const MALLOC_CONF_PROF: &str = "";
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2024-04-27 04:50:20 -07:00
|
|
|
#[global_allocator]
|
|
|
|
|
static JEMALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc;
|
2025-07-19 22:20:26 +01:00
|
|
|
static CONTROL: SyncRwLock<()> = SyncRwLock::new(());
|
2024-04-27 04:50:20 -07:00
|
|
|
|
2025-01-16 08:58:40 +00:00
|
|
|
type Name = ArrayVec<u8, NAME_MAX>;
|
2025-01-18 01:30:41 +00:00
|
|
|
type Key = ArrayVec<usize, KEY_SEGS>;
|
2025-01-16 08:58:40 +00:00
|
|
|
|
|
|
|
|
const NAME_MAX: usize = 128;
|
2025-01-18 01:30:41 +00:00
|
|
|
const KEY_SEGS: usize = 8;
|
2026-11-21 00:28:09 +00:00
|
|
|
const ARENA_LIMIT: usize = 4095;
|
|
|
|
|
const ARENAS_ALL: usize = 4096;
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-05-03 08:55:50 -04:00
|
|
|
#[ctor::ctor(unsafe)]
|
2025-01-18 01:30:41 +00:00
|
|
|
fn _static_initialization() {
|
2026-11-21 00:20:05 +00:00
|
|
|
let mut epoch: u64 = 0;
|
|
|
|
|
let mut len = size_of::<u64>();
|
|
|
|
|
// SAFETY: Pre-initialize jemalloc before main() without touching Rust TLS
|
|
|
|
|
// or unwinding across the constructor boundary.
|
|
|
|
|
unsafe {
|
|
|
|
|
ffi::mallctl(
|
|
|
|
|
c"epoch".as_ptr(),
|
|
|
|
|
ptr::from_mut(&mut epoch).cast::<c_void>(),
|
|
|
|
|
&raw mut len,
|
|
|
|
|
ptr::null_mut(),
|
|
|
|
|
0,
|
|
|
|
|
);
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2024-05-09 15:59:08 -07:00
|
|
|
#[must_use]
|
2024-08-18 17:36:33 -04:00
|
|
|
#[cfg(feature = "jemalloc_stats")]
|
2024-07-09 21:55:56 +00:00
|
|
|
pub fn memory_usage() -> Option<String> {
|
2026-09-24 15:30:29 +02:00
|
|
|
let mibs = |input: usize| {
|
2026-11-21 00:20:27 +00:00
|
|
|
let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX);
|
|
|
|
|
let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default();
|
|
|
|
|
f64::from(whole) + f64::from(rem_kibs) / 1024.0
|
2024-07-07 06:17:58 +00:00
|
|
|
};
|
|
|
|
|
|
2026-09-24 15:30:29 +02:00
|
|
|
let [allocated, active, mapped, metadata, resident, retained] =
|
|
|
|
|
memory_usage_stats()?.map(|(_, bytes)| mibs(bytes));
|
2024-07-09 21:55:56 +00:00
|
|
|
Some(format!(
|
2024-12-15 00:05:47 -05:00
|
|
|
"allocated: {allocated:.2} MiB\nactive: {active:.2} MiB\nmapped: {mapped:.2} \
|
|
|
|
|
MiB\nmetadata: {metadata:.2} MiB\nresident: {resident:.2} MiB\nretained: {retained:.2} \
|
|
|
|
|
MiB\n"
|
2024-07-09 21:55:56 +00:00
|
|
|
))
|
2024-04-27 04:50:20 -07:00
|
|
|
}
|
|
|
|
|
|
2024-08-18 17:36:33 -04:00
|
|
|
#[must_use]
|
|
|
|
|
#[cfg(not(feature = "jemalloc_stats"))]
|
|
|
|
|
pub fn memory_usage() -> Option<String> { None }
|
|
|
|
|
|
2026-09-24 15:30:29 +02:00
|
|
|
#[must_use]
|
|
|
|
|
#[cfg(feature = "jemalloc_stats")]
|
|
|
|
|
pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> {
|
|
|
|
|
use mallctl::stats;
|
|
|
|
|
|
|
|
|
|
// Acquire the epoch; ensure latest stats are pulled in
|
|
|
|
|
acq_epoch().ok()?;
|
|
|
|
|
|
|
|
|
|
Some([
|
|
|
|
|
("allocated", stats::allocated::read().unwrap_or_default()),
|
|
|
|
|
("active", stats::active::read().unwrap_or_default()),
|
|
|
|
|
("mapped", stats::mapped::read().unwrap_or_default()),
|
|
|
|
|
("metadata", stats::metadata::read().unwrap_or_default()),
|
|
|
|
|
("resident", stats::resident::read().unwrap_or_default()),
|
|
|
|
|
("retained", stats::retained::read().unwrap_or_default()),
|
|
|
|
|
])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[must_use]
|
|
|
|
|
#[cfg(not(feature = "jemalloc_stats"))]
|
|
|
|
|
pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None }
|
|
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
struct StatsPrintState {
|
|
|
|
|
buf: String,
|
|
|
|
|
max_len: usize,
|
|
|
|
|
panic: Option<Box<dyn Any + Send>>,
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-18 01:32:37 +00:00
|
|
|
pub fn memory_stats(opts: &str) -> Option<String> {
|
|
|
|
|
const MAX_LENGTH: usize = 1_048_576;
|
2024-04-27 04:50:20 -07:00
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
let opts = CString::new(opts).ok()?;
|
2024-04-27 22:03:30 -07:00
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
// Acquire the epoch; ensure latest stats are pulled in
|
|
|
|
|
acq_epoch().ok()?;
|
|
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
let mut state = StatsPrintState {
|
|
|
|
|
buf: String::new(),
|
|
|
|
|
max_len: MAX_LENGTH,
|
|
|
|
|
panic: None,
|
|
|
|
|
};
|
|
|
|
|
let opaque = ptr::from_mut(&mut state).cast::<c_void>();
|
2024-04-27 04:50:20 -07:00
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
// SAFETY: `state` and `opts` remain live in this frame for the duration of
|
|
|
|
|
// `malloc_stats_print()`, which invokes `malloc_stats_cb` synchronously.
|
|
|
|
|
unsafe { ffi::malloc_stats_print(Some(malloc_stats_cb), opaque, opts.as_ptr()) };
|
2025-01-18 01:32:37 +00:00
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
if let Some(payload) = state.panic {
|
|
|
|
|
panic::resume_unwind(payload);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Some(state.buf)
|
2024-04-27 04:50:20 -07:00
|
|
|
}
|
|
|
|
|
|
2024-12-12 10:22:30 -05:00
|
|
|
unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) {
|
2026-11-21 00:20:27 +00:00
|
|
|
// SAFETY: `opaque` points to `StatsPrintState` on the caller's stack.
|
|
|
|
|
let Some(state) = (unsafe { opaque.cast::<StatsPrintState>().as_mut() }) else {
|
|
|
|
|
return;
|
2025-01-16 08:58:40 +00:00
|
|
|
};
|
2024-04-27 22:03:30 -07:00
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
if state.panic.is_some() || msg.is_null() || state.buf.len() >= state.max_len {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SAFETY: jemalloc guarantees `msg` is a valid NUL-terminated C string.
|
2025-01-18 01:30:41 +00:00
|
|
|
let msg = unsafe { CStr::from_ptr(msg) };
|
2024-04-27 22:03:30 -07:00
|
|
|
|
2026-11-21 00:20:27 +00:00
|
|
|
if let Err(err) = panic::catch_unwind(AssertUnwindSafe(|| {
|
|
|
|
|
let msg = String::from_utf8_lossy(msg.to_bytes());
|
|
|
|
|
let remaining = state.max_len.saturating_sub(state.buf.len());
|
|
|
|
|
if msg.len() <= remaining {
|
|
|
|
|
state.buf.push_str(msg.as_ref());
|
|
|
|
|
} else {
|
|
|
|
|
if let Some(prefix) = msg.get(..msg.floor_char_boundary(remaining)) {
|
|
|
|
|
state.buf.push_str(prefix);
|
|
|
|
|
}
|
|
|
|
|
state.max_len = state.buf.len();
|
|
|
|
|
}
|
|
|
|
|
})) {
|
|
|
|
|
state.panic = Some(err);
|
|
|
|
|
}
|
2024-04-27 04:50:20 -07:00
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
|
|
|
|
macro_rules! mallctl {
|
2026-11-21 00:20:46 +00:00
|
|
|
($name:literal) => {{
|
2026-11-21 00:20:05 +00:00
|
|
|
static KEY: OnceLock<Key> = OnceLock::new();
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2026-11-21 00:20:05 +00:00
|
|
|
KEY.get_or_init(|| key($name).expect("failed to translate name into mib key"))
|
|
|
|
|
.clone()
|
2025-01-16 08:58:40 +00:00
|
|
|
}};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub mod this_thread {
|
2026-11-21 00:29:10 +00:00
|
|
|
use super::{Debug, Key, OnceLock, Result, c_uint, is_nonzero, key, math};
|
2025-01-22 21:38:15 +00:00
|
|
|
|
2025-01-24 11:29:36 +00:00
|
|
|
pub fn trim() -> Result { decay().and_then(|()| purge()) }
|
2025-01-22 21:38:15 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn purge() -> Result {
|
|
|
|
|
// SAFETY: `arena.<i>.purge` is an `arena.<i>.*` notification ctl.
|
|
|
|
|
unsafe { notify(mallctl!("arena.0.purge")) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn decay() -> Result {
|
|
|
|
|
// SAFETY: `arena.<i>.decay` is an `arena.<i>.*` notification ctl.
|
|
|
|
|
unsafe { notify(mallctl!("arena.0.decay")) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn idle() -> Result {
|
|
|
|
|
// SAFETY: `thread.idle` is a non-indexed notification ctl.
|
|
|
|
|
unsafe { super::notify(&mallctl!("thread.idle")) }
|
|
|
|
|
}
|
2025-01-24 11:29:36 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn flush() -> Result {
|
|
|
|
|
// SAFETY: `thread.tcache.flush` is a non-indexed notification ctl.
|
|
|
|
|
unsafe { super::notify(&mallctl!("thread.tcache.flush")) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
|
|
|
|
pub fn set_muzzy_decay(decay_ms: isize) -> Result<isize> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.muzzy_decay_ms` has C type `ssize_t`.
|
|
|
|
|
unsafe { set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms) }
|
2025-01-16 08:58:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn get_muzzy_decay() -> Result<isize> {
|
|
|
|
|
// SAFETY: `arena.<i>.muzzy_decay_ms` has C type `ssize_t`.
|
|
|
|
|
unsafe { get(mallctl!("arena.0.muzzy_decay_ms")) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
|
|
|
|
pub fn set_dirty_decay(decay_ms: isize) -> Result<isize> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.dirty_decay_ms` has C type `ssize_t`.
|
|
|
|
|
unsafe { set(mallctl!("arena.0.dirty_decay_ms"), decay_ms) }
|
2025-01-16 08:58:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn get_dirty_decay() -> Result<isize> {
|
|
|
|
|
// SAFETY: `arena.<i>.dirty_decay_ms` has C type `ssize_t`.
|
|
|
|
|
unsafe { get(mallctl!("arena.0.dirty_decay_ms")) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2025-01-22 21:38:15 +00:00
|
|
|
pub fn cache_enable(enable: bool) -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { super::set::<u8>(&mallctl!("thread.tcache.enabled"), enable.into()) }
|
|
|
|
|
.map(is_nonzero!())
|
2025-01-16 08:58:40 +00:00
|
|
|
}
|
|
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
pub fn is_cache_enabled() -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { super::get::<u8>(&mallctl!("thread.tcache.enabled")) }.map(is_nonzero!())
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
pub fn set_arena(id: usize) -> Result<usize> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.arena` has C type `unsigned`.
|
|
|
|
|
unsafe { super::set::<c_uint>(&mallctl!("thread.arena"), id.try_into()?) }
|
|
|
|
|
.and_then(math::try_into)
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
pub fn arena_id() -> Result<usize> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.arena` has C type `unsigned`.
|
|
|
|
|
unsafe { super::get::<c_uint>(&mallctl!("thread.arena")) }.and_then(math::try_into)
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
2025-01-22 21:38:15 +00:00
|
|
|
pub fn prof_enable(enable: bool) -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { super::set::<u8>(&mallctl!("thread.prof.active"), enable.into()) }
|
|
|
|
|
.map(is_nonzero!())
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2025-01-22 21:38:15 +00:00
|
|
|
pub fn is_prof_enabled() -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { super::get::<u8>(&mallctl!("thread.prof.active")) }.map(is_nonzero!())
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn reset_peak() -> Result {
|
|
|
|
|
// SAFETY: `thread.peak.reset` is a non-indexed notification ctl.
|
|
|
|
|
unsafe { super::notify(&mallctl!("thread.peak.reset")) }
|
|
|
|
|
}
|
2025-01-22 21:38:15 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn peak() -> Result<u64> {
|
|
|
|
|
// SAFETY: `thread.peak.read` has C type `uint64_t`.
|
|
|
|
|
unsafe { super::get(&mallctl!("thread.peak.read")) }
|
|
|
|
|
}
|
2025-01-22 21:38:15 +00:00
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub fn allocated() -> u64 {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.allocated` has C type `uint64_t`.
|
|
|
|
|
unsafe { super::get(&mallctl!("thread.allocated")) }.unwrap_or_default()
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub fn deallocated() -> u64 {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `thread.deallocated` has C type `uint64_t`.
|
|
|
|
|
unsafe { super::get(&mallctl!("thread.deallocated")) }.unwrap_or_default()
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is an `arena.<i>.*` notification MIB
|
|
|
|
|
/// (`key.len() >= 2`).
|
|
|
|
|
// `arena_id()` returns this thread's own valid arena (< narenas < ARENA_LIMIT),
|
|
|
|
|
// so we skip `validate_arena_id()` to avoid locking `ctl_mtx` on hot paths like
|
|
|
|
|
// `decay()`.
|
|
|
|
|
unsafe fn notify(mut key: Key) -> Result {
|
2026-11-21 00:28:09 +00:00
|
|
|
key[1] = arena_id()?;
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `key` is an `arena.<i>.*` notification MIB
|
|
|
|
|
// and `arena_id()` returns a valid arena index.
|
|
|
|
|
unsafe { super::notify(&key) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is an `arena.<i>.*` MIB and `T` matches its
|
|
|
|
|
/// exact C type.
|
|
|
|
|
unsafe fn set<T>(mut key: Key, val: T) -> Result<T>
|
2025-01-18 01:30:41 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
2026-11-21 00:28:09 +00:00
|
|
|
// `arena_id()` is already a valid arena index; skip `validate_arena_id()`.
|
|
|
|
|
key[1] = arena_id()?;
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches `key`.
|
|
|
|
|
unsafe { super::set(&key, val) }
|
2026-11-21 00:28:09 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is an `arena.<i>.*` MIB and `T` matches its
|
|
|
|
|
/// exact C type.
|
|
|
|
|
unsafe fn get<T>(mut key: Key) -> Result<T>
|
2026-11-21 00:28:09 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
|
|
|
|
// `arena_id()` is already a valid arena index; skip `validate_arena_id()`.
|
|
|
|
|
key[1] = arena_id()?;
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches `key`.
|
|
|
|
|
unsafe { super::get(&key) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn stats_reset() -> Result {
|
|
|
|
|
// SAFETY: `stats.mutexes.reset` is a non-indexed notification ctl.
|
|
|
|
|
unsafe { notify(&mallctl!("stats.mutexes.reset")) }
|
|
|
|
|
}
|
2025-01-22 21:38:15 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn prof_reset() -> Result {
|
|
|
|
|
// SAFETY: `prof.reset` is a non-indexed notification ctl.
|
|
|
|
|
unsafe { notify(&mallctl!("prof.reset")) }
|
|
|
|
|
}
|
2025-01-22 21:38:15 +00:00
|
|
|
|
|
|
|
|
pub fn prof_enable(enable: bool) -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { set::<u8>(&mallctl!("prof.active"), enable.into()) }.map(is_nonzero!())
|
2025-01-22 21:38:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn is_prof_enabled() -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { get::<u8>(&mallctl!("prof.active")) }.map(is_nonzero!())
|
2025-01-16 08:58:40 +00:00
|
|
|
}
|
|
|
|
|
|
2025-01-24 11:29:36 +00:00
|
|
|
pub fn trim<I: Into<Option<usize>> + Copy>(arena: I) -> Result {
|
|
|
|
|
decay(arena).and_then(|()| purge(arena))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn purge<I: Into<Option<usize>>>(arena: I) -> Result {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.purge` is an `arena.<i>.*` notification ctl.
|
|
|
|
|
unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.purge")) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn decay<I: Into<Option<usize>>>(arena: I) -> Result {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.decay` is an `arena.<i>.*` notification ctl.
|
|
|
|
|
unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.decay")) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn set_muzzy_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> {
|
2025-02-23 01:17:45 -05:00
|
|
|
match arena.into() {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.muzzy_decay_ms` has C type `ssize_t`.
|
|
|
|
|
| Some(arena) => unsafe {
|
|
|
|
|
set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms)
|
|
|
|
|
},
|
|
|
|
|
// SAFETY: `arenas.muzzy_decay_ms` has C type `ssize_t`.
|
|
|
|
|
| _ => unsafe { set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms) },
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn set_dirty_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> {
|
2025-02-23 01:17:45 -05:00
|
|
|
match arena.into() {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arena.<i>.dirty_decay_ms` has C type `ssize_t`.
|
|
|
|
|
| Some(arena) => unsafe {
|
|
|
|
|
set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms)
|
|
|
|
|
},
|
|
|
|
|
// SAFETY: `arenas.dirty_decay_ms` has C type `ssize_t`.
|
|
|
|
|
| _ => unsafe { set(&mallctl!("arenas.dirty_decay_ms"), decay_ms) },
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-22 06:29:30 +00:00
|
|
|
pub fn background_thread_enable(enable: bool) -> Result<bool> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `background_thread` has C type `bool` (1 byte on non-MSVC).
|
|
|
|
|
unsafe { set::<u8>(&mallctl!("background_thread"), enable.into()) }.map(is_nonzero!())
|
2025-04-22 06:29:30 +00:00
|
|
|
}
|
|
|
|
|
|
2025-01-18 01:30:41 +00:00
|
|
|
#[inline]
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub fn is_affine_arena() -> bool { is_percpu_arena() || is_phycpu_arena() }
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub fn is_percpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("percpu")) }
|
|
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
|
#[must_use]
|
|
|
|
|
pub fn is_phycpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("phycpu")) }
|
|
|
|
|
|
|
|
|
|
pub fn percpu_arenas() -> Result<&'static str> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `opt.percpu_arena` has C type `const char *`.
|
|
|
|
|
let ptr = unsafe { get::<*const c_char>(&mallctl!("opt.percpu_arena")) }?;
|
|
|
|
|
if ptr.is_null() {
|
|
|
|
|
return Err(err!("mallctl: opt.percpu_arena returned NULL"));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SAFETY: `ptr` is non-null and points to a static NUL-terminated string
|
|
|
|
|
// returned by jemalloc for `opt.percpu_arena`.
|
2025-01-18 01:30:41 +00:00
|
|
|
let cstr = unsafe { CStr::from_ptr(ptr) };
|
|
|
|
|
cstr.to_str().map_err(Into::into)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn arenas() -> Result<usize> {
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: `arenas.narenas` has C type `unsigned`.
|
|
|
|
|
unsafe { get::<c_uint>(&mallctl!("arenas.narenas")) }.and_then(math::try_into)
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn inc_epoch() -> Result<u64> {
|
|
|
|
|
// SAFETY: `epoch` has C type `uint64_t`.
|
|
|
|
|
unsafe { xchg(&mallctl!("epoch"), 1_u64) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
pub fn acq_epoch() -> Result<u64> {
|
|
|
|
|
// SAFETY: `epoch` has C type `uint64_t`.
|
|
|
|
|
unsafe { xchg(&mallctl!("epoch"), 0_u64) }
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:28:09 +00:00
|
|
|
fn validate_arena_id(id: usize, allow_all: bool) -> Result<usize> {
|
|
|
|
|
if allow_all && id == ARENAS_ALL {
|
|
|
|
|
return Ok(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let narenas = arenas()?.min(ARENA_LIMIT);
|
|
|
|
|
if id < narenas {
|
|
|
|
|
Ok(id)
|
|
|
|
|
} else {
|
|
|
|
|
Err(err!("mallctl: invalid arena index {id} (narenas: {narenas})"))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is an `arena.<i>.*` notification MIB
|
|
|
|
|
/// (`key.len() >= 2`).
|
|
|
|
|
unsafe fn notify_by_arena(id: Option<usize>, mut key: Key) -> Result {
|
2026-11-21 00:28:09 +00:00
|
|
|
key[1] = match id {
|
|
|
|
|
| Some(id) => validate_arena_id(id, true)?,
|
|
|
|
|
| None => ARENAS_ALL,
|
|
|
|
|
};
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `key` is an `arena.<i>.*` notification MIB and
|
|
|
|
|
// `key[1]` has been validated above.
|
|
|
|
|
unsafe { notify(&key) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is an `arena.<i>.*` MIB (`key.len() >= 2`) and `T`
|
|
|
|
|
/// matches its exact C type.
|
|
|
|
|
unsafe fn set_by_arena<T>(id: usize, mut key: Key, val: T) -> Result<T>
|
2025-01-16 08:58:40 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
2026-11-21 00:28:09 +00:00
|
|
|
key[1] = validate_arena_id(id, false)?;
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches `key`.
|
|
|
|
|
unsafe { set(&key, val) }
|
2025-01-18 01:30:41 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `key` is a valid notification MIB and any indexed arena
|
|
|
|
|
/// component is within bounds.
|
|
|
|
|
unsafe fn notify(key: &Key) -> Result {
|
2026-11-21 00:21:06 +00:00
|
|
|
// SAFETY: jemalloc notification ctls require `oldp`, `oldlenp`, and `newp`
|
|
|
|
|
// to be NULL and `newlen` to be 0 (otherwise `EPERM` is returned).
|
|
|
|
|
let ret = unsafe {
|
|
|
|
|
ffi::mallctlbymib(
|
|
|
|
|
key.as_ptr(),
|
|
|
|
|
key.len(),
|
|
|
|
|
ptr::null_mut(),
|
|
|
|
|
ptr::null_mut(),
|
|
|
|
|
ptr::null_mut(),
|
|
|
|
|
0,
|
|
|
|
|
)
|
|
|
|
|
};
|
|
|
|
|
if ret == 0 {
|
|
|
|
|
Ok(())
|
|
|
|
|
} else {
|
|
|
|
|
Err(err!("mallctl: {}", std::io::Error::from_raw_os_error(ret)))
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-01-18 01:30:41 +00:00
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `T` matches the exact C type expected by `key`.
|
|
|
|
|
unsafe fn set<T>(key: &Key, val: T) -> Result<T>
|
2025-01-18 01:30:41 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
2025-07-19 22:20:26 +01:00
|
|
|
let _lock = CONTROL.write();
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches `key`.
|
|
|
|
|
let res = unsafe { xchg(key, val) }?;
|
2025-01-18 01:30:41 +00:00
|
|
|
inc_epoch()?;
|
|
|
|
|
|
|
|
|
|
Ok(res)
|
2025-01-16 08:58:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `T` matches the exact C type expected by `key`.
|
2025-03-30 01:56:00 +00:00
|
|
|
#[tracing::instrument(
|
|
|
|
|
name = "get",
|
2026-01-04 03:04:37 +00:00
|
|
|
level = "trace",
|
2025-03-30 01:56:00 +00:00
|
|
|
skip_all,
|
|
|
|
|
fields(?key)
|
|
|
|
|
)]
|
2026-11-21 00:29:10 +00:00
|
|
|
unsafe fn get<T>(key: &Key) -> Result<T>
|
2025-01-16 08:58:40 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
2025-01-18 01:30:41 +00:00
|
|
|
acq_epoch()?;
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches the C type returned for `key`.
|
2025-01-16 08:58:40 +00:00
|
|
|
unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:29:10 +00:00
|
|
|
/// # Safety
|
|
|
|
|
/// Caller must ensure `T` matches the exact C type expected by `key`.
|
2025-03-30 01:56:00 +00:00
|
|
|
#[tracing::instrument(
|
|
|
|
|
name = "xchg",
|
2026-01-04 03:04:37 +00:00
|
|
|
level = "trace",
|
2025-03-30 01:56:00 +00:00
|
|
|
skip_all,
|
|
|
|
|
fields(?key, ?val)
|
|
|
|
|
)]
|
2026-11-21 00:29:10 +00:00
|
|
|
unsafe fn xchg<T>(key: &Key, val: T) -> Result<T>
|
2025-01-18 01:30:41 +00:00
|
|
|
where
|
|
|
|
|
T: Copy + Debug,
|
|
|
|
|
{
|
2026-11-21 00:29:10 +00:00
|
|
|
// SAFETY: Caller guarantees `T` matches the C type expected by `key`.
|
2025-01-18 01:30:41 +00:00
|
|
|
unsafe { mallctl::raw::update_mib(key.as_slice(), val) }.map_err(map_err)
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-16 08:58:40 +00:00
|
|
|
fn key(name: &str) -> Result<Key> {
|
|
|
|
|
// tikv asserts the output buffer length is tight to the number of required
|
|
|
|
|
// mibs so we slice that down here.
|
|
|
|
|
let segs = name.chars().filter(is_equal_to!(&'.')).count().try_add(1)?;
|
2026-11-21 00:20:05 +00:00
|
|
|
if segs > KEY_SEGS {
|
|
|
|
|
return Err(err!("mallctl: key has too many segments ({segs} > {KEY_SEGS})"));
|
|
|
|
|
}
|
2025-01-16 08:58:40 +00:00
|
|
|
|
|
|
|
|
let name = self::name(name)?;
|
|
|
|
|
let mut buf = [0_usize; KEY_SEGS];
|
|
|
|
|
mallctl::raw::name_to_mib(name.as_slice(), &mut buf[0..segs])
|
|
|
|
|
.map_err(map_err)
|
|
|
|
|
.map(move |()| buf.into_iter().take(segs).collect())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn name(name: &str) -> Result<Name> {
|
2026-11-21 00:20:05 +00:00
|
|
|
if name.as_bytes().contains(&0) {
|
|
|
|
|
return Err(err!("mallctl: key contains interior NUL byte"));
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-16 08:58:40 +00:00
|
|
|
let mut buf = Name::new();
|
|
|
|
|
buf.try_extend_from_slice(name.as_bytes())?;
|
|
|
|
|
buf.try_extend_from_slice(b"\0")?;
|
|
|
|
|
|
|
|
|
|
Ok(buf)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn map_err(error: tikv_jemalloc_ctl::Error) -> crate::Error {
|
|
|
|
|
err!("mallctl: {}", error.to_string())
|
|
|
|
|
}
|