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

Added configuration option for setting mem_limit in /sys/block/zramX/… #192

Merged
merged 6 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
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
12 changes: 10 additions & 2 deletions man/zram-generator.conf.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,18 @@ Devices with the final size of *0* will be discarded.

Sets the size of the zram device as a function of *MemTotal*, available as the `ram` variable.

Arithmetic operators (^%/\*-+), e, π, SI suffixes, log(), int(), ceil(), floor(), round(), abs(), min(), max(), and trigonometric functions are supported.

Arithmetic operators (^%/\*-+), e, π, SI suffixes, log(), int(), ceil(), floor(), round(), abs(), min(), max(), and trigonometric functions are supported.
Defaults to *min(ram / 2, 4096)*.

* `zram-resident-limit`=

Sets the maximum resident memory limit of the zram device as a function of *MemTotal*, available as the `ram` variable.

Same format as *zram-size*.

Defaults to *0* (no limit).

* `compression-algorithm`=

Specifies the algorithm used to compress the zram device.
Expand Down
81 changes: 63 additions & 18 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* SPDX-License-Identifier: MIT */

use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, Context, Error, Result};
use fasteval::Evaler;
use ini::Ini;
use log::{info, warn};
Expand All @@ -25,6 +25,10 @@ pub struct Device {
pub writeback_dev: Option<PathBuf>,
pub disksize: u64,

/// sets maximum zramX device limit (/sys/block/zramX/mem_limit option)
pub zram_resident_limit: Option<(String, fasteval::ExpressionI, fasteval::Slab)>,
pub mem_limit: u64,

pub swap_priority: i32,
/// when set, a mount unit will be created
pub mount_point: Option<PathBuf>,
Expand All @@ -48,6 +52,8 @@ impl Device {
compression_algorithm: None,
writeback_dev: None,
disksize: 0,
zram_resident_limit: None,
mem_limit: 0,
swap_priority: 100,
mount_point: None,
fs_type: None,
Expand Down Expand Up @@ -87,6 +93,32 @@ impl Device {
}
}

fn process_size(
&self,
zram_option: &Option<(String, fasteval::ExpressionI, fasteval::Slab)>,
memtotal_mb: f64,
name: &str,
default_size: f64,
label: &str,
) -> Result<u64, Error> {
Ok((match zram_option {
Some(zs) => {
zs.1.from(&zs.2.ps)
.eval(&zs.2, &mut RamNs(memtotal_mb))
.with_context(|| format!("{} {}", name, label))
.and_then(|f| {
if f >= 0. {
Ok(f)
} else {
Err(anyhow!("{}: {}={} < 0", name, label, f))
}
})?
}
None => default_size,
} * 1024.0
* 1024.0) as u64)
}

fn set_disksize_if_enabled(&mut self, memtotal_mb: u64) -> Result<()> {
if !self.is_enabled(memtotal_mb) {
return Ok(());
Expand All @@ -99,22 +131,20 @@ impl Device {
.min(max_mb)
* (1024 * 1024);
} else {
self.disksize = (match self.zram_size.as_ref() {
Some(zs) => {
zs.1.from(&zs.2.ps)
.eval(&zs.2, &mut RamNs(memtotal_mb as f64))
.with_context(|| format!("{} zram-size", self.name))
.and_then(|f| {
if f >= 0. {
Ok(f)
} else {
Err(anyhow!("{}: zram-size={} < 0", self.name, f))
}
})?
}
None => (memtotal_mb as f64 / 2.).min(4096.), // DEFAULT_ZRAM_SIZE
} * 1024.
* 1024.) as u64;
self.disksize = self.process_size(
&self.zram_size,
memtotal_mb as f64,
&self.name,
(memtotal_mb as f64 / 2.).min(4096.),
"zram-size",
)?;
self.mem_limit = self.process_size(
&self.zram_resident_limit,
memtotal_mb as f64,
&self.name,
0.,
"zram-resident-limit",
)?;
}

Ok(())
Expand All @@ -125,13 +155,17 @@ impl fmt::Display for Device {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: host-memory-limit={} zram-size={} compression-algorithm={} writeback-device={} options={}",
"{}: host-memory-limit={} zram-size={} zram_resident_limit={} compression-algorithm={} writeback-device={} options={}",
self.name,
OptMB(self.host_memory_limit_mb),
self.zram_size
.as_ref()
.map(|zs| &zs.0[..])
.unwrap_or(DEFAULT_ZRAM_SIZE),
self.zram_resident_limit
.as_ref()
.map(|zs| &zs.0[..])
.unwrap_or("0"),
self.compression_algorithm.as_deref().unwrap_or("<default>"),
self.writeback_dev.as_deref().unwrap_or_else(|| Path::new("<none>")).display(),
self.options
Expand Down Expand Up @@ -330,6 +364,17 @@ fn parse_line(dev: &mut Device, key: &str, value: &str) -> Result<()> {
));
}

"zram-resident-limit" => {
let mut sl = fasteval::Slab::new();
dev.zram_resident_limit = Some((
value.to_string(),
fasteval::Parser::new()
.parse_noclear(value, &mut sl.ps)
.with_context(|| format!("{} zram-resident-limit", dev.name))?,
sl,
));
Comment on lines +368 to +375
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clear copy-paste of the "zram-size" branch

}

"compression-algorithm" => {
dev.compression_algorithm = Some(value.to_string());
}
Expand Down
8 changes: 8 additions & 0 deletions src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ pub fn run_device_setup(device: Option<Device>, device_name: &str) -> Result<()>
}
}

let resident_memory = device_sysfs_path.join("mem_limit");
fs::write(&resident_memory, format!("{}", device.mem_limit)).with_context(|| {
format!(
"Failed to configure zram maximum resident memory limit into {}",
resident_memory.display()
)
})?;

let disksize_path = device_sysfs_path.join("disksize");
fs::write(&disksize_path, format!("{}", device.disksize)).with_context(|| {
format!(
Expand Down
8 changes: 8 additions & 0 deletions zram-generator.conf.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ host-memory-limit = 9048
# The default is "min(ram / 2, 4096)".
zram-size = min(ram / 10, 2048)

# The maximum memory resident for this zram device, as a function of MemTotal,
# both in MB.
# For example, if the machine has 1 GiB, and zram-resident-limit=ram/8,
# then the resident space on RAM won't exceed 128 MiB.
#
# The default is "0" (no limit).
zram-resident-limit = 0

# The compression algorithm to use for the zram device,
# or leave unspecified to keep the kernel default.
compression-algorithm = lzo-rle
Expand Down
Loading