Files
continuwuity/src/core/alloc/je.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

483 lines
13 KiB
Rust
Raw Normal View History

//! jemalloc allocator
use std::{
any::Any,
ffi::{CStr, CString, c_char, c_void},
2025-01-18 01:32:37 +00:00
fmt::Debug,
panic::{self, AssertUnwindSafe},
ptr,
sync::OnceLock,
};
2024-04-27 04:50:20 -07: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},
};
#[cfg(feature = "jemalloc_conf")]
#[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",
MALLOC_CONF_PLATFORM,
2025-01-29 06:36:14 +00:00
MALLOC_CONF_PROF,
0
);
#[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 = "";
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
type Name = ArrayVec<u8, NAME_MAX>;
2025-01-18 01:30:41 +00:00
type Key = ArrayVec<usize, KEY_SEGS>;
const NAME_MAX: usize = 128;
2025-01-18 01:30:41 +00:00
const KEY_SEGS: usize = 8;
2026-05-03 08:55:50 -04:00
#[ctor::ctor(unsafe)]
2025-01-18 01:30:41 +00:00
fn _static_initialization() {
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
}
2024-05-09 15:59:08 -07:00
#[must_use]
2024-08-18 17:36:33 -04:00
#[cfg(feature = "jemalloc_stats")]
pub fn memory_usage() -> Option<String> {
let mibs = |input: usize| {
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
};
let [allocated, active, mapped, metadata, resident, retained] =
memory_usage_stats()?.map(|(_, bytes)| mibs(bytes));
Some(format!(
"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-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 }
#[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 }
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
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()?;
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
// 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
if let Some(payload) = state.panic {
panic::resume_unwind(payload);
}
Some(state.buf)
2024-04-27 04:50:20 -07:00
}
unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) {
// SAFETY: `opaque` points to `StatsPrintState` on the caller's stack.
let Some(state) = (unsafe { opaque.cast::<StatsPrintState>().as_mut() }) else {
return;
};
2024-04-27 22:03:30 -07: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
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
}
macro_rules! mallctl {
($name:literal) => {{
static KEY: OnceLock<Key> = OnceLock::new();
KEY.get_or_init(|| key($name).expect("failed to translate name into mib key"))
.clone()
}};
}
pub mod this_thread {
use super::{Debug, Key, OnceLock, Result, is_nonzero, key, math};
2025-01-24 11:29:36 +00:00
pub fn trim() -> Result { decay().and_then(|()| purge()) }
2025-01-24 11:29:36 +00:00
pub fn purge() -> Result { notify(mallctl!("arena.0.purge")) }
2025-01-18 01:30:41 +00:00
pub fn decay() -> Result { notify(mallctl!("arena.0.decay")) }
2025-01-24 11:29:36 +00:00
pub fn idle() -> Result { super::notify(&mallctl!("thread.idle")) }
2025-01-18 01:30:41 +00:00
pub fn flush() -> Result { super::notify(&mallctl!("thread.tcache.flush")) }
pub fn set_muzzy_decay(decay_ms: isize) -> Result<isize> {
set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms)
}
2025-01-18 01:30:41 +00:00
pub fn get_muzzy_decay() -> Result<isize> { get(mallctl!("arena.0.muzzy_decay_ms")) }
pub fn set_dirty_decay(decay_ms: isize) -> Result<isize> {
set(mallctl!("arena.0.dirty_decay_ms"), decay_ms)
}
2025-01-18 01:30:41 +00:00
pub fn get_dirty_decay() -> Result<isize> { get(mallctl!("arena.0.dirty_decay_ms")) }
pub fn cache_enable(enable: bool) -> Result<bool> {
2025-01-18 01:30:41 +00:00
super::set::<u8>(&mallctl!("thread.tcache.enabled"), enable.into()).map(is_nonzero!())
}
2025-01-18 01:30:41 +00:00
pub fn is_cache_enabled() -> Result<bool> {
super::get::<u8>(&mallctl!("thread.tcache.enabled")).map(is_nonzero!())
}
2025-01-18 01:30:41 +00:00
pub fn set_arena(id: usize) -> Result<usize> {
super::set::<u32>(&mallctl!("thread.arena"), id.try_into()?).and_then(math::try_into)
}
2025-01-18 01:30:41 +00:00
pub fn arena_id() -> Result<usize> {
super::get::<u32>(&mallctl!("thread.arena")).and_then(math::try_into)
}
pub fn prof_enable(enable: bool) -> Result<bool> {
super::set::<u8>(&mallctl!("thread.prof.active"), enable.into()).map(is_nonzero!())
}
2025-01-18 01:30:41 +00:00
pub fn is_prof_enabled() -> Result<bool> {
super::get::<u8>(&mallctl!("thread.prof.active")).map(is_nonzero!())
}
pub fn reset_peak() -> Result { super::notify(&mallctl!("thread.peak.reset")) }
pub fn peak() -> Result<u64> { super::get(&mallctl!("thread.peak.read")) }
#[inline]
#[must_use]
pub fn allocated() -> u64 {
super::get(&mallctl!("thread.allocated")).unwrap_or_default()
}
#[inline]
#[must_use]
pub fn deallocated() -> u64 {
super::get(&mallctl!("thread.deallocated")).unwrap_or_default()
}
2025-01-18 01:30:41 +00:00
fn notify(key: Key) -> Result { super::notify_by_arena(Some(arena_id()?), key) }
fn set<T>(key: Key, val: T) -> Result<T>
where
T: Copy + Debug,
{
super::set_by_arena(Some(arena_id()?), key, val)
}
fn get<T>(key: Key) -> Result<T>
where
T: Copy + Debug,
{
super::get_by_arena(Some(arena_id()?), key)
}
}
pub fn stats_reset() -> Result { notify(&mallctl!("stats.mutexes.reset")) }
pub fn prof_reset() -> Result { notify(&mallctl!("prof.reset")) }
pub fn prof_enable(enable: bool) -> Result<bool> {
set::<u8>(&mallctl!("prof.active"), enable.into()).map(is_nonzero!())
}
pub fn is_prof_enabled() -> Result<bool> {
get::<u8>(&mallctl!("prof.active")).map(is_nonzero!())
}
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 {
2025-01-18 01:30:41 +00:00
notify_by_arena(arena.into(), mallctl!("arena.4096.purge"))
}
pub fn decay<I: Into<Option<usize>>>(arena: I) -> Result {
notify_by_arena(arena.into(), mallctl!("arena.4096.decay"))
}
pub fn set_muzzy_decay<I: Into<Option<usize>>>(arena: I, decay_ms: isize) -> Result<isize> {
match arena.into() {
| Some(arena) =>
set_by_arena(Some(arena), mallctl!("arena.4096.muzzy_decay_ms"), decay_ms),
| _ => 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> {
match arena.into() {
| Some(arena) =>
set_by_arena(Some(arena), mallctl!("arena.4096.dirty_decay_ms"), decay_ms),
| _ => set(&mallctl!("arenas.dirty_decay_ms"), decay_ms),
2025-01-18 01:30:41 +00:00
}
}
pub fn background_thread_enable(enable: bool) -> Result<bool> {
set::<u8>(&mallctl!("background_thread"), enable.into()).map(is_nonzero!())
}
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> {
let ptr = get::<*const c_char>(&mallctl!("opt.percpu_arena"))?;
//SAFETY: ptr points to a null-terminated string returned for
// opt.percpu_arena.
let cstr = unsafe { CStr::from_ptr(ptr) };
cstr.to_str().map_err(Into::into)
}
pub fn arenas() -> Result<usize> {
get::<u32>(&mallctl!("arenas.narenas")).and_then(math::try_into)
}
pub fn inc_epoch() -> Result<u64> { xchg(&mallctl!("epoch"), 1_u64) }
pub fn acq_epoch() -> Result<u64> { xchg(&mallctl!("epoch"), 0_u64) }
fn notify_by_arena(id: Option<usize>, mut key: Key) -> Result {
key[1] = id.unwrap_or(4096);
notify(&key)
}
fn set_by_arena<T>(id: Option<usize>, mut key: Key, val: T) -> Result<T>
where
T: Copy + Debug,
{
2025-01-18 01:30:41 +00:00
key[1] = id.unwrap_or(4096);
set(&key, val)
}
fn get_by_arena<T>(id: Option<usize>, mut key: Key) -> Result<T>
where
T: Copy + Debug,
{
key[1] = id.unwrap_or(4096);
get(&key)
}
fn notify(key: &Key) -> Result {
// 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
fn set<T>(key: &Key, val: T) -> Result<T>
where
T: Copy + Debug,
{
2025-07-19 22:20:26 +01:00
let _lock = CONTROL.write();
2025-01-18 01:30:41 +00:00
let res = xchg(key, val)?;
inc_epoch()?;
Ok(res)
}
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)
)]
fn get<T>(key: &Key) -> Result<T>
where
T: Copy + Debug,
{
2025-01-18 01:30:41 +00:00
acq_epoch()?;
// SAFETY: T must be perfectly valid to receive value.
unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err)
}
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)
)]
2025-01-18 01:30:41 +00:00
fn xchg<T>(key: &Key, val: T) -> Result<T>
where
T: Copy + Debug,
{
// SAFETY: T must be the exact expected type.
unsafe { mallctl::raw::update_mib(key.as_slice(), val) }.map_err(map_err)
}
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)?;
if segs > KEY_SEGS {
return Err(err!("mallctl: key has too many segments ({segs} > {KEY_SEGS})"));
}
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> {
if name.as_bytes().contains(&0) {
return Err(err!("mallctl: key contains interior NUL byte"));
}
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())
}