use std::ffi::c_int;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tuning {
Applied {
threshold: u64,
},
Disabled,
Unsupported,
TooLarge {
threshold: u64,
},
Failed {
threshold: u64,
},
}
impl Tuning {
pub(crate) fn report(self) {
match self {
Self::Applied { threshold } => {
tracing::info!(threshold, "the system allocator mmap threshold is applied");
}
Self::Disabled => {
tracing::debug!("the system allocator mmap threshold is left unchanged");
}
Self::Unsupported => {
tracing::debug!(
"the system allocator mmap threshold is not applied: the platform is not glibc"
);
}
Self::TooLarge { threshold } => {
tracing::warn!(
threshold,
"the system allocator mmap threshold is not applied: the value is too large"
);
}
Self::Failed { threshold } => {
tracing::warn!(
threshold,
"the system allocator mmap threshold is not applied: the allocator refused it"
);
}
}
}
}
pub(crate) fn tune(mmap_threshold: Option<u64>) -> Tuning {
let Some(threshold) = mmap_threshold.filter(|value| *value > 0) else {
return Tuning::Disabled;
};
if !cfg!(target_env = "gnu") {
return Tuning::Unsupported;
}
let Ok(value) = c_int::try_from(threshold) else {
return Tuning::TooLarge { threshold };
};
if apply(value).is_none() {
return Tuning::Failed { threshold };
}
Tuning::Applied { threshold }
}
#[cfg(target_env = "gnu")]
#[allow(unsafe_code)]
fn apply(threshold: c_int) -> Option<()> {
let applied = unsafe { libc::mallopt(libc::M_MMAP_THRESHOLD, threshold) } != 0;
if !applied {
return None;
}
unsafe {
libc::malloc_trim(0);
}
Some(())
}
#[cfg(not(target_env = "gnu"))]
fn apply(_threshold: c_int) -> Option<()> {
None
}
#[cfg(test)]
mod tests {
use super::{Tuning, tune};
#[test]
fn threshold_is_applied_on_glibc() {
if cfg!(target_env = "gnu") {
assert_eq!(
tune(Some(2 * 1024 * 1024)),
Tuning::Applied {
threshold: 2 * 1024 * 1024
}
);
}
}
#[test]
fn null_and_zero_disable_the_threshold() {
assert_eq!(tune(None), Tuning::Disabled);
assert_eq!(tune(Some(0)), Tuning::Disabled);
}
#[cfg(target_env = "gnu")]
#[test]
fn value_above_the_allocator_limit_is_rejected() {
let too_large = 2_147_483_648;
assert_eq!(
tune(Some(too_large)),
Tuning::TooLarge {
threshold: too_large
}
);
}
#[cfg(not(target_env = "gnu"))]
#[test]
fn tuning_is_unsupported_off_glibc() {
assert_eq!(tune(Some(2 * 1024 * 1024)), Tuning::Unsupported);
}
}