leleka-memory loses libc and windows-sys: PageLocking and ProcSource ports, OS adapters in the new L3 crate leleka-memory-os
The two baselined forbidden-dep violations are gone. FdMapping keeps the bounds checks and lock bookkeeping as safe Rust over plain addresses; mmap/mlock/mincore/madvise/munmap/setrlimit are LinuxPageLocking, the Win32 host facts are WindowsProc, the glibc heap trim moved verbatim. Governor::real is replaced by leleka_memory_os::real_governor (the page-locking adapter is part of it). No behaviour change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
b5e7c2834f
commit
51b45b82d8
Generated
+12
-1
@@ -1313,6 +1313,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"leleka-memory",
|
||||
"leleka-memory-os",
|
||||
"leleka-model-format",
|
||||
"leleka-obs",
|
||||
"rustix",
|
||||
@@ -1350,6 +1351,7 @@ dependencies = [
|
||||
"leleka-engine-core",
|
||||
"leleka-experimental-ref",
|
||||
"leleka-memory",
|
||||
"leleka-memory-os",
|
||||
"leleka-model-format",
|
||||
"leleka-native-cpu-expert",
|
||||
"leleka-obs",
|
||||
@@ -1499,9 +1501,18 @@ name = "leleka-memory"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"leleka-obs",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-memory-os"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"leleka-memory",
|
||||
"leleka-obs",
|
||||
"libc",
|
||||
"serde",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "crates/engine-fake", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-model", "crates/cuda-driver", "crates/engine-qwen35-cuda", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
|
||||
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "crates/engine-fake", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
|
||||
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "crates/engine-fake", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-model", "crates/cuda-driver", "crates/engine-qwen35-cuda", "crates/leleka-runtime", "crates/leleka-memory", "crates/memory-os", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
|
||||
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "crates/engine-fake", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/memory-os", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
{
|
||||
"_comment": "Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline refuses to raise one). Do not edit by hand; regenerate. Policy: architecture.json.",
|
||||
"violations": [
|
||||
"forbidden-dep leleka-memory libc",
|
||||
"forbidden-dep leleka-memory windows-sys"
|
||||
],
|
||||
"violations": [],
|
||||
"oversize": {},
|
||||
"source": {
|
||||
"dyn-trait:leleka-backend-api": 1,
|
||||
@@ -20,7 +17,7 @@
|
||||
"dyn-trait:leleka-gptoss-igpu": 3,
|
||||
"dyn-trait:leleka-gptoss-npu": 3,
|
||||
"dyn-trait:leleka-gpu-npu-worker": 5,
|
||||
"dyn-trait:leleka-memory": 17,
|
||||
"dyn-trait:leleka-memory": 12,
|
||||
"dyn-trait:leleka-model-format": 8,
|
||||
"dyn-trait:leleka-tokenizer": 1,
|
||||
"dyn-trait:strata-control": 11,
|
||||
@@ -37,7 +34,8 @@
|
||||
"env-read:leleka-gpu-npu-worker": 2,
|
||||
"env-read:leleka-igpu": 1,
|
||||
"env-read:leleka-libc-shim": 3,
|
||||
"env-read:leleka-memory": 3,
|
||||
"env-read:leleka-memory": 2,
|
||||
"env-read:leleka-memory-os": 1,
|
||||
"env-read:leleka-model-format": 5,
|
||||
"env-read:leleka-native-cpu-expert": 19,
|
||||
"env-read:leleka-native-parity-bench": 1,
|
||||
@@ -76,7 +74,8 @@
|
||||
"process-global:leleka-gateway-text": 5,
|
||||
"process-global:leleka-gptoss-npu": 3,
|
||||
"process-global:leleka-libc-shim": 13,
|
||||
"process-global:leleka-memory": 10,
|
||||
"process-global:leleka-memory": 8,
|
||||
"process-global:leleka-memory-os": 2,
|
||||
"process-global:leleka-model-format": 8,
|
||||
"process-global:leleka-native-cpu-expert": 32,
|
||||
"process-global:leleka-obs": 7,
|
||||
|
||||
+3
-2
@@ -13,7 +13,7 @@
|
||||
],
|
||||
"L2": ["leleka-gateway-domain", "leleka-engine-core"],
|
||||
"L3": [
|
||||
"leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
|
||||
"leleka-libc-shim", "leleka-memory-os", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
|
||||
"leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker",
|
||||
"leleka-gpu-npu-worker", "leleka-offline-tools", "leleka-runtime-client",
|
||||
"leleka-engine-fake",
|
||||
@@ -41,7 +41,8 @@
|
||||
["leleka-offline-tools", "leleka-model-format"],
|
||||
["leleka-engine-qwen35-cuda", "leleka-cuda-driver"],
|
||||
["leleka-engine-qwen35-cuda", "leleka-model-format"],
|
||||
["leleka-engine-qwen35-cuda", "leleka-native-cpu-expert"]
|
||||
["leleka-engine-qwen35-cuda", "leleka-native-cpu-expert"],
|
||||
["leleka-engine-qwen35-cuda", "leleka-memory-os"]
|
||||
],
|
||||
"mechanical_names": {
|
||||
"why": "a module name must say what it is and what it is for; names left by mechanical splits (impl_*, *_fn, numbered) make the source hard to read",
|
||||
|
||||
@@ -38,6 +38,7 @@ rustix = { version = "=1.1.5", features = ["fs", "process", "stdio"] }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Console", "Win32_UI_WindowsAndMessaging"] }
|
||||
leleka-memory = { path = "../leleka-memory" }
|
||||
leleka-memory-os = { path = "../memory-os" }
|
||||
|
||||
# The workspace forbids unsafe code; this crate denies it and lets exactly one module (`winsys`, Windows only) opt in.
|
||||
[lints.rust]
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Windows probe of the host facts: nvidia-smi, memory, ports and the CUDA libraries on PATH.
|
||||
|
||||
use super::*;
|
||||
use leleka_memory::{ProcSource, RealProc};
|
||||
use leleka_memory::ProcSource;
|
||||
use leleka_memory_os::HostProc;
|
||||
use std::{net::TcpListener, process::Command};
|
||||
|
||||
fn nvidia_smi() -> Option<PathBuf> {
|
||||
@@ -29,7 +30,7 @@ pub fn probe(request: &ProbeRequest) -> Facts {
|
||||
};
|
||||
// The memory governor's Win32 view, rendered as /proc/meminfo: available = available physical memory,
|
||||
// swap = commit limit - RAM (`leleka-memory/src/winproc.rs`).
|
||||
facts.memory = RealProc
|
||||
facts.memory = HostProc::default()
|
||||
.read("/proc/meminfo")
|
||||
.map(|text| parse_meminfo(&text))
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -21,6 +21,7 @@ leleka-experimental-ref = { path = "../experimental-ref" }
|
||||
leleka-sampler-ref = { path = "../sampler-ref" }
|
||||
leleka-context = { path = "../context" }
|
||||
leleka-memory = { path = "../leleka-memory" }
|
||||
leleka-memory-os = { path = "../memory-os" }
|
||||
leleka-obs = { path = "../obs" }
|
||||
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver"] }
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_memory::telemetry;
|
||||
use leleka_memory_os::HostProc;
|
||||
|
||||
/// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply
|
||||
/// target, as `serve_load` does after its loop.
|
||||
@@ -15,7 +17,7 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError
|
||||
let model = RecordedModel { artifact_digest: &loaded.descriptor.artifact_digest, files: &model_files };
|
||||
let (stack, mut workers) = open_run_stack(&binding, &context, &options, context_tokens, model)?;
|
||||
publish_open(&stack, shared, (&options, &model_files), (context_tokens, workers));
|
||||
let _telemetry = leleka_memory::telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1));
|
||||
let _telemetry = telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1), HostProc::default());
|
||||
let mut stack = Some(stack);
|
||||
if !announce(shared, reply, &loaded, &mut stack)? {
|
||||
drop(stack);
|
||||
|
||||
@@ -26,7 +26,7 @@ pub fn available_memory() -> Option<u64> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use leleka_memory::ProcSource;
|
||||
let text = leleka_memory::RealProc.read("/proc/meminfo").ok()?;
|
||||
let text = leleka_memory_os::HostProc::default().read("/proc/meminfo").ok()?;
|
||||
mem_available(text.as_bytes())
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
|
||||
@@ -47,7 +47,7 @@ mod tests {
|
||||
#[test]
|
||||
fn windows_renders_the_proc_meminfo_text_the_guards_parse() {
|
||||
use leleka_memory::ProcSource;
|
||||
let text = leleka_memory::RealProc.read("/proc/meminfo").unwrap();
|
||||
let text = leleka_memory_os::HostProc::default().read("/proc/meminfo").unwrap();
|
||||
let available = mem_available(text.as_bytes()).expect("MemAvailable");
|
||||
assert!(available > (64 << 20));
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ use crate::qwen_forward::{
|
||||
original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig},
|
||||
};
|
||||
use leleka_memory::census::{Census, Tolerances, check_flat};
|
||||
use leleka_memory::{Admission, Governor, Level, RealProc, RequestShape};
|
||||
use leleka_memory::{Admission, Governor, Level, RequestShape};
|
||||
use leleka_memory_os::HostProc;
|
||||
use std::env;
|
||||
|
||||
fn required_path(name: &str) -> PathBuf {
|
||||
@@ -138,7 +139,7 @@ fn serve_one(
|
||||
}
|
||||
|
||||
fn census(context: &leleka_cuda_driver::Context<'_>) -> Census {
|
||||
let c = Census::take(&RealProc);
|
||||
let c = Census::take(&HostProc::default());
|
||||
match context.memory_info() {
|
||||
Ok((free, total)) => c.with_device((total - free) as u64, context.allocated_bytes() as u64),
|
||||
Err(_) => c,
|
||||
|
||||
+3
-3
@@ -121,7 +121,7 @@ impl Mem<'_, '_> {
|
||||
self.governor.sample_now();
|
||||
let c = self.census();
|
||||
let facts = self.governor.probe();
|
||||
let heap = leleka_memory::heap::stats().unwrap_or_default();
|
||||
let heap = leleka_memory_os::heap::stats().unwrap_or_default();
|
||||
let prefix = self.stack.prefix_bytes() as u64;
|
||||
let row = tsv_row(t, run.req, &c, (&facts, &heap), prefix);
|
||||
run.tsv.push_str(&row.map(|v| v.to_string()).join("\t"));
|
||||
@@ -138,7 +138,7 @@ fn tsv_row(
|
||||
t: u64,
|
||||
req: usize,
|
||||
c: &Census,
|
||||
(facts, heap): (&leleka_memory::HostFacts, &leleka_memory::heap::HeapStats),
|
||||
(facts, heap): (&leleka_memory::HostFacts, &leleka_memory_os::heap::HeapStats),
|
||||
prefix: u64,
|
||||
) -> [u64; 21] {
|
||||
let mi = &facts.meminfo;
|
||||
@@ -154,7 +154,7 @@ fn tsv_row(
|
||||
row
|
||||
}
|
||||
/// The point of the series: the request count and the values the slopes are fitted to.
|
||||
fn series_point(req: usize, c: &Census, heap: &leleka_memory::heap::HeapStats, prefix: u64) -> [f64; 12] {
|
||||
fn series_point(req: usize, c: &Census, heap: &leleka_memory_os::heap::HeapStats, prefix: u64) -> [f64; 12] {
|
||||
[
|
||||
req as f64,
|
||||
c.rss as f64,
|
||||
|
||||
@@ -9,9 +9,10 @@ use crate::settings::{EnvSource, Settings};
|
||||
use leleka_backend_api::BackendError;
|
||||
use leleka_memory::ledger::{DeviceSample, OpenStage};
|
||||
use leleka_memory::{
|
||||
CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, RealProc, SamplerGuard,
|
||||
CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, SamplerGuard,
|
||||
Space, VramFacts, When,
|
||||
};
|
||||
use leleka_memory_os::{HostProc, real_governor};
|
||||
use std::sync::Mutex;
|
||||
|
||||
mod page_cache;
|
||||
@@ -70,14 +71,14 @@ pub(crate) fn install(laptop: bool, settings: &Settings) -> Result<&'static Gove
|
||||
if let Some(g) = Governor::global() {
|
||||
return Ok(g);
|
||||
}
|
||||
let facts = HostFacts::probe(&RealProc);
|
||||
let facts = HostFacts::probe(&HostProc::default());
|
||||
let total = facts.effective_total().unwrap_or(0);
|
||||
let cfg = GovernorConfig::from_env(total, laptop, &|k| settings.env().get(k)).map_err(|e| BackendError {
|
||||
code: leleka_backend_api::ErrorCode::InvalidRequest,
|
||||
message: e,
|
||||
retryable: false,
|
||||
})?;
|
||||
let g = Governor::real(cfg).install();
|
||||
let g = real_governor(cfg).install();
|
||||
let mut sampler = SAMPLER.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if sampler.is_none() {
|
||||
*sampler = Some(g.spawn_sampler());
|
||||
|
||||
@@ -7,13 +7,13 @@ use super::*;
|
||||
/// sealed memfd into swap. Clean pages only, `POSIX_FADV_DONTNEED`; best effort.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn drop_file_cache(paths: &[&std::path::Path]) {
|
||||
let before = HostFacts::probe(&RealProc).meminfo.cached;
|
||||
let before = HostFacts::probe(&HostProc::default()).meminfo.cached;
|
||||
for path in paths {
|
||||
if let Ok(file) = std::fs::File::open(path) {
|
||||
let _ = rustix::fs::fadvise(&file, 0, None, rustix::fs::Advice::DontNeed);
|
||||
}
|
||||
}
|
||||
let after = HostFacts::probe(&RealProc).meminfo.cached;
|
||||
let after = HostFacts::probe(&HostProc::default()).meminfo.cached;
|
||||
if let (Some(g), Some(b), Some(a)) = (Governor::global(), before, after) {
|
||||
g.log(&format!("page cache of the model shards released: {} MiB -> {} MiB cached", b >> 20, a >> 20));
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fn read_meminfo() -> Result<String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use leleka_memory::ProcSource;
|
||||
leleka_memory::RealProc.read("/proc/meminfo").map_err(|_| Error::InputAllocation)
|
||||
leleka_memory_os::HostProc::default().read("/proc/meminfo").map_err(|_| Error::InputAllocation)
|
||||
}
|
||||
}
|
||||
fn memory_available() -> Result<u64> {
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
if freed > 0 {
|
||||
// the freed blocks sit in the allocator's arenas until they are returned: without this the shed would
|
||||
// not move MemAvailable
|
||||
leleka_memory::heap::trim();
|
||||
leleka_memory_os::heap::trim();
|
||||
}
|
||||
freed
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ fn mem_available_bytes() -> u64 {
|
||||
#[cfg(target_os = "windows")]
|
||||
let meminfo = {
|
||||
use leleka_memory::ProcSource;
|
||||
leleka_memory::RealProc.read("/proc/meminfo")
|
||||
leleka_memory_os::HostProc::default().read("/proc/meminfo")
|
||||
};
|
||||
meminfo
|
||||
.ok()
|
||||
|
||||
@@ -218,7 +218,7 @@ fn read_meminfo() -> Result<String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
fn read_meminfo() -> Result<String> {
|
||||
use leleka_memory::ProcSource;
|
||||
leleka_memory::RealProc.read("/proc/meminfo").map_err(|_| Error::InputAllocation)
|
||||
leleka_memory_os::HostProc::default().read("/proc/meminfo").map_err(|_| Error::InputAllocation)
|
||||
}
|
||||
/// `MemTotal` and `MemAvailable` in bytes; each must appear exactly once.
|
||||
fn meminfo_totals(text: &str) -> Result<(u64, u64)> {
|
||||
|
||||
@@ -11,17 +11,10 @@ serde = { version = "1", features = ["derive"] }
|
||||
leleka-obs = { path = "../obs" }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
|
||||
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
|
||||
libc = "=0.2.190"
|
||||
|
||||
# Windows: the memory facts come from Win32 (GlobalMemoryStatusEx, GetProcessMemoryInfo, GetSystemTimes) and are
|
||||
# rendered in the /proc text formats the governor already parses (`winproc.rs`).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_SystemInformation", "Win32_System_ProcessStatus", "Win32_System_Threading"] }
|
||||
|
||||
# The workspace forbids unsafe code. This crate denies it and lets exactly one module (`lock`: mmap/mlock/mincore/madvise
|
||||
# over a file descriptor's pages, never dereferenced) opt in. Everything else (procfs parsing, planning, the pressure state
|
||||
# machine, the inventory) is safe Rust and runs under Miri.
|
||||
# No libc and no windows-sys: the system calls (mmap/mlock/mincore/madvise over a file descriptor's pages, glibc heap
|
||||
# trim, Win32 host facts) are made by the adapter crate `leleka-memory-os` behind the ports of this crate (`PageLocking`,
|
||||
# `ProcSource`). The workspace forbids unsafe code; this crate denies it and has none: procfs parsing, planning, the
|
||||
# pressure state machine, the inventory and the page-locking bookkeeping are safe Rust and run under Miri.
|
||||
[lints.rust]
|
||||
unsafe_code = "deny"
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
@@ -30,7 +30,7 @@ pub struct Census {
|
||||
}
|
||||
|
||||
impl Census {
|
||||
pub fn take(src: &dyn ProcSource) -> Self {
|
||||
pub fn take(src: &(impl ProcSource + ?Sized)) -> Self {
|
||||
let f = HostFacts::probe(src);
|
||||
Self {
|
||||
rss: f.status.vm_rss.unwrap_or(0),
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! updates the level and publishes the report; status queries read the published text from [`published_report`].
|
||||
|
||||
use crate::census::Census;
|
||||
use crate::host::{HostFacts, ProcSource, RealProc};
|
||||
use crate::host::{HostFacts, ProcSource};
|
||||
use crate::inventory::Inventory;
|
||||
use crate::ledger::Ledger;
|
||||
use crate::lock::{LockDecision, LockMode, LockOutcome};
|
||||
@@ -175,6 +175,9 @@ struct Inner {
|
||||
#[derive(Clone)]
|
||||
pub struct Governor {
|
||||
inner: Arc<Inner>,
|
||||
/// The page-locking adapter of the archive guard; `None` where the composition root installed none.
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pages: Option<crate::lock::SharedPageLocking>,
|
||||
}
|
||||
|
||||
static GLOBAL: OnceLock<Governor> = OnceLock::new();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::lock::{FdMapping, Residency, Span, compact_piece, raise_memlock_soft, spans_bytes};
|
||||
use crate::lock::{FdMapping, Residency, SharedPageLocking, Span, compact_piece, spans_bytes};
|
||||
|
||||
/// What every lock report of one `guard_archive_extents` call shares.
|
||||
pub(super) struct ReportBase {
|
||||
@@ -34,14 +34,18 @@ pub(super) fn check_extents(extents: Option<&[Span]>, len: u64) -> Result<(), Re
|
||||
/// shared mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a
|
||||
/// read-only description can never become writable, so the mapping is allowed everywhere and is immutable by
|
||||
/// construction.
|
||||
pub(super) fn map_readonly_archive(fd: std::os::fd::BorrowedFd<'_>, len: u64) -> std::io::Result<FdMapping> {
|
||||
fn map_readonly_reopen(
|
||||
pages: SharedPageLocking,
|
||||
fd: std::os::fd::BorrowedFd<'_>,
|
||||
len: u64,
|
||||
) -> std::io::Result<FdMapping> {
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _};
|
||||
let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.open(path)
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}")))?;
|
||||
FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX))
|
||||
FdMapping::map_readonly(pages, file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX))
|
||||
}
|
||||
|
||||
/// The refusal of `LELEKA_MEMORY_LOCK=require` when the archive could not be locked.
|
||||
@@ -78,6 +82,13 @@ impl Guarded {
|
||||
}
|
||||
|
||||
impl Governor {
|
||||
/// Map the archive descriptor through the installed page-locking adapter (an error when none was installed).
|
||||
pub(super) fn map_readonly_archive(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64) -> std::io::Result<FdMapping> {
|
||||
let pages = self.pages.clone();
|
||||
let pages = pages.ok_or_else(|| std::io::Error::other("no page-locking adapter was installed"))?;
|
||||
map_readonly_reopen(pages, fd, len)
|
||||
}
|
||||
|
||||
/// The report of a lock attempt that mapped `mapping_bytes` of the archive.
|
||||
pub(super) fn lock_report(
|
||||
&self,
|
||||
@@ -154,7 +165,7 @@ impl Governor {
|
||||
len: u64,
|
||||
) -> LockOutcome {
|
||||
if let Some(to) = raise_soft_to
|
||||
&& let Err(e) = raise_memlock_soft(to)
|
||||
&& let Err(e) = mapping.raise_memlock_soft(to)
|
||||
{
|
||||
self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20));
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ impl Governor {
|
||||
return facts;
|
||||
}
|
||||
self.inner.trim.last_ms.store(now, Ordering::Release);
|
||||
if !crate::winproc::trim_working_set() {
|
||||
if !self.inner.src.trim_working_set() {
|
||||
return facts;
|
||||
}
|
||||
let after = self.probe();
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ impl Governor {
|
||||
let extent_bytes = extents.map(crate::lock::spans_bytes);
|
||||
let base = archive_guard::ReportBase { mode, started, memlock: facts.memlock, extent_bytes };
|
||||
let decision = plan_lock(mode, resident, facts.memlock, &facts.status);
|
||||
let mut mapping = match archive_guard::map_readonly_archive(fd, len) {
|
||||
let mut mapping = match self.map_readonly_archive(fd, len) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return self.unmapped_archive(&base, decision, &e),
|
||||
};
|
||||
|
||||
@@ -48,12 +48,22 @@ impl Governor {
|
||||
|
||||
/// A governor over any [`MemoryPressure`] and any clock: the composition root, and the way a test scripts both.
|
||||
pub fn with_parts(cfg: GovernorConfig, pressure: impl MemoryPressure + 'static, clock: AnyClock) -> Self {
|
||||
Self { inner: Arc::new(Inner::new(cfg, pressure, clock)) }
|
||||
Self {
|
||||
inner: Arc::new(Inner::new(cfg, pressure, clock)),
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pages: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A governor over the real `/proc`.
|
||||
pub fn real(cfg: GovernorConfig) -> Self {
|
||||
Self::new(cfg, Arc::new(RealProc))
|
||||
/// [`Self::with_parts`] plus the adapter that maps, locks and inspects the pages of the sealed archive.
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pub fn with_page_locking(
|
||||
cfg: GovernorConfig,
|
||||
pressure: impl MemoryPressure + 'static,
|
||||
clock: AnyClock,
|
||||
pages: crate::lock::SharedPageLocking,
|
||||
) -> Self {
|
||||
Self { pages: Some(pages), ..Self::with_parts(cfg, pressure, clock) }
|
||||
}
|
||||
|
||||
/// Make this the process-wide governor (the first install wins; later ones are returned unchanged).
|
||||
|
||||
@@ -12,13 +12,17 @@ pub trait ProcSource {
|
||||
fn read(&self, path: &str) -> io::Result<String>;
|
||||
/// Number of entries of a directory (`/proc/self/fd`, `/proc/self/task`).
|
||||
fn count_entries(&self, path: &str) -> io::Result<usize>;
|
||||
/// Windows only: move the pages of this process's working set to the standby list so the host counts them as
|
||||
/// available again; `true` when that was done. Hosts that read real `/proc` files have nothing to trim.
|
||||
fn trim_working_set(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `/proc` and `/sys`.
|
||||
/// The real `/proc` and `/sys`, read as files (on Windows the files do not exist; `leleka-memory-os` answers there).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct RealProc;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
impl ProcSource for RealProc {
|
||||
fn read(&self, path: &str) -> io::Result<String> {
|
||||
use std::io::Read;
|
||||
@@ -32,17 +36,6 @@ impl ProcSource for RealProc {
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows has no /proc: the paths the governor reads are answered from Win32 in the same text formats (`winproc.rs`).
|
||||
#[cfg(windows)]
|
||||
impl ProcSource for RealProc {
|
||||
fn read(&self, path: &str) -> io::Result<String> {
|
||||
crate::winproc::read(path).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, path.to_owned()))
|
||||
}
|
||||
fn count_entries(&self, path: &str) -> io::Result<usize> {
|
||||
Err(io::Error::new(io::ErrorKind::NotFound, path.to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixture: files by absolute path, directories by entry count.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FakeProc {
|
||||
@@ -137,7 +130,7 @@ impl HostFacts {
|
||||
pub fn swap_free(&self) -> u64 {
|
||||
self.meminfo.swap_free.unwrap_or(0)
|
||||
}
|
||||
pub fn probe(src: &dyn ProcSource) -> Self {
|
||||
pub fn probe(src: &(impl ProcSource + ?Sized)) -> Self {
|
||||
let text = |p: &str| src.read(p).ok();
|
||||
let meminfo = text("/proc/meminfo").map(|t| procfs::parse_meminfo(&t)).unwrap_or_default();
|
||||
let status = text("/proc/self/status").map(|t| procfs::parse_status(&t)).unwrap_or_default();
|
||||
@@ -167,7 +160,7 @@ impl HostFacts {
|
||||
|
||||
/// The cgroup levels of this process, innermost first, ending at the root. `None` when cgroup v2 is not mounted or
|
||||
/// `/proc/self/cgroup` is not the unified hierarchy.
|
||||
fn probe_cgroup(src: &dyn ProcSource) -> Option<CgroupFacts> {
|
||||
fn probe_cgroup(src: &(impl ProcSource + ?Sized)) -> Option<CgroupFacts> {
|
||||
let text = src.read("/proc/self/cgroup").ok()?;
|
||||
// the unified hierarchy first; on a hybrid host (WSL2, older container hosts) the memory controller may still be a
|
||||
// v1 hierarchy, which is where the limit lives
|
||||
@@ -254,7 +247,7 @@ fn level_v1(src: &(impl ProcSource + ?Sized), dir: &str) -> Option<CgroupLevel>
|
||||
|
||||
/// cgroup v1 `memory` controller: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes`, `memory.stat`
|
||||
/// and the `oom_kill` counter of `memory.oom_control`.
|
||||
fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option<CgroupFacts> {
|
||||
fn probe_cgroup_v1(src: &(impl ProcSource + ?Sized), proc_cgroup: &str) -> Option<CgroupFacts> {
|
||||
const ROOT: &str = "/sys/fs/cgroup/memory";
|
||||
let rel = procfs::parse_cgroup_v1_memory_path(proc_cgroup)?;
|
||||
if escapes_root(&rel) {
|
||||
@@ -288,7 +281,7 @@ fn level_v2(src: &(impl ProcSource + ?Sized), dir: &str) -> Option<CgroupLevel>
|
||||
})
|
||||
}
|
||||
|
||||
fn probe_cgroup_v2(src: &dyn ProcSource, rel: String) -> Option<CgroupFacts> {
|
||||
fn probe_cgroup_v2(src: &(impl ProcSource + ?Sized), rel: String) -> Option<CgroupFacts> {
|
||||
if escapes_root(&rel) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub struct HostSample {
|
||||
}
|
||||
|
||||
impl HostSample {
|
||||
pub fn take(src: &dyn ProcSource) -> Self {
|
||||
pub fn take(src: &(impl ProcSource + ?Sized)) -> Self {
|
||||
let f = HostFacts::probe(src);
|
||||
Self {
|
||||
rss: f.status.vm_rss.unwrap_or(0),
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
pub mod census;
|
||||
pub mod governor;
|
||||
pub mod heap;
|
||||
pub mod host;
|
||||
pub mod inventory;
|
||||
pub mod ledger;
|
||||
|
||||
@@ -78,11 +78,14 @@ pub struct Residency {
|
||||
pub type Span = (u64, u64);
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pub use sys::{FdMapping, raise_memlock_soft};
|
||||
pub use archive_mapping::FdMapping;
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pub use page_locking::{PageLocking, SharedPageLocking};
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
#[allow(unsafe_code)]
|
||||
mod sys;
|
||||
mod archive_mapping;
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
mod page_locking;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! A read-only mapping of the sealed archive descriptor and the bookkeeping of what is locked in it.
|
||||
//!
|
||||
//! This module holds no system call: the `mmap`, `mlock`, `mincore`, `madvise` and `munmap` calls are made by the
|
||||
//! [`PageLocking`] adapter handed in at map time (`leleka-memory-os` in production), so the governor stays free of
|
||||
//! `libc`. An address is a plain integer here: nothing in this crate dereferences it.
|
||||
|
||||
use super::{LockOutcome, PAGE, SharedPageLocking};
|
||||
use std::io;
|
||||
use std::os::fd::BorrowedFd;
|
||||
|
||||
/// A read-only `MAP_SHARED` mapping of a descriptor, held only for `mlock`, `mincore` and `madvise`.
|
||||
///
|
||||
/// Invariants (the whole safety argument of this module):
|
||||
/// * `addr..addr+len` is a live mapping created by `pages.map_readonly` and unmapped exactly once, in `Drop`;
|
||||
/// * the address is only handed back to `pages`, never turned into a reference or slice, so there is nothing to
|
||||
/// dangle, alias or fault on (and the sealed memfd cannot shrink under it);
|
||||
/// * every range handed to `pages` is checked `offset + n <= len` and page aligned first.
|
||||
pub struct FdMapping {
|
||||
pages: SharedPageLocking,
|
||||
addr: usize,
|
||||
len: usize,
|
||||
locked: u64,
|
||||
/// Ranges locked by `lock_ranges` (a sparse archive locks its extents only; the prefix counter above stays 0).
|
||||
locked_spans: Vec<(u64, u64)>,
|
||||
}
|
||||
|
||||
impl FdMapping {
|
||||
/// Map `len` bytes of `fd` read-only. `len` must be non-zero and the descriptor at least that long.
|
||||
pub fn map_readonly(pages: SharedPageLocking, fd: BorrowedFd<'_>, len: usize) -> io::Result<Self> {
|
||||
if len == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty mapping"));
|
||||
}
|
||||
let addr = pages.map_readonly(fd, len)?;
|
||||
Ok(Self { pages, addr, len, locked: 0, locked_spans: Vec::new() })
|
||||
}
|
||||
/// Raise the soft `RLIMIT_MEMLOCK` to `to` (never above the hard limit).
|
||||
pub fn raise_memlock_soft(&self, to: u64) -> io::Result<()> {
|
||||
self.pages.raise_memlock_soft(to)
|
||||
}
|
||||
pub fn start(&self) -> u64 {
|
||||
self.addr as u64
|
||||
}
|
||||
pub fn len(&self) -> u64 {
|
||||
self.len as u64
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
pub fn locked_bytes(&self) -> u64 {
|
||||
self.locked
|
||||
}
|
||||
fn range(&self, offset: u64, n: u64) -> io::Result<(usize, usize)> {
|
||||
if !offset.is_multiple_of(PAGE)
|
||||
|| n == 0
|
||||
|| offset.checked_add(n).is_none_or(|end| end > self.len as u64)
|
||||
|| usize::try_from(offset).is_err()
|
||||
|| usize::try_from(n).is_err()
|
||||
{
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "range outside the mapping"));
|
||||
}
|
||||
// `offset <= len` was checked, so the result stays inside (or one past) the mapping.
|
||||
Ok((self.addr + offset as usize, n as usize))
|
||||
}
|
||||
/// Lock `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before each; stop at the first refusal.
|
||||
/// A chunk that is swapped out must be read back from swap (host memory), which is why the guard exists.
|
||||
pub fn lock(&mut self, chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome {
|
||||
let chunk = chunk.max(PAGE) / PAGE * PAGE;
|
||||
let total = self.len as u64;
|
||||
let mut offset = self.locked;
|
||||
while offset < total {
|
||||
let n = chunk.min(total - offset);
|
||||
if !allow(n) {
|
||||
return LockOutcome::Partial {
|
||||
locked: self.locked,
|
||||
wanted: total,
|
||||
why: "host memory guard refused the next chunk".into(),
|
||||
};
|
||||
}
|
||||
let (ptr, n_usize) = match self.range(offset, n) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() },
|
||||
};
|
||||
if let Err(e) = self.pages.lock(ptr, n_usize) {
|
||||
return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") };
|
||||
}
|
||||
offset += n;
|
||||
self.locked = offset;
|
||||
}
|
||||
LockOutcome::Locked { bytes: self.locked }
|
||||
}
|
||||
/// `mlock` the `n` bytes at `offset` of the mapping; the reason when that fails.
|
||||
fn mlock_range(&self, offset: u64, n: u64) -> Result<(), String> {
|
||||
let (ptr, n_usize) = self.range(offset, n).map_err(|e| e.to_string())?;
|
||||
self.pages.lock(ptr, n_usize).map_err(|e| format!("mlock: {e}"))
|
||||
}
|
||||
/// Ask `allow`, then `mlock` and record the `n` bytes at `offset`; the reason when either refuses.
|
||||
fn lock_chunk(&mut self, offset: u64, n: u64, allow: &mut impl FnMut(u64) -> bool) -> Result<(), String> {
|
||||
if !allow(n) {
|
||||
return Err("host memory guard refused the next chunk".to_owned());
|
||||
}
|
||||
self.mlock_range(offset, n)?;
|
||||
self.locked_spans.push((offset, n));
|
||||
Ok(())
|
||||
}
|
||||
/// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling
|
||||
/// `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. The holes between the spans are never
|
||||
/// touched: `mlock` of a hole in a shmem file allocates zero pages for it (the sparse copy would silently become
|
||||
/// the full 55 GB again), so a range outside the spans is not representable here. `check_spans` runs first. The
|
||||
/// counter `locked_bytes` is the sum of the locked spans.
|
||||
pub fn lock_ranges(
|
||||
&mut self,
|
||||
spans: &[super::Span],
|
||||
chunk: u64,
|
||||
mut allow: impl FnMut(u64) -> bool,
|
||||
) -> LockOutcome {
|
||||
let wanted = super::spans_bytes(spans);
|
||||
if let Err(why) = super::check_spans(spans, self.len as u64) {
|
||||
return LockOutcome::Partial { locked: 0, wanted, why };
|
||||
}
|
||||
let chunk = chunk.max(PAGE) / PAGE * PAGE;
|
||||
let mut locked = 0u64;
|
||||
for &(span_offset, span_len) in spans {
|
||||
let mut done = 0u64;
|
||||
while done < span_len {
|
||||
let n = chunk.min(span_len - done);
|
||||
if let Err(why) = self.lock_chunk(span_offset + done, n, &mut allow) {
|
||||
return LockOutcome::Partial { locked, wanted, why };
|
||||
}
|
||||
done += n;
|
||||
locked += n;
|
||||
self.locked = locked;
|
||||
}
|
||||
}
|
||||
LockOutcome::Locked { bytes: locked }
|
||||
}
|
||||
/// Unlock everything this mapping locked.
|
||||
pub fn unlock(&mut self) {
|
||||
if self.locked > 0 && self.locked_spans.is_empty() {
|
||||
self.pages.unlock(self.addr, self.locked as usize);
|
||||
}
|
||||
for (offset, n) in std::mem::take(&mut self.locked_spans) {
|
||||
if let Ok((ptr, n_usize)) = self.range(offset, n) {
|
||||
self.pages.unlock(ptr, n_usize);
|
||||
}
|
||||
}
|
||||
self.locked = 0;
|
||||
}
|
||||
/// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the
|
||||
/// caller may not write, newer kernels report every page resident: use the smaps number for totals.
|
||||
pub fn incore(&self, offset: u64, n: u64) -> io::Result<Vec<bool>> {
|
||||
let (ptr, n_usize) = self.range(offset, n)?;
|
||||
let pages = n_usize.div_ceil(PAGE as usize);
|
||||
let mut vec = vec![0u8; pages];
|
||||
self.pages.resident_pages(ptr, n_usize, &mut vec)?;
|
||||
Ok(vec.into_iter().map(|b| b & 1 == 1).collect())
|
||||
}
|
||||
/// Bring `offset..offset+n` into memory (read faults, including from swap) without touching the bytes.
|
||||
pub fn populate(&self, offset: u64, n: u64) -> io::Result<()> {
|
||||
let (ptr, n_usize) = self.range(offset, n)?;
|
||||
self.pages.populate(ptr, n_usize)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FdMapping {
|
||||
fn drop(&mut self) {
|
||||
// `addr`/`len` are exactly what `map_readonly` returned/was given, and `drop` runs once; munlock is implied.
|
||||
self.pages.unmap(self.addr, self.len);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lock::PageLocking;
|
||||
use std::os::fd::AsFd;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Records every call and answers with a fake address, so the bookkeeping runs without any system call.
|
||||
#[derive(Default)]
|
||||
struct RecordingPages {
|
||||
calls: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl RecordingPages {
|
||||
fn note(&self, call: String) {
|
||||
self.calls.lock().unwrap().push(call);
|
||||
}
|
||||
}
|
||||
|
||||
impl PageLocking for RecordingPages {
|
||||
fn map_readonly(&self, _fd: BorrowedFd<'_>, len: usize) -> io::Result<usize> {
|
||||
self.note(format!("map {len}"));
|
||||
Ok(0x10_0000)
|
||||
}
|
||||
fn unmap(&self, address: usize, len: usize) {
|
||||
self.note(format!("unmap {address:#x} {len}"));
|
||||
}
|
||||
fn lock(&self, address: usize, len: usize) -> io::Result<()> {
|
||||
self.note(format!("lock {address:#x} {len}"));
|
||||
Ok(())
|
||||
}
|
||||
fn unlock(&self, address: usize, len: usize) {
|
||||
self.note(format!("unlock {address:#x} {len}"));
|
||||
}
|
||||
fn resident_pages(&self, _address: usize, _len: usize, page_flags: &mut [u8]) -> io::Result<()> {
|
||||
page_flags.fill(1);
|
||||
Ok(())
|
||||
}
|
||||
fn populate(&self, _address: usize, _len: usize) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn raise_memlock_soft(&self, _to: u64) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locking_and_unmapping_go_through_the_port_with_checked_addresses() {
|
||||
let pages = Arc::new(RecordingPages::default());
|
||||
let file = std::fs::File::open("/dev/null").unwrap();
|
||||
let mut mapping = FdMapping::map_readonly(pages.clone(), file.as_fd(), 4 * PAGE as usize).unwrap();
|
||||
let outcome = mapping.lock(2 * PAGE, |_| true);
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 4 * PAGE });
|
||||
assert_eq!(mapping.incore(PAGE, 2 * PAGE).unwrap(), [true, true]);
|
||||
assert!(mapping.populate(3 * PAGE, 2 * PAGE).is_err(), "outside the mapping: refused before the port");
|
||||
mapping.unlock();
|
||||
drop(mapping);
|
||||
let calls = pages.calls.lock().unwrap().clone();
|
||||
assert_eq!(
|
||||
calls,
|
||||
["map 16384", "lock 0x100000 8192", "lock 0x102000 8192", "unlock 0x100000 16384", "unmap 0x100000 16384"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The port the archive guard locks and inspects pages through (STRA-338).
|
||||
//!
|
||||
//! The governor decides what to lock and when; the system calls (`mmap`, `mlock`, `mincore`, `madvise`, `munmap`,
|
||||
//! `setrlimit`) belong to an adapter in an L3 crate (`leleka-memory-os`), so this crate stays free of `libc`. Addresses
|
||||
//! are plain integers handed back to the adapter that produced them and are never dereferenced here.
|
||||
|
||||
use std::io;
|
||||
use std::os::fd::BorrowedFd;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A page-locking adapter shared by the governor and the mappings it creates.
|
||||
pub type SharedPageLocking = Arc<dyn PageLocking>;
|
||||
|
||||
/// Page-level operations on a read-only mapping of the sealed archive descriptor.
|
||||
pub trait PageLocking: Send + Sync {
|
||||
/// Map `len` bytes of `fd` read-only and shared; the address of the mapping.
|
||||
fn map_readonly(&self, fd: BorrowedFd<'_>, len: usize) -> io::Result<usize>;
|
||||
/// Unmap a mapping returned by [`Self::map_readonly`] (this also drops its locks).
|
||||
fn unmap(&self, address: usize, len: usize);
|
||||
/// Lock `len` bytes at `address` in RAM (`mlock`).
|
||||
fn lock(&self, address: usize, len: usize) -> io::Result<()>;
|
||||
/// Release the lock of `len` bytes at `address` (`munlock`); a failure is ignored by the caller.
|
||||
fn unlock(&self, address: usize, len: usize);
|
||||
/// One byte per page of `address..address+len`: the lowest bit is set when the page is in memory (`mincore`).
|
||||
fn resident_pages(&self, address: usize, len: usize, page_flags: &mut [u8]) -> io::Result<()>;
|
||||
/// Bring `address..address+len` into memory without touching the bytes (`MADV_POPULATE_READ`).
|
||||
fn populate(&self, address: usize, len: usize) -> io::Result<()>;
|
||||
/// Raise the soft `RLIMIT_MEMLOCK` to `to`, never above the hard limit.
|
||||
fn raise_memlock_soft(&self, to: u64) -> io::Result<()>;
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
//! Moved out of the parent file by STRA-338 (same module path as before).
|
||||
|
||||
use super::{LockOutcome, PAGE};
|
||||
use std::io;
|
||||
use std::os::fd::{AsRawFd, BorrowedFd};
|
||||
|
||||
/// A read-only `MAP_SHARED` mapping of a descriptor, held only for `mlock`, `mincore` and `madvise`.
|
||||
///
|
||||
/// Invariants (the whole safety argument of this module):
|
||||
/// * `addr..addr+len` is a live mapping created by `mmap` in `map_readonly` and unmapped exactly once, in `Drop`;
|
||||
/// * no reference or slice into it is ever created: the pointer is only passed to system calls, so there is
|
||||
/// nothing to dangle, alias or fault on (and the sealed memfd cannot shrink under it);
|
||||
/// * every range handed to a syscall is checked `offset + n <= len` and page aligned first.
|
||||
pub struct FdMapping {
|
||||
addr: *mut libc::c_void,
|
||||
len: usize,
|
||||
locked: u64,
|
||||
/// Ranges locked by `lock_ranges` (a sparse archive locks its extents only; the prefix counter above stays 0).
|
||||
locked_spans: Vec<(u64, u64)>,
|
||||
}
|
||||
|
||||
// SAFETY: the pointer is an address-space handle used only by thread-safe system calls on an immutable mapping; it
|
||||
// is never dereferenced, so sharing it between threads cannot race.
|
||||
unsafe impl Send for FdMapping {}
|
||||
// SAFETY: see `Send`; all methods take `&self` and only issue syscalls, or `&mut self` for the lock counter.
|
||||
unsafe impl Sync for FdMapping {}
|
||||
|
||||
/// Raise the soft `RLIMIT_MEMLOCK` to `to` (never above the hard limit).
|
||||
pub fn raise_memlock_soft(to: u64) -> io::Result<()> {
|
||||
let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
|
||||
// SAFETY: `lim` is a valid, writable rlimit for the duration of the call.
|
||||
if unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, &mut lim) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
lim.rlim_cur = to.min(lim.rlim_max);
|
||||
// SAFETY: `lim` is a valid, initialized rlimit.
|
||||
if unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &lim) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl FdMapping {
|
||||
/// Map `len` bytes of `fd` read-only. `len` must be non-zero and the descriptor at least that long.
|
||||
pub fn map_readonly(fd: BorrowedFd<'_>, len: usize) -> io::Result<Self> {
|
||||
if len == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty mapping"));
|
||||
}
|
||||
// SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing
|
||||
// mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED.
|
||||
let addr =
|
||||
unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) };
|
||||
if addr == libc::MAP_FAILED {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(Self { addr, len, locked: 0, locked_spans: Vec::new() })
|
||||
}
|
||||
pub fn start(&self) -> u64 {
|
||||
self.addr as usize as u64
|
||||
}
|
||||
pub fn len(&self) -> u64 {
|
||||
self.len as u64
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
pub fn locked_bytes(&self) -> u64 {
|
||||
self.locked
|
||||
}
|
||||
fn range(&self, offset: u64, n: u64) -> io::Result<(*mut libc::c_void, usize)> {
|
||||
if !offset.is_multiple_of(PAGE)
|
||||
|| n == 0
|
||||
|| offset.checked_add(n).is_none_or(|end| end > self.len as u64)
|
||||
|| usize::try_from(offset).is_err()
|
||||
|| usize::try_from(n).is_err()
|
||||
{
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "range outside the mapping"));
|
||||
}
|
||||
// SAFETY: `offset <= len` was checked, so the result stays inside (or one past) the mapping.
|
||||
Ok((unsafe { self.addr.cast::<u8>().add(offset as usize) }.cast(), n as usize))
|
||||
}
|
||||
/// Lock `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before each; stop at the first refusal.
|
||||
/// A chunk that is swapped out must be read back from swap (host memory), which is why the guard exists.
|
||||
pub fn lock(&mut self, chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome {
|
||||
let chunk = chunk.max(PAGE) / PAGE * PAGE;
|
||||
let total = self.len as u64;
|
||||
let mut offset = self.locked;
|
||||
while offset < total {
|
||||
let n = chunk.min(total - offset);
|
||||
if !allow(n) {
|
||||
return LockOutcome::Partial {
|
||||
locked: self.locked,
|
||||
wanted: total,
|
||||
why: "host memory guard refused the next chunk".into(),
|
||||
};
|
||||
}
|
||||
let (ptr, n_usize) = match self.range(offset, n) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() },
|
||||
};
|
||||
// SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins
|
||||
// pages.
|
||||
if unsafe { libc::mlock(ptr, n_usize) } != 0 {
|
||||
let e = io::Error::last_os_error();
|
||||
return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") };
|
||||
}
|
||||
offset += n;
|
||||
self.locked = offset;
|
||||
}
|
||||
LockOutcome::Locked { bytes: self.locked }
|
||||
}
|
||||
/// `mlock` the `n` bytes at `offset` of the mapping; the reason when that fails.
|
||||
fn mlock_range(&self, offset: u64, n: u64) -> Result<(), String> {
|
||||
let (ptr, n_usize) = self.range(offset, n).map_err(|e| e.to_string())?;
|
||||
// SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages.
|
||||
if unsafe { libc::mlock(ptr, n_usize) } != 0 {
|
||||
return Err(format!("mlock: {}", io::Error::last_os_error()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Ask `allow`, then `mlock` and record the `n` bytes at `offset`; the reason when either refuses.
|
||||
fn lock_chunk(&mut self, offset: u64, n: u64, allow: &mut impl FnMut(u64) -> bool) -> Result<(), String> {
|
||||
if !allow(n) {
|
||||
return Err("host memory guard refused the next chunk".to_owned());
|
||||
}
|
||||
self.mlock_range(offset, n)?;
|
||||
self.locked_spans.push((offset, n));
|
||||
Ok(())
|
||||
}
|
||||
/// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling
|
||||
/// `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. The holes between the spans are never
|
||||
/// touched: `mlock` of a hole in a shmem file allocates zero pages for it (the sparse copy would silently become
|
||||
/// the full 55 GB again), so a range outside the spans is not representable here. `check_spans` runs first. The
|
||||
/// counter `locked_bytes` is the sum of the locked spans.
|
||||
pub fn lock_ranges(
|
||||
&mut self,
|
||||
spans: &[super::Span],
|
||||
chunk: u64,
|
||||
mut allow: impl FnMut(u64) -> bool,
|
||||
) -> LockOutcome {
|
||||
let wanted = super::spans_bytes(spans);
|
||||
if let Err(why) = super::check_spans(spans, self.len as u64) {
|
||||
return LockOutcome::Partial { locked: 0, wanted, why };
|
||||
}
|
||||
let chunk = chunk.max(PAGE) / PAGE * PAGE;
|
||||
let mut locked = 0u64;
|
||||
for &(span_offset, span_len) in spans {
|
||||
let mut done = 0u64;
|
||||
while done < span_len {
|
||||
let n = chunk.min(span_len - done);
|
||||
if let Err(why) = self.lock_chunk(span_offset + done, n, &mut allow) {
|
||||
return LockOutcome::Partial { locked, wanted, why };
|
||||
}
|
||||
done += n;
|
||||
locked += n;
|
||||
self.locked = locked;
|
||||
}
|
||||
}
|
||||
LockOutcome::Locked { bytes: locked }
|
||||
}
|
||||
/// Unlock everything this mapping locked.
|
||||
pub fn unlock(&mut self) {
|
||||
if self.locked > 0 && self.locked_spans.is_empty() {
|
||||
// SAFETY: the locked prefix `addr..addr+locked` lies inside our live mapping.
|
||||
let _ = unsafe { libc::munlock(self.addr, self.locked as usize) };
|
||||
}
|
||||
for (offset, n) in std::mem::take(&mut self.locked_spans) {
|
||||
if let Ok((ptr, n_usize)) = self.range(offset, n) {
|
||||
// SAFETY: the span was locked by `lock_ranges` and lies inside our live mapping (checked by `range`).
|
||||
let _ = unsafe { libc::munlock(ptr, n_usize) };
|
||||
}
|
||||
}
|
||||
self.locked = 0;
|
||||
}
|
||||
/// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the
|
||||
/// caller may not write, newer kernels report every page resident: use the smaps number for totals.
|
||||
pub fn incore(&self, offset: u64, n: u64) -> io::Result<Vec<bool>> {
|
||||
let (ptr, n_usize) = self.range(offset, n)?;
|
||||
let pages = n_usize.div_ceil(PAGE as usize);
|
||||
let mut vec = vec![0u8; pages];
|
||||
// SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; `vec` has one byte per page of the range.
|
||||
if unsafe { libc::mincore(ptr, n_usize, vec.as_mut_ptr()) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(vec.into_iter().map(|b| b & 1 == 1).collect())
|
||||
}
|
||||
/// Bring `offset..offset+n` into memory (read faults, including from swap) without touching the bytes.
|
||||
pub fn populate(&self, offset: u64, n: u64) -> io::Result<()> {
|
||||
let (ptr, n_usize) = self.range(offset, n)?;
|
||||
// SAFETY: `ptr..ptr+n_usize` lies inside our live mapping; MADV_POPULATE_READ changes no contents.
|
||||
if unsafe { libc::madvise(ptr, n_usize, libc::MADV_POPULATE_READ) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FdMapping {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: `addr`/`len` are exactly what `mmap` returned/was given, and `drop` runs once; nothing borrows
|
||||
// the mapping (no references are ever created into it). munlock is implied by munmap.
|
||||
unsafe {
|
||||
libc::munmap(self.addr, self.len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(miri)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsFd;
|
||||
|
||||
fn file(len: usize) -> std::fs::File {
|
||||
let mut f = tempfile_in_target();
|
||||
f.write_all(&vec![7u8; len]).unwrap();
|
||||
f.flush().unwrap();
|
||||
f
|
||||
}
|
||||
fn tempfile_in_target() -> std::fs::File {
|
||||
// an unlinked file under the system temp dir
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"leleka-memory-lock-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_locks_inside_the_limit_and_reports_incore() {
|
||||
let f = file(64 * 4096);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), 64 * 4096).unwrap();
|
||||
assert_eq!(m.len(), 64 * 4096);
|
||||
let mut asked = Vec::new();
|
||||
let outcome = m.lock(16 * 4096, |n| {
|
||||
asked.push(n);
|
||||
true
|
||||
});
|
||||
// 64 pages = 256 KiB: inside any RLIMIT_MEMLOCK of 8 MiB
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 64 * 4096 }, "{outcome:?}");
|
||||
assert_eq!(asked, vec![16 * 4096; 4]);
|
||||
let pages = m.incore(0, 64 * 4096).unwrap();
|
||||
assert_eq!(pages.len(), 64);
|
||||
assert!(pages.iter().all(|&p| p));
|
||||
m.populate(0, 64 * 4096).unwrap();
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guard_stops_the_lock_between_chunks() {
|
||||
let f = file(32 * 4096);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), 32 * 4096).unwrap();
|
||||
let mut calls = 0;
|
||||
let outcome = m.lock(8 * 4096, |_| {
|
||||
calls += 1;
|
||||
calls <= 2
|
||||
});
|
||||
assert!(matches!(outcome, LockOutcome::Partial { locked, .. } if locked == 16 * 4096), "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 16 * 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_outside_the_mapping_or_unaligned_are_refused_before_any_syscall() {
|
||||
let f = file(8 * 4096);
|
||||
let m = FdMapping::map_readonly(f.as_fd(), 8 * 4096).unwrap();
|
||||
assert!(m.incore(4096, 8 * 4096).is_err());
|
||||
assert!(m.incore(1, 4096).is_err());
|
||||
assert!(m.populate(0, 0).is_err());
|
||||
assert!(m.populate(u64::MAX - 100, 4096).is_err());
|
||||
assert!(m.incore(0, 8 * 4096).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_mapping_is_refused() {
|
||||
let f = file(4096);
|
||||
assert!(FdMapping::map_readonly(f.as_fd(), 0).is_err());
|
||||
}
|
||||
|
||||
/// An anonymous memfd of `pages` pages with data in the page ranges `data` (everything else is a hole).
|
||||
fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File {
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::unix::fs::FileExt;
|
||||
// SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it.
|
||||
let f = unsafe {
|
||||
let fd = libc::memfd_create(c"leleka-lock-test".as_ptr(), 0);
|
||||
assert!(fd >= 0, "memfd_create: {}", io::Error::last_os_error());
|
||||
std::fs::File::from_raw_fd(fd)
|
||||
};
|
||||
f.set_len(pages * PAGE).unwrap();
|
||||
for &(first, count) in data {
|
||||
for page in first..first + count {
|
||||
f.write_all_at(&vec![0xA5u8; PAGE as usize], page * PAGE).unwrap();
|
||||
}
|
||||
}
|
||||
f
|
||||
}
|
||||
fn allocated(f: &std::fs::File) -> u64 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
f.metadata().unwrap().blocks() * 512
|
||||
}
|
||||
fn pages_to_spans(ranges: &[(u64, u64)]) -> Vec<(u64, u64)> {
|
||||
ranges.iter().map(|&(first, count)| (first * PAGE, count * PAGE)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locking_and_populating_the_extents_of_a_sparse_memfd_allocates_nothing_in_the_holes() {
|
||||
let data = [(10u64, 4u64), (100, 6)];
|
||||
let spans = pages_to_spans(&data);
|
||||
let f = sparse_memfd(256, &data);
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "only the pages written exist");
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap();
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "mapping a sparse file allocates nothing");
|
||||
let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| true);
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 10 * PAGE }, "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 10 * PAGE);
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "locking the extents instantiated no hole");
|
||||
for &(offset, n) in &spans {
|
||||
m.populate(offset, n).unwrap();
|
||||
}
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "populating the extents instantiated no hole");
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 10 * PAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() {
|
||||
// the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be
|
||||
// needed
|
||||
let f = sparse_memfd(256, &[(10, 4), (100, 6)]);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap();
|
||||
let outcome = m.lock(64 * PAGE, |_| true);
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 256 * PAGE }, "{outcome:?}");
|
||||
assert_eq!(allocated(&f), 256 * PAGE, "mlock of a shmem hole allocates a zero page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_ranges_refuses_spans_that_are_unaligned_overlapping_unsorted_or_outside_before_any_syscall() {
|
||||
let f = sparse_memfd(16, &[(0, 2)]);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), (16 * PAGE) as usize).unwrap();
|
||||
for bad in [
|
||||
vec![(1, PAGE)],
|
||||
vec![(0, 2 * PAGE), (PAGE, PAGE)],
|
||||
vec![(4 * PAGE, PAGE), (0, PAGE)],
|
||||
vec![(15 * PAGE, 2 * PAGE)],
|
||||
vec![(0, 0)],
|
||||
] {
|
||||
let outcome = m.lock_ranges(&bad, PAGE, |_| panic!("the guard must not be consulted for an invalid span"));
|
||||
assert!(matches!(outcome, LockOutcome::Partial { locked: 0, .. }), "{bad:?}: {outcome:?}");
|
||||
}
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 2 * PAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guard_can_stop_a_ranged_lock_between_chunks_and_unlock_releases_what_was_locked() {
|
||||
let f = sparse_memfd(64, &[(0, 8), (32, 8)]);
|
||||
let mut m = FdMapping::map_readonly(f.as_fd(), (64 * PAGE) as usize).unwrap();
|
||||
let spans = pages_to_spans(&[(0, 8), (32, 8)]);
|
||||
let mut calls = 0;
|
||||
let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| {
|
||||
calls += 1;
|
||||
calls <= 3
|
||||
});
|
||||
let LockOutcome::Partial { locked, wanted, .. } = outcome else { panic!("{outcome:?}") };
|
||||
assert_eq!((locked, wanted), (12 * PAGE, 16 * PAGE), "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 12 * PAGE);
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 16 * PAGE);
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
//! * [`Level::Normal`]: caches grow under their budgets.
|
||||
//! * [`Level::Shed`]: the caches stop admitting and give memory back (prefix cache evicted, conversation checkpoints
|
||||
//! dropped); requests are still served.
|
||||
//! * [`Level::Reject`]: new requests are refused with 503 `memory_pressure` and `Retry-After`; everything sheddable is
|
||||
//! shed.
|
||||
//! * [`Level::Reject`]: new requests are refused with 503 `memory_pressure` and `Retry-After`; everything sheddable
|
||||
//! is shed.
|
||||
//!
|
||||
//! Unknown telemetry never reads as "plenty": a missing `MemAvailable` holds the level at `Shed`.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! single files (`/proc/self/smaps`) through the same object.
|
||||
//!
|
||||
//! * [`ProcPressure`] is the adapter for production: `/proc` and `/sys` on Linux, the Win32 text renderings of
|
||||
//! `winproc.rs` on Windows, parsed by [`HostFacts::probe`] exactly as before.
|
||||
//! `winproc.rs` served by `leleka-memory-os` on Windows, parsed by [`HostFacts::probe`] exactly as before.
|
||||
//! * [`ScriptedPressure`] is the fixture: a list of readings handed out one per probe, the last one repeating, so a
|
||||
//! test can play a rising, falling or flapping host without touching the real one.
|
||||
use crate::host::{FakeProc, HostFacts, ProcSource};
|
||||
@@ -26,6 +26,9 @@ impl<T: ProcSource + ?Sized> ProcSource for std::sync::Arc<T> {
|
||||
fn count_entries(&self, path: &str) -> io::Result<usize> {
|
||||
(**self).count_entries(path)
|
||||
}
|
||||
fn trim_working_set(&self) -> bool {
|
||||
(**self).trim_working_set()
|
||||
}
|
||||
}
|
||||
|
||||
/// The real host, read through a [`ProcSource`] (`RealProc` in production).
|
||||
@@ -39,6 +42,9 @@ impl<S: ProcSource> ProcSource for ProcPressure<S> {
|
||||
fn count_entries(&self, path: &str) -> io::Result<usize> {
|
||||
self.0.count_entries(path)
|
||||
}
|
||||
fn trim_working_set(&self) -> bool {
|
||||
self.0.trim_working_set()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: ProcSource + Send + Sync> MemoryPressure for ProcPressure<S> {
|
||||
|
||||
@@ -5,10 +5,7 @@
|
||||
//!
|
||||
//! The serve loop calls the `record_*` functions (a mutex-guarded struct, no allocation); one sampler thread reads
|
||||
//! `/proc` once a second and publishes. Everything that parses or computes is a pure function over fixtures.
|
||||
use crate::{
|
||||
host::{ProcSource, RealProc},
|
||||
procfs,
|
||||
};
|
||||
use crate::{host::ProcSource, procfs};
|
||||
use leleka_obs::time::{Clock, SystemClock};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
|
||||
@@ -138,41 +138,59 @@ impl Drop for Sampler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU
|
||||
/// block.
|
||||
pub fn start(gpu_probe: Option<GpuProbe>, period: Duration) -> Sampler {
|
||||
start_with_clock(gpu_probe, period, SystemClock)
|
||||
/// Start the once-a-second sampler over `host` (the real `/proc`, or the Win32 renderings on Windows). `gpu_probe`
|
||||
/// reads the device (NVML); `None` reports no GPU block.
|
||||
pub fn start(gpu_probe: Option<GpuProbe>, period: Duration, host: impl ProcSource + Send + 'static) -> Sampler {
|
||||
start_with_clock(gpu_probe, period, SystemClock, host)
|
||||
}
|
||||
|
||||
/// [`start`] with the monotonic readings of every tick taken from `clock`.
|
||||
pub fn start_with_clock(gpu_probe: Option<GpuProbe>, period: Duration, clock: impl Clock + Send + 'static) -> Sampler {
|
||||
pub fn start_with_clock(
|
||||
gpu_probe: Option<GpuProbe>,
|
||||
period: Duration,
|
||||
clock: impl Clock + Send + 'static,
|
||||
host: impl ProcSource + Send + 'static,
|
||||
) -> Sampler {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("leleka-telemetry".into())
|
||||
.spawn(move || sample_until_stopped(&flag, gpu_probe, period, &clock));
|
||||
.spawn(move || sample_until_stopped(&flag, gpu_probe, period, (&clock, &host)));
|
||||
if spawned.is_err() {
|
||||
stop.store(true, Ordering::Release);
|
||||
}
|
||||
Sampler { stop }
|
||||
}
|
||||
|
||||
fn sample_until_stopped(flag: &AtomicBool, gpu_probe: Option<GpuProbe>, period: Duration, clock: &impl Clock) {
|
||||
let src = RealProc;
|
||||
/// Cores worth of CPU and system busy percentage since the previous reading; the new reading replaces it.
|
||||
fn cpu_since_previous(
|
||||
previous: &mut Option<(CpuReading, Instant)>,
|
||||
reading: Option<CpuReading>,
|
||||
now: Instant,
|
||||
) -> Option<(f64, f64)> {
|
||||
let usage = match (&*previous, &reading) {
|
||||
(Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(reading) = reading {
|
||||
*previous = Some((reading, now));
|
||||
}
|
||||
usage
|
||||
}
|
||||
|
||||
fn sample_until_stopped(
|
||||
flag: &AtomicBool,
|
||||
gpu_probe: Option<GpuProbe>,
|
||||
period: Duration,
|
||||
(clock, src): (&impl Clock, &impl ProcSource),
|
||||
) {
|
||||
let began = clock.now();
|
||||
let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32);
|
||||
let mut previous = read_cpu(&src).map(|reading| (reading, clock.now()));
|
||||
let mut previous = read_cpu(src).map(|reading| (reading, clock.now()));
|
||||
while !flag.load(Ordering::Acquire) {
|
||||
std::thread::sleep(period);
|
||||
let now = clock.now();
|
||||
let reading = read_cpu(&src);
|
||||
let cpu = match (&previous, &reading) {
|
||||
(Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(reading) = reading {
|
||||
previous = Some((reading, now));
|
||||
}
|
||||
let cpu = cpu_since_previous(&mut previous, read_cpu(src), now);
|
||||
let measured = Measured {
|
||||
at: now,
|
||||
now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64),
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Windows host facts rendered as the `/proc` text the governor already parses.
|
||||
//!
|
||||
//! The governor reads the host through [`crate::host::ProcSource`], a map from `/proc/...` paths to text. On Windows
|
||||
//! `RealProc` answers the handful of paths below from Win32 (`GlobalMemoryStatusEx`, `GetProcessMemoryInfo`,
|
||||
//! the adapter answers the handful of paths below from Win32 (`GlobalMemoryStatusEx`, `GetProcessMemoryInfo`,
|
||||
//! `GetProcessTimes`, `GetSystemTimes`) so that every parser, policy and report stays the one that runs on Linux.
|
||||
//!
|
||||
//! The formatters are pure and tested on every platform; only [`read`] (the Win32 calls) is Windows-only.
|
||||
//! The formatters are pure and tested on every platform; the Win32 calls that feed them live in the adapter crate
|
||||
//! `leleka-memory-os` (`windows_host.rs`), so this crate links no operating-system API.
|
||||
//! Fields Windows cannot answer (`Threads`, `VmLck`, `VmPin`, cgroups, PSI, `/proc/vmstat`) are left out, which the
|
||||
//! parsers read as "unknown" and the governor fails closed on, exactly as for a kernel without that file.
|
||||
//!
|
||||
@@ -95,122 +96,6 @@ pub fn ticks_of_100ns(units: u64) -> u64 {
|
||||
units / 100_000
|
||||
}
|
||||
|
||||
/// The text for `path`, or `None` when Windows has nothing to say (the caller reports NotFound).
|
||||
#[cfg(windows)]
|
||||
pub fn read(path: &str) -> Option<String> {
|
||||
match path {
|
||||
"/proc/meminfo" => system_memory().map(|m| meminfo_text(&m)),
|
||||
"/proc/self/status" => process_memory().map(|p| status_text(&p)),
|
||||
"/proc/self/limits" => Some(limits_text()),
|
||||
"/proc/self/stat" => process_times().map(|(user, kernel)| self_stat_text(user, kernel)),
|
||||
"/proc/stat" => system_times().map(|(idle, kernel, user)| stat_text(idle, kernel, user)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Trim this process's working set (Windows only; `false` elsewhere or on failure). Windows counts the mapped pages a
|
||||
/// process still has in its working set as in use, so a file-mapped expert bank that was touched looks like pressure to
|
||||
/// the governor although the OS could reclaim it.
|
||||
pub fn trim_working_set() -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
win32::trim_working_set()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
mod win32 {
|
||||
use super::{ProcessMemory, SystemMemory, ticks_of_100ns};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::FILETIME,
|
||||
System::{
|
||||
ProcessStatus::{EmptyWorkingSet, GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
|
||||
SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX},
|
||||
Threading::{GetCurrentProcess, GetProcessTimes, GetSystemTimes},
|
||||
},
|
||||
};
|
||||
|
||||
fn filetime(t: &FILETIME) -> u64 {
|
||||
(u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime)
|
||||
}
|
||||
|
||||
pub fn system_memory() -> Option<SystemMemory> {
|
||||
let mut s = MEMORYSTATUSEX {
|
||||
dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
|
||||
dwMemoryLoad: 0,
|
||||
ullTotalPhys: 0,
|
||||
ullAvailPhys: 0,
|
||||
ullTotalPageFile: 0,
|
||||
ullAvailPageFile: 0,
|
||||
ullTotalVirtual: 0,
|
||||
ullAvailVirtual: 0,
|
||||
ullAvailExtendedVirtual: 0,
|
||||
};
|
||||
// SAFETY: a writable MEMORYSTATUSEX with dwLength set, as the API requires.
|
||||
if unsafe { GlobalMemoryStatusEx(&mut s) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(SystemMemory {
|
||||
total_phys: s.ullTotalPhys,
|
||||
avail_phys: s.ullAvailPhys,
|
||||
total_commit: s.ullTotalPageFile,
|
||||
avail_commit: s.ullAvailPageFile,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn process_memory() -> Option<ProcessMemory> {
|
||||
// SAFETY: an all-zero PROCESS_MEMORY_COUNTERS is a valid value (plain integers).
|
||||
let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
|
||||
c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
|
||||
// SAFETY: the pseudo handle of the current process is always valid; `c` is writable and `cb` is its size.
|
||||
if unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(ProcessMemory {
|
||||
working_set: c.WorkingSetSize as u64,
|
||||
peak_working_set: c.PeakWorkingSetSize as u64,
|
||||
private_commit: c.PagefileUsage as u64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its
|
||||
/// working set to the standby list: they stay cached, count as available again and come back with a soft fault.
|
||||
pub fn trim_working_set() -> bool {
|
||||
// SAFETY: the pseudo handle of the current process is always valid.
|
||||
unsafe { EmptyWorkingSet(GetCurrentProcess()) != 0 }
|
||||
}
|
||||
|
||||
/// (user, kernel) ticks of this process.
|
||||
pub fn process_times() -> Option<(u64, u64)> {
|
||||
let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
|
||||
let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
|
||||
// SAFETY: the current-process pseudo handle and four writable FILETIMEs.
|
||||
if unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((ticks_of_100ns(filetime(&user)), ticks_of_100ns(filetime(&kernel))))
|
||||
}
|
||||
|
||||
/// (idle, kernel including idle, user) ticks of the whole system.
|
||||
pub fn system_times() -> Option<(u64, u64, u64)> {
|
||||
let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
|
||||
let (mut idle, mut kernel, mut user) = (zero, zero, zero);
|
||||
// SAFETY: three writable FILETIMEs.
|
||||
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((ticks_of_100ns(filetime(&idle)), ticks_of_100ns(filetime(&kernel)), ticks_of_100ns(filetime(&user))))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
use win32::{process_memory, process_times, system_memory, system_times};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -263,16 +148,4 @@ mod tests {
|
||||
assert_eq!(telemetry::parse_stat_cpu(&stat_text(900, 1000, 400)), Some((500, 1400)));
|
||||
assert_eq!(ticks_of_100ns(10_000_000), 100);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_win32_readers_answer_plausible_numbers() {
|
||||
let info = procfs::parse_meminfo(&read("/proc/meminfo").unwrap());
|
||||
assert!(info.mem_total.unwrap() > GIB && info.mem_available.unwrap() <= info.mem_total.unwrap());
|
||||
let status = procfs::parse_status(&read("/proc/self/status").unwrap());
|
||||
assert!(status.vm_rss.unwrap() > 0);
|
||||
assert!(telemetry::parse_self_stat_ticks(&read("/proc/self/stat").unwrap()).is_some());
|
||||
assert!(telemetry::parse_stat_cpu(&read("/proc/stat").unwrap()).is_some());
|
||||
assert!(read("/proc/vmstat").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "leleka-memory-os"
|
||||
version = "0.1.0"
|
||||
description = "Operating-system adapters of the memory governor (page locking, glibc heap, Win32 host facts); the pure policy is leleka-memory"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
leleka-memory = { path = "../leleka-memory" }
|
||||
leleka-obs = { path = "../obs" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
|
||||
libc = "=0.2.190"
|
||||
|
||||
# Windows: the memory facts come from Win32 (GlobalMemoryStatusEx, GetProcessMemoryInfo, GetSystemTimes) and are rendered
|
||||
# in the /proc text formats the governor already parses (`leleka_memory::winproc`).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_SystemInformation", "Win32_System_ProcessStatus", "Win32_System_Threading"] }
|
||||
|
||||
# Unsafe is the point of this crate (system calls on addresses that are never dereferenced); every block carries a SAFETY
|
||||
# comment. The pure policy that decides when to call them is in leleka-memory, which denies unsafe code.
|
||||
[lints.rust]
|
||||
unsafe_code = "allow"
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
all = "warn"
|
||||
@@ -15,6 +15,8 @@ use leleka_memory::lock::LockMode;
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
use leleka_memory::{Governor, GovernorConfig, Policy};
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
use leleka_memory_os::real_governor;
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
use std::os::fd::{AsFd, FromRawFd, OwnedFd};
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
use std::sync::Arc;
|
||||
@@ -74,7 +76,7 @@ fn open_governor(lock: LockMode, heal: bool) -> Governor {
|
||||
cfg.residency_every_ms = 1000;
|
||||
cfg.sample_interval_ms = 500;
|
||||
let _ = Policy::for_host(0, false);
|
||||
Governor::real(cfg)
|
||||
real_governor(cfg)
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
@@ -0,0 +1,3 @@
|
||||
# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line.
|
||||
max_width = 120
|
||||
use_small_heuristics = "Max"
|
||||
@@ -6,6 +6,7 @@
|
||||
//! is called after an eviction. On other allocators or platforms it does nothing.
|
||||
|
||||
/// `LELEKA_MEMORY_NO_TRIM=1` turns `trim` into a no-op (for the A/B of what the trim buys).
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))]
|
||||
fn trim_disabled() -> bool {
|
||||
static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*OFF.get_or_init(|| std::env::var("LELEKA_MEMORY_NO_TRIM").is_ok_and(|v| v == "1"))
|
||||
@@ -0,0 +1,45 @@
|
||||
//! The operating-system side of `leleka-memory` (STRA-338): everything that calls `libc` or Win32.
|
||||
//!
|
||||
//! `leleka-memory` decides (plans, levels, sheds, lock decisions) and stays free of OS crates; this crate implements
|
||||
//! the ports it defines:
|
||||
//!
|
||||
//! * [`LinuxPageLocking`] is `leleka_memory::lock::PageLocking` over `mmap`, `mlock`, `mincore` and `madvise`;
|
||||
//! * [`WindowsProc`] is `leleka_memory::ProcSource` over Win32, rendered in the `/proc` text formats;
|
||||
//! * [`heap`] gives freed glibc heap pages back to the kernel and reads allocator totals.
|
||||
//!
|
||||
//! The composition roots (`leleka-engine-qwen35-cuda`, `leleka-deploy`) build the governor from these.
|
||||
|
||||
pub mod heap;
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
mod linux_page_locking;
|
||||
#[cfg(windows)]
|
||||
mod windows_host;
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
pub use linux_page_locking::LinuxPageLocking;
|
||||
#[cfg(windows)]
|
||||
pub use windows_host::WindowsProc;
|
||||
|
||||
/// The real host as a [`leleka_memory::ProcSource`]: Win32 facts on Windows, the `/proc` and `/sys` files elsewhere.
|
||||
#[cfg(windows)]
|
||||
pub type HostProc = WindowsProc;
|
||||
/// The real host as a [`leleka_memory::ProcSource`]: Win32 facts on Windows, the `/proc` and `/sys` files elsewhere.
|
||||
#[cfg(not(windows))]
|
||||
pub type HostProc = leleka_memory::RealProc;
|
||||
|
||||
/// A governor over the real host: the host facts of this platform and, on 64-bit Linux, the page-locking adapter of the
|
||||
/// archive guard.
|
||||
pub fn real_governor(cfg: leleka_memory::GovernorConfig) -> leleka_memory::Governor {
|
||||
use leleka_memory::{Governor, ProcPressure};
|
||||
use leleka_obs::time::AnyClock;
|
||||
let pressure = ProcPressure(HostProc::default());
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
{
|
||||
Governor::with_page_locking(cfg, pressure, AnyClock::System, std::sync::Arc::new(LinuxPageLocking))
|
||||
}
|
||||
#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
|
||||
{
|
||||
Governor::with_parts(cfg, pressure, AnyClock::System)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! The Linux page-locking adapter: the system calls behind `leleka_memory::lock::PageLocking`.
|
||||
//!
|
||||
//! Every call takes an address and a length that `leleka_memory::lock::FdMapping` already checked against its live
|
||||
//! mapping (page aligned, inside the length). No address is ever dereferenced here: they only travel to `mlock`,
|
||||
//! `mincore`, `madvise` and `munmap`, so there is nothing to dangle, alias or fault on.
|
||||
|
||||
use leleka_memory::lock::PageLocking;
|
||||
use std::io;
|
||||
use std::os::fd::{AsRawFd, BorrowedFd};
|
||||
|
||||
/// `mmap`, `mlock`, `mincore`, `madvise` and `setrlimit` over a read-only shared mapping of a descriptor.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct LinuxPageLocking;
|
||||
|
||||
fn check(result: libc::c_int) -> io::Result<()> {
|
||||
if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
|
||||
}
|
||||
|
||||
impl PageLocking for LinuxPageLocking {
|
||||
fn map_readonly(&self, fd: BorrowedFd<'_>, len: usize) -> io::Result<usize> {
|
||||
// SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing
|
||||
// mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED.
|
||||
let addr =
|
||||
unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) };
|
||||
if addr == libc::MAP_FAILED {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(addr as usize)
|
||||
}
|
||||
|
||||
fn unmap(&self, address: usize, len: usize) {
|
||||
// SAFETY: the caller passes exactly what `map_readonly` returned and was given, once; nothing borrows the
|
||||
// mapping. munlock is implied by munmap.
|
||||
unsafe {
|
||||
libc::munmap(address as *mut libc::c_void, len);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self, address: usize, len: usize) -> io::Result<()> {
|
||||
// SAFETY: `address..address+len` lies inside a live mapping of the caller; mlock only faults and pins pages.
|
||||
check(unsafe { libc::mlock(address as *const libc::c_void, len) })
|
||||
}
|
||||
|
||||
fn unlock(&self, address: usize, len: usize) {
|
||||
// SAFETY: `address..address+len` lies inside a live mapping of the caller; munlock only unpins pages.
|
||||
let _ = unsafe { libc::munlock(address as *const libc::c_void, len) };
|
||||
}
|
||||
|
||||
fn resident_pages(&self, address: usize, len: usize, page_flags: &mut [u8]) -> io::Result<()> {
|
||||
// SAFETY: `address..address+len` lies inside a live mapping of the caller; `page_flags` has one byte per page
|
||||
// of the range (the caller sizes it).
|
||||
check(unsafe { libc::mincore(address as *mut libc::c_void, len, page_flags.as_mut_ptr()) })
|
||||
}
|
||||
|
||||
fn populate(&self, address: usize, len: usize) -> io::Result<()> {
|
||||
// SAFETY: `address..address+len` lies inside a live mapping of the caller; MADV_POPULATE_READ changes no
|
||||
// contents.
|
||||
check(unsafe { libc::madvise(address as *mut libc::c_void, len, libc::MADV_POPULATE_READ) })
|
||||
}
|
||||
|
||||
fn raise_memlock_soft(&self, to: u64) -> io::Result<()> {
|
||||
let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
|
||||
// SAFETY: `lim` is a valid, writable rlimit for the duration of the call.
|
||||
check(unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, &mut lim) })?;
|
||||
lim.rlim_cur = to.min(lim.rlim_max);
|
||||
// SAFETY: `lim` is a valid, initialized rlimit.
|
||||
check(unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &lim) })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(miri)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use leleka_memory::lock::{FdMapping, LockOutcome};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PAGE: u64 = 4096;
|
||||
|
||||
fn map_readonly(fd: BorrowedFd<'_>, len: usize) -> io::Result<FdMapping> {
|
||||
FdMapping::map_readonly(Arc::new(LinuxPageLocking), fd, len)
|
||||
}
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsFd;
|
||||
|
||||
fn file(len: usize) -> std::fs::File {
|
||||
let mut f = tempfile_in_target();
|
||||
f.write_all(&vec![7u8; len]).unwrap();
|
||||
f.flush().unwrap();
|
||||
f
|
||||
}
|
||||
fn tempfile_in_target() -> std::fs::File {
|
||||
// an unlinked file under the system temp dir
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"leleka-memory-lock-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_locks_inside_the_limit_and_reports_incore() {
|
||||
let f = file(64 * 4096);
|
||||
let mut m = map_readonly(f.as_fd(), 64 * 4096).unwrap();
|
||||
assert_eq!(m.len(), 64 * 4096);
|
||||
let mut asked = Vec::new();
|
||||
let outcome = m.lock(16 * 4096, |n| {
|
||||
asked.push(n);
|
||||
true
|
||||
});
|
||||
// 64 pages = 256 KiB: inside any RLIMIT_MEMLOCK of 8 MiB
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 64 * 4096 }, "{outcome:?}");
|
||||
assert_eq!(asked, vec![16 * 4096; 4]);
|
||||
let pages = m.incore(0, 64 * 4096).unwrap();
|
||||
assert_eq!(pages.len(), 64);
|
||||
assert!(pages.iter().all(|&p| p));
|
||||
m.populate(0, 64 * 4096).unwrap();
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guard_stops_the_lock_between_chunks() {
|
||||
let f = file(32 * 4096);
|
||||
let mut m = map_readonly(f.as_fd(), 32 * 4096).unwrap();
|
||||
let mut calls = 0;
|
||||
let outcome = m.lock(8 * 4096, |_| {
|
||||
calls += 1;
|
||||
calls <= 2
|
||||
});
|
||||
assert!(matches!(outcome, LockOutcome::Partial { locked, .. } if locked == 16 * 4096), "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 16 * 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_outside_the_mapping_or_unaligned_are_refused_before_any_syscall() {
|
||||
let f = file(8 * 4096);
|
||||
let m = map_readonly(f.as_fd(), 8 * 4096).unwrap();
|
||||
assert!(m.incore(4096, 8 * 4096).is_err());
|
||||
assert!(m.incore(1, 4096).is_err());
|
||||
assert!(m.populate(0, 0).is_err());
|
||||
assert!(m.populate(u64::MAX - 100, 4096).is_err());
|
||||
assert!(m.incore(0, 8 * 4096).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_mapping_is_refused() {
|
||||
let f = file(4096);
|
||||
assert!(map_readonly(f.as_fd(), 0).is_err());
|
||||
}
|
||||
|
||||
/// An anonymous memfd of `pages` pages with data in the page ranges `data` (everything else is a hole).
|
||||
fn sparse_memfd(pages: u64, data: &[(u64, u64)]) -> std::fs::File {
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::unix::fs::FileExt;
|
||||
// SAFETY: memfd_create returns a fresh descriptor that nothing else owns; File takes ownership of it.
|
||||
let f = unsafe {
|
||||
let fd = libc::memfd_create(c"leleka-lock-test".as_ptr(), 0);
|
||||
assert!(fd >= 0, "memfd_create: {}", io::Error::last_os_error());
|
||||
std::fs::File::from_raw_fd(fd)
|
||||
};
|
||||
f.set_len(pages * PAGE).unwrap();
|
||||
for &(first, count) in data {
|
||||
for page in first..first + count {
|
||||
f.write_all_at(&vec![0xA5u8; PAGE as usize], page * PAGE).unwrap();
|
||||
}
|
||||
}
|
||||
f
|
||||
}
|
||||
fn allocated(f: &std::fs::File) -> u64 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
f.metadata().unwrap().blocks() * 512
|
||||
}
|
||||
fn pages_to_spans(ranges: &[(u64, u64)]) -> Vec<(u64, u64)> {
|
||||
ranges.iter().map(|&(first, count)| (first * PAGE, count * PAGE)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locking_and_populating_the_extents_of_a_sparse_memfd_allocates_nothing_in_the_holes() {
|
||||
let data = [(10u64, 4u64), (100, 6)];
|
||||
let spans = pages_to_spans(&data);
|
||||
let f = sparse_memfd(256, &data);
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "only the pages written exist");
|
||||
let mut m = map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap();
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "mapping a sparse file allocates nothing");
|
||||
let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| true);
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 10 * PAGE }, "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 10 * PAGE);
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "locking the extents instantiated no hole");
|
||||
for &(offset, n) in &spans {
|
||||
m.populate(offset, n).unwrap();
|
||||
}
|
||||
assert_eq!(allocated(&f), 10 * PAGE, "populating the extents instantiated no hole");
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 10 * PAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() {
|
||||
// the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be
|
||||
// needed
|
||||
let f = sparse_memfd(256, &[(10, 4), (100, 6)]);
|
||||
let mut m = map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap();
|
||||
let outcome = m.lock(64 * PAGE, |_| true);
|
||||
assert_eq!(outcome, LockOutcome::Locked { bytes: 256 * PAGE }, "{outcome:?}");
|
||||
assert_eq!(allocated(&f), 256 * PAGE, "mlock of a shmem hole allocates a zero page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_ranges_refuses_spans_that_are_unaligned_overlapping_unsorted_or_outside_before_any_syscall() {
|
||||
let f = sparse_memfd(16, &[(0, 2)]);
|
||||
let mut m = map_readonly(f.as_fd(), (16 * PAGE) as usize).unwrap();
|
||||
for bad in [
|
||||
vec![(1, PAGE)],
|
||||
vec![(0, 2 * PAGE), (PAGE, PAGE)],
|
||||
vec![(4 * PAGE, PAGE), (0, PAGE)],
|
||||
vec![(15 * PAGE, 2 * PAGE)],
|
||||
vec![(0, 0)],
|
||||
] {
|
||||
let outcome = m.lock_ranges(&bad, PAGE, |_| panic!("the guard must not be consulted for an invalid span"));
|
||||
assert!(matches!(outcome, LockOutcome::Partial { locked: 0, .. }), "{bad:?}: {outcome:?}");
|
||||
}
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 2 * PAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guard_can_stop_a_ranged_lock_between_chunks_and_unlock_releases_what_was_locked() {
|
||||
let f = sparse_memfd(64, &[(0, 8), (32, 8)]);
|
||||
let mut m = map_readonly(f.as_fd(), (64 * PAGE) as usize).unwrap();
|
||||
let spans = pages_to_spans(&[(0, 8), (32, 8)]);
|
||||
let mut calls = 0;
|
||||
let outcome = m.lock_ranges(&spans, 4 * PAGE, |_| {
|
||||
calls += 1;
|
||||
calls <= 3
|
||||
});
|
||||
let LockOutcome::Partial { locked, wanted, .. } = outcome else { panic!("{outcome:?}") };
|
||||
assert_eq!((locked, wanted), (12 * PAGE, 16 * PAGE), "{outcome:?}");
|
||||
assert_eq!(m.locked_bytes(), 12 * PAGE);
|
||||
m.unlock();
|
||||
assert_eq!(m.locked_bytes(), 0);
|
||||
assert_eq!(allocated(&f), 16 * PAGE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Windows host facts for the memory governor: Win32 answers rendered as the `/proc` text the governor parses.
|
||||
//!
|
||||
//! `leleka_memory::winproc` holds the pure formatters (tested on every platform); this module makes the Win32 calls
|
||||
//! that feed them and implements the `ProcSource` port over them. Paths Windows cannot answer (`/proc/vmstat`, cgroups,
|
||||
//! PSI) report NotFound, which the parsers read as "unknown" and the governor fails closed on.
|
||||
|
||||
use leleka_memory::ProcSource;
|
||||
use leleka_memory::winproc::{limits_text, meminfo_text, self_stat_text, stat_text, status_text};
|
||||
use std::io;
|
||||
|
||||
/// The Windows host: [`ProcSource`] answered from Win32.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct WindowsProc;
|
||||
|
||||
/// The text for `path`, or `None` when Windows has nothing to say (the caller reports NotFound).
|
||||
fn read_text(path: &str) -> Option<String> {
|
||||
match path {
|
||||
"/proc/meminfo" => win32::system_memory().map(|m| meminfo_text(&m)),
|
||||
"/proc/self/status" => win32::process_memory().map(|p| status_text(&p)),
|
||||
"/proc/self/limits" => Some(limits_text()),
|
||||
"/proc/self/stat" => win32::process_times().map(|(user, kernel)| self_stat_text(user, kernel)),
|
||||
"/proc/stat" => win32::system_times().map(|(idle, kernel, user)| stat_text(idle, kernel, user)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl ProcSource for WindowsProc {
|
||||
fn read(&self, path: &str) -> io::Result<String> {
|
||||
read_text(path).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, path.to_owned()))
|
||||
}
|
||||
fn count_entries(&self, path: &str) -> io::Result<usize> {
|
||||
Err(io::Error::new(io::ErrorKind::NotFound, path.to_owned()))
|
||||
}
|
||||
/// Windows counts the mapped pages a process still has in its working set as in use, so a file-mapped expert bank
|
||||
/// that was touched looks like pressure to the governor although the OS could reclaim it.
|
||||
fn trim_working_set(&self) -> bool {
|
||||
win32::trim_working_set()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
mod win32 {
|
||||
use leleka_memory::winproc::{ProcessMemory, SystemMemory, ticks_of_100ns};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::FILETIME,
|
||||
System::{
|
||||
ProcessStatus::{EmptyWorkingSet, GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
|
||||
SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX},
|
||||
Threading::{GetCurrentProcess, GetProcessTimes, GetSystemTimes},
|
||||
},
|
||||
};
|
||||
|
||||
fn filetime(t: &FILETIME) -> u64 {
|
||||
(u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime)
|
||||
}
|
||||
|
||||
pub fn system_memory() -> Option<SystemMemory> {
|
||||
let mut s = MEMORYSTATUSEX {
|
||||
dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
|
||||
dwMemoryLoad: 0,
|
||||
ullTotalPhys: 0,
|
||||
ullAvailPhys: 0,
|
||||
ullTotalPageFile: 0,
|
||||
ullAvailPageFile: 0,
|
||||
ullTotalVirtual: 0,
|
||||
ullAvailVirtual: 0,
|
||||
ullAvailExtendedVirtual: 0,
|
||||
};
|
||||
// SAFETY: a writable MEMORYSTATUSEX with dwLength set, as the API requires.
|
||||
if unsafe { GlobalMemoryStatusEx(&mut s) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(SystemMemory {
|
||||
total_phys: s.ullTotalPhys,
|
||||
avail_phys: s.ullAvailPhys,
|
||||
total_commit: s.ullTotalPageFile,
|
||||
avail_commit: s.ullAvailPageFile,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn process_memory() -> Option<ProcessMemory> {
|
||||
// SAFETY: an all-zero PROCESS_MEMORY_COUNTERS is a valid value (plain integers).
|
||||
let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
|
||||
c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
|
||||
// SAFETY: the pseudo handle of the current process is always valid; `c` is writable and `cb` is its size.
|
||||
if unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(ProcessMemory {
|
||||
working_set: c.WorkingSetSize as u64,
|
||||
peak_working_set: c.PeakWorkingSetSize as u64,
|
||||
private_commit: c.PagefileUsage as u64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its
|
||||
/// working set to the standby list: they stay cached, count as available again and come back with a soft fault.
|
||||
pub fn trim_working_set() -> bool {
|
||||
// SAFETY: the pseudo handle of the current process is always valid.
|
||||
unsafe { EmptyWorkingSet(GetCurrentProcess()) != 0 }
|
||||
}
|
||||
|
||||
/// (user, kernel) ticks of this process.
|
||||
pub fn process_times() -> Option<(u64, u64)> {
|
||||
let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
|
||||
let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
|
||||
// SAFETY: the current-process pseudo handle and four writable FILETIMEs.
|
||||
if unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((ticks_of_100ns(filetime(&user)), ticks_of_100ns(filetime(&kernel))))
|
||||
}
|
||||
|
||||
/// (idle, kernel including idle, user) ticks of the whole system.
|
||||
pub fn system_times() -> Option<(u64, u64, u64)> {
|
||||
let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
|
||||
let (mut idle, mut kernel, mut user) = (zero, zero, zero);
|
||||
// SAFETY: three writable FILETIMEs.
|
||||
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((ticks_of_100ns(filetime(&idle)), ticks_of_100ns(filetime(&kernel)), ticks_of_100ns(filetime(&user))))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use leleka_memory::{procfs, telemetry};
|
||||
|
||||
const GIB: u64 = 1 << 30;
|
||||
|
||||
#[test]
|
||||
fn the_win32_readers_answer_plausible_numbers() {
|
||||
let host = WindowsProc;
|
||||
let info = procfs::parse_meminfo(&host.read("/proc/meminfo").unwrap());
|
||||
assert!(info.mem_total.unwrap() > GIB && info.mem_available.unwrap() <= info.mem_total.unwrap());
|
||||
let status = procfs::parse_status(&host.read("/proc/self/status").unwrap());
|
||||
assert!(status.vm_rss.unwrap() > 0);
|
||||
assert!(telemetry::parse_self_stat_ticks(&host.read("/proc/self/stat").unwrap()).is_some());
|
||||
assert!(telemetry::parse_stat_cpu(&host.read("/proc/stat").unwrap()).is_some());
|
||||
assert!(host.read("/proc/vmstat").is_err());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -4,6 +4,7 @@
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use leleka_memory::{Governor, GovernorConfig, governor::LockReport, lock::LockOutcome};
|
||||
use leleka_memory_os::real_governor;
|
||||
use std::os::fd::{AsFd, FromRawFd};
|
||||
use std::os::unix::fs::{FileExt, MetadataExt};
|
||||
|
||||
@@ -34,7 +35,7 @@ fn governor() -> Governor {
|
||||
cfg.lock_mode = leleka_memory::lock::LockMode::Try;
|
||||
cfg.heal = true;
|
||||
cfg.log = false;
|
||||
Governor::real(cfg)
|
||||
real_governor(cfg)
|
||||
}
|
||||
|
||||
fn report(r: &Result<LockReport, leleka_memory::Refusal>) -> &LockReport {
|
||||
@@ -16,7 +16,7 @@ Inside L3 a crate may use another L3 crate only through an edge listed in `adapt
|
||||
| L0 contract | wire and trait contracts | `leleka-backend-api` (the `Backend` trait), `leleka-worker-protocol` |
|
||||
| L1 leaf libraries | pure or std-only libraries | `leleka-obs` (`Clock`), `leleka-memory` (`MemoryPressure`), `leleka-context`, `leleka-sampler-ref`, `leleka-quant-core`, `leleka-serving-policy`, `leleka-harmony`, `leleka-tokenizer`, `leleka-gguf`, `leleka-kar-codec`, `leleka-experimental-ref`, `leleka-cpu-sys`, `leleka-cpu-kernels`, `leleka-shm`, `leleka-openvino`, `leleka-gateway-text`, `leleka-cuda-model` (the pure host-side models peeled out of `leleka-cuda-driver`: `Error`, projection formats and geometries, serving context, schedules and kernel specifications) |
|
||||
| L2 domain | pure domain of one side | `leleka-engine-core` (prefix cache, conversation policy, prompt plan, speculative-decoding policies, request lifecycle, `EngineFamily`), `leleka-gateway-domain` (sampling, reasoning budget, codec, `OutputEvent` and the output decoders, Responses and Messages protocol) |
|
||||
| L3 adapters | OS, device, process and file access | engine: `leleka-engine-qwen35-cuda`, `leleka-engine-fake`, `leleka-cuda-driver`, `leleka-model-format` (`WeightSource`), `leleka-native-cpu-expert`, `leleka-libc-shim`; gpt-oss workers: `leleka-gptoss`, `leleka-gptoss-igpu`, `leleka-gptoss-npu`, `leleka-cpu-worker`, `leleka-igpu-worker`, `leleka-npu-worker`, `leleka-gpu-npu-worker`, `leleka-npu-service`, `leleka-igpu`; also `leleka-offline-tools`, `leleka-runtime-client` (gRPC client) |
|
||||
| L3 adapters | OS, device, process and file access | engine: `leleka-engine-qwen35-cuda`, `leleka-engine-fake`, `leleka-cuda-driver`, `leleka-model-format` (`WeightSource`), `leleka-native-cpu-expert`, `leleka-libc-shim`, `leleka-memory-os` (page locking, glibc heap and Win32 host facts for the memory governor); gpt-oss workers: `leleka-gptoss`, `leleka-gptoss-igpu`, `leleka-gptoss-npu`, `leleka-cpu-worker`, `leleka-igpu-worker`, `leleka-npu-worker`, `leleka-gpu-npu-worker`, `leleka-npu-service`, `leleka-igpu`; also `leleka-offline-tools`, `leleka-runtime-client` (gRPC client) |
|
||||
| L4 hosts | composition roots and facades | `leleka-runtime` (facade), `strata-desktop-core` (the `leleka-inference` binary), `strata-control` (gateway, binary `strata-next`), `leleka-deploy` (the `leleka` binary), `leleka-native-parity-bench` |
|
||||
|
||||
`leleka-runtime` is one line, `pub use leleka_engine_qwen35_cuda::*;` (S22), so the binaries keep importing `leleka_runtime::...`.
|
||||
@@ -89,7 +89,8 @@ is the composition root of the gateway process (`serve()` in `control-plane/src/
|
||||
|---|---|---|---|
|
||||
| Clock (engine) | `leleka_obs::time::Clock`; `SystemClock`, `ManualClock`, `AnyClock`, `Stopwatch<C>` (`crates/obs/src/time/clock.rs`) | generic (`C = SystemClock` by default); `AnyClock` is an enum for owners that cannot be generic | read at coarse points (request, decision, tick); hot loops take one reading and compare it |
|
||||
| Settings / EnvSource | `EnvSource`, `ProcessEnv`, `MapEnv`, `Settings` (`crates/engine-qwen35-cuda/src/settings/`, crate-private) | generic (`&impl EnvSource`) | the operator namespace is captured once; parsers are tested with `MapEnv` |
|
||||
| MemoryPressure | `leleka_memory::pressure_port::MemoryPressure`; `ProcPressure<S>`, `ScriptedPressure` | `Arc<dyn MemoryPressure>` inside `Governor` | read at sampler and admission cadence, never per token |
|
||||
| MemoryPressure | `leleka_memory::pressure_port::MemoryPressure`; `ProcPressure<S>`, `ScriptedPressure`; Windows adapter `leleka_memory_os::WindowsProc` | `Arc<dyn MemoryPressure>` inside `Governor` | read at sampler and admission cadence, never per token |
|
||||
| PageLocking | `leleka_memory::lock::PageLocking` (`mmap`, `mlock`, `mincore`, `madvise`, `munmap`, `setrlimit` on plain addresses); adapter `leleka_memory_os::LinuxPageLocking`; `leleka_memory_os::real_governor(cfg)` is the composition | `SharedPageLocking` (`Arc<dyn PageLocking>`) held by `Governor` and `FdMapping` | called at archive guard time (startup lock, residency tick, heal), never per token; `leleka-memory` has no `libc` and no unsafe |
|
||||
| WeightSource | `leleka_model_format::weight_source::WeightSource`; file, shard, resident-tensor and KAR adapters, an in-memory double | generic (`S: WeightSource + ?Sized`) | opened once per load; no method returns an owning copy of the bytes |
|
||||
| ServeDevice | `ServeDevice` (`crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs`, crate-private), implemented by `OriginalServeStack` | generic (`&mut impl ServeDevice`) | one call per request; tests drive the real `generate` over a scripted device |
|
||||
| Lifecycle / run_request | `leleka_engine_core::request::{Lifecycle, run_request, ServeError<E>, admit}` | generic, no trait object | admission, reset or resume, prefill, decode, finish: the order and the failure classes run over any owners |
|
||||
@@ -156,7 +157,7 @@ chooses by its own logic, and a second family adds a second arm there.
|
||||
| size ratchet | no `.rs` file over 400 lines; a file already over may not grow past its baseline entry; a shrunk file is reported stale | `max_lines`, baseline `oversize` |
|
||||
| mechanical file names | no new `.rs` file named by a mechanical split: `impl_*.rs`, `*_fn.rs`, `*_<N>.rs` / `*_<N>_<M>.rs` (a name must say what the module is and what it is for); the baseline lists the existing 964 files (`mechanical_names`) and an entry goes away when the file is renamed; `scripts/dev/rustsplit` now names the modules it creates after what they hold (`foo`, `thing_methods`, `display_for_thing`, `thing_methods_from_<method>`) and disambiguates with a word (`_more`), never a number | `mechanical_names`, baseline `mechanical_names` |
|
||||
| source ratchets | per-crate counts of `env-read`, `instant-now`, `path-include`, `process-global`, `dyn-trait` over production code in `src/`; a count may only fall | `source_patterns`, baseline `source` |
|
||||
| baselined violations | the two known `leleka-memory` dependencies (`libc`, `windows-sys`) | baseline `violations` |
|
||||
| baselined violations | none: the two `leleka-memory` dependencies (`libc`, `windows-sys`) were removed on 2026-11-13 by the `PageLocking` port and the `leleka-memory-os` adapter | baseline `violations` |
|
||||
|
||||
Commands: `python scripts/check-architecture.py` (0 errors expected), `--report` (layer graph, oversize census, ratchets), `--update-baseline`
|
||||
(lowers numbers, refuses to raise one), `--update-baseline --allow-increase` (raising needs a reason in review). Test-only modules (a `mod x;`
|
||||
|
||||
@@ -11,6 +11,25 @@ Crate names after S22: the sections below that say `leleka-runtime` describe cod
|
||||
`backend/` and `settings/` are relative to the new crate, and the ratchet keys read `...:leleka-engine-qwen35-cuda`. The layers, the ports and the
|
||||
numbers after S22 are on `docs/architecture/hexagonal.md`; the S19 to S22 section below says what the engine recut moved and what it left.
|
||||
|
||||
## Debt register of the architecture rework (owner request 2026-11-13)
|
||||
|
||||
The three debts the rework still carried, each with the state it was left in. Numbers are from `scripts/check-architecture.py`.
|
||||
|
||||
### (a) Pure layer using OS crates: 2 violations -> 0 (done)
|
||||
|
||||
`leleka-memory` (L1) depended on `libc` and `windows-sys`. It now owns the ports and no OS crate: `lock::PageLocking`
|
||||
(`mmap`/`mlock`/`mincore`/`madvise`/`munmap`/`setrlimit` over plain integer addresses, `SharedPageLocking` = `Arc<dyn PageLocking>`),
|
||||
`ProcSource::trim_working_set` (Windows working-set trim, default `false`) and the pure `winproc` text formatters; `FdMapping` keeps the
|
||||
bounds checks and lock bookkeeping, now safe Rust. The adapter is the new L3 crate `crates/memory-os` (`leleka-memory-os`): `LinuxPageLocking`,
|
||||
`WindowsProc` (Win32 facts as `/proc` text), `heap` (glibc `mallinfo2`/`malloc_trim`, moved verbatim with its `LELEKA_MEMORY_NO_TRIM` read),
|
||||
`HostProc` (the real host of this platform) and `real_governor(cfg)`, which the engine's `memory_governor::install` calls instead of
|
||||
`Governor::real` (removed: it had no page-locking adapter). `Governor::with_page_locking` is the composition point; without an adapter the archive
|
||||
guard reports `NotAttempted` exactly as a failed `mmap` does. `telemetry::start` takes the host as its third argument. The sparse-archive test and the
|
||||
`swap_ab` example moved to `memory-os` with the code they exercise. Behaviour is unchanged: same calls, same order, same messages (the `mlock: ...`
|
||||
text is built from the same `io::Error`); the page-locking calls are per archive guard and heal tick, not per token. `leleka-memory` is edge-free of `unsafe`
|
||||
(`lock` no longer opts in) and runs under Miri in full. Gate: `forbidden-dep` entries gone from `architecture-baseline.json`; `leleka-memory-os` is in
|
||||
`ci-coverage.json` and the product test and Clippy lists.
|
||||
|
||||
## crates/engine-qwen35-cuda `backend/` (formerly leleka-runtime; STRA-338 S5a, S5b)
|
||||
|
||||
`backend.rs` (3797 lines) is a parent of 258 lines plus responsibility-named children. `serve_load` is decomposed
|
||||
|
||||
@@ -292,7 +292,7 @@ cargo test -p leleka-engine-qwen35-cuda --lib original_serve_stack::prefix # s
|
||||
cargo test -p leleka-deploy # profiles carry the memory section
|
||||
|
||||
# swap A/B under real pressure, fenced into one cgroup (root; WSL2 or a test box)
|
||||
cargo build --release -p leleka-memory --example swap_ab
|
||||
cargo build --release -p leleka-memory-os --example swap_ab
|
||||
sudo ARMS="A B C" HOG_RELEASE=20 SWAP_AB_BIN=target/release/examples/swap_ab scripts/memory/swap_ab.sh \
|
||||
--memfd-mib 6144 --hog-mib 5120 --limit-mib 9216 --secs 60 --reader /path/to/a/12GiB/file
|
||||
|
||||
|
||||
@@ -167,7 +167,7 @@ product_path() {
|
||||
local host_tests=(dry_run_prints_the_plan_and_changes_nothing a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it)
|
||||
PATH="${smi_path}" gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-deploy --features test-fakes -- --skip "${host_tests[0]}" --skip "${host_tests[1]}"
|
||||
PATH="${smi_path}" gate debt cargo test "${manifest[@]}" -p leleka-deploy --features test-fakes --test e2e -- "${host_tests[@]}"
|
||||
gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-memory -p leleka-runtime-client -p leleka-gateway-text -p leleka-gateway-domain -p leleka-worker-protocol -p leleka-engine-core -p leleka-engine-fake -p strata-control -p strata-desktop-core
|
||||
gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-memory -p leleka-memory-os -p leleka-runtime-client -p leleka-gateway-text -p leleka-gateway-domain -p leleka-worker-protocol -p leleka-engine-core -p leleka-engine-fake -p strata-control -p strata-desktop-core
|
||||
gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-cuda-model
|
||||
gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-cuda-driver --features cuda-driver
|
||||
gate cargo test "${manifest[@]}" --no-fail-fast -p leleka-engine-qwen35-cuda -p leleka-native-cpu-expert
|
||||
@@ -181,7 +181,7 @@ product_path() {
|
||||
# memory governor and the deploy tool for Clippy (-D warnings).
|
||||
gate cargo fmt -p strata-control -p strata-desktop-core -p leleka-runtime-client --check
|
||||
local crate
|
||||
for crate in leleka-memory leleka-runtime-client strata-control strata-desktop-core leleka-deploy; do
|
||||
for crate in leleka-memory leleka-memory-os leleka-runtime-client strata-control strata-desktop-core leleka-deploy; do
|
||||
gate cargo clippy "${manifest[@]}" -p "${crate}" --all-targets --no-deps -- -D warnings
|
||||
done
|
||||
# Known debt (docs/ci-audit.md lists the counts); STRICT_DEBT=1 makes it fatal. Other agents own these sources.
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"leleka-model-format",
|
||||
"leleka-deploy",
|
||||
"leleka-memory",
|
||||
"leleka-memory-os",
|
||||
"leleka-runtime-client",
|
||||
"leleka-gateway-text",
|
||||
"leleka-gateway-domain",
|
||||
|
||||
Reference in New Issue
Block a user