Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: set M_MMAP_THRESHOLD to prevent memory fragmentation #73

Merged
merged 2 commits into from
Feb 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,32 @@ mod img_source;
mod scaler;
mod wallpaper;

/// Access glibc malloc tunables.
#[cfg(target_env = "gnu")]
mod malloc {
use std::os::raw::c_int;
const M_MMAP_THRESHOLD: c_int = -3;

extern "C" {
fn malloc_trim(pad: usize);
fn mallopt(param: c_int, value: c_int) -> c_int;
}

/// Prevents glibc from hoarding memory via memory fragmentation.
pub fn limit_mmap_threshold() {
unsafe {
mallopt(M_MMAP_THRESHOLD, 65536);
}
}

/// Asks glibc to trim malloc arenas.
pub fn trim() {
unsafe {
malloc_trim(0);
}
}
}

use cosmic_bg_config::{state::State, Config};
use cosmic_config::{calloop::ConfigWatchSource, CosmicConfigEntry};
use eyre::Context;
Expand Down Expand Up @@ -43,15 +69,11 @@ use sctk::{
},
shm::{slot::SlotPool, Shm, ShmHandler},
};

use tracing::error;
use tracing_subscriber::prelude::*;
use wallpaper::Wallpaper;

#[cfg(target_env = "gnu")]
extern "C" {
fn malloc_trim(pad: usize);
}

#[derive(Debug)]
pub struct CosmicBgLayer {
layer: LayerSurface,
Expand All @@ -66,6 +88,10 @@ pub struct CosmicBgLayer {

#[allow(clippy::too_many_lines)]
fn main() -> color_eyre::Result<()> {
// Prevents glibc from hoarding memory via memory fragmentation.
#[cfg(target_env = "gnu")]
malloc::limit_mmap_threshold();

color_eyre::install()?;

if std::env::var("RUST_SPANTRACE").is_err() {
Expand Down Expand Up @@ -151,9 +177,7 @@ fn main() -> color_eyre::Result<()> {
state.apply_backgrounds();

#[cfg(target_env = "gnu")]
unsafe {
malloc_trim(0);
}
malloc::trim();

tracing::debug!(
same_on_all = state.config.same_on_all,
Expand Down
Loading