Skip to main content

sys_lib/
mem.rs

1//! Memory: how much there is, how much is in use, and how much this process
2//! may use, container-aware by default.
3//!
4//! Inside a container or a systemd unit with a memory limit, [`total`] is the
5//! limit: what this process can use and what the out-of-memory killer
6//! enforces. The host's values are one call away ([`host_total`]).
7//!
8//! ```
9//! use sys_lib as sys;
10//!
11//! println!("{} of {} used ({})", sys::mem::used()?, sys::mem::total()?, sys::mem::used_percent()?);
12//! # Ok::<(), sys_lib::Error>(())
13//! ```
14
15use core::time::Duration;
16use std::time::Instant;
17
18use crate::{Bytes, Error, Percent, Pressure, Rate, Result};
19
20/// Every memory value from one set of reads; see [`snapshot`].
21#[derive(Clone, Copy, Debug)]
22#[non_exhaustive]
23pub struct Memory {
24    /// What this process may use: the host's memory, or the container's limit
25    /// when that is smaller.
26    pub total: Bytes,
27    /// In use, counted against `total`.
28    pub used: Bytes,
29    /// Available to new allocations without swapping (reclaimable cache counts
30    /// as available). `used + free == total` always holds.
31    pub free: Bytes,
32    /// The machine's memory, ignoring any limit.
33    pub host_total: Bytes,
34    /// Available on the machine, ignoring any limit.
35    pub host_free: Bytes,
36    /// Pages doing nothing at all (the kernel's `MemFree`), when reported.
37    pub unused: Option<Bytes>,
38    /// File cache that can be reclaimed, when reported.
39    pub cached: Option<Bytes>,
40    /// The limit applied to `total`, when there is one.
41    pub limit: Option<MemoryLimit>,
42    /// Swap space (all zero when there is none).
43    pub swap: Swap,
44    /// Where `total` and `used` came from.
45    pub source: MemorySource,
46}
47
48impl Memory {
49    /// `used` as a share of `total`.
50    #[must_use]
51    pub fn used_percent(&self) -> Percent {
52        self.used.percent_of(self.total)
53    }
54
55    /// `free` as a share of `total`.
56    #[must_use]
57    pub fn free_percent(&self) -> Percent {
58        self.free.percent_of(self.total)
59    }
60}
61
62/// Where [`Memory::total`] and [`Memory::used`] came from.
63#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
64#[non_exhaustive]
65pub enum MemorySource {
66    /// The operating system's own totals: no limit applies.
67    Host,
68    /// A cgroup v1 memory limit (Linux).
69    Cgroup1,
70    /// A cgroup v2 memory limit (Linux).
71    Cgroup2,
72    /// A job object's memory limit (Windows).
73    JobObject,
74    /// LXCFS, which already shows the container's values in `/proc/meminfo`
75    /// (Linux): the limit is not applied a second time.
76    Lxcfs,
77}
78
79/// A memory limit on this process.
80#[derive(Clone, Copy, PartialEq, Eq, Debug)]
81#[non_exhaustive]
82pub struct MemoryLimit {
83    /// The hard limit: the out-of-memory killer acts at this size.
84    pub hard: Bytes,
85    /// The throttle point (cgroup v2 `memory.high`, v1 soft limit), when set.
86    pub soft: Option<Bytes>,
87    /// The swap limit, when set.
88    pub swap: Option<Bytes>,
89    /// Where the limit came from.
90    pub source: LimitSource,
91}
92
93/// Where a container or job limit came from.
94#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
95#[non_exhaustive]
96pub enum LimitSource {
97    /// cgroup v1 (Linux).
98    Cgroup1,
99    /// cgroup v2 (Linux).
100    Cgroup2,
101    /// A job object (Windows).
102    JobObject,
103}
104
105/// Swap space. All zero when there is none; never NaN in any percentage.
106#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
107#[non_exhaustive]
108pub struct Swap {
109    /// The size of all swap space.
110    pub total: Bytes,
111    /// In use.
112    pub used: Bytes,
113    /// Free. `used + free == total`.
114    pub free: Bytes,
115}
116
117impl Swap {
118    pub(crate) fn new(total: u64, free: u64) -> Swap {
119        let free = free.min(total);
120        Swap {
121            total: Bytes::new(total),
122            used: Bytes::new(total - free),
123            free: Bytes::new(free),
124        }
125    }
126}
127
128/// Which parts of the memory reading a caller needs, so each Tier 1 function
129/// performs only the reads it needs (`host_total()` reads no cgroup file).
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub(crate) struct MemWant {
132    /// The limit (cgroup `memory.max` and its ancestors, the job object).
133    pub(crate) limit: bool,
134    /// The usage counted against the limit (`memory.current`, `memory.stat`).
135    pub(crate) usage: bool,
136    /// Swap, and on Windows the cache.
137    pub(crate) swap: bool,
138}
139
140impl MemWant {
141    pub(crate) const HOST: MemWant = MemWant {
142        limit: false,
143        usage: false,
144        swap: false,
145    };
146    pub(crate) const TOTAL: MemWant = MemWant {
147        limit: true,
148        usage: false,
149        swap: false,
150    };
151    pub(crate) const USED: MemWant = MemWant {
152        limit: true,
153        usage: true,
154        swap: false,
155    };
156    pub(crate) const SWAP: MemWant = MemWant {
157        limit: false,
158        usage: false,
159        swap: true,
160    };
161    pub(crate) const ALL: MemWant = MemWant {
162        limit: true,
163        usage: true,
164        swap: true,
165    };
166    /// Everything, for the backend tests.
167    #[cfg(test)]
168    pub(crate) const ALL_FOR_TESTS: MemWant = MemWant::ALL;
169}
170
171/// Memory as a platform reports it, in bytes. [`from_raw`] turns it into the
172/// public values and enforces their invariants in one place.
173#[derive(Clone, Copy, Debug, Default)]
174pub(crate) struct MemRaw {
175    pub(crate) host_total: u64,
176    pub(crate) host_available: u64,
177    pub(crate) host_unused: Option<u64>,
178    pub(crate) cached: Option<u64>,
179    /// The limit, as configured (it may exceed the host's memory).
180    pub(crate) limit: Option<MemoryLimit>,
181    /// Usage counted against the limit (the cgroup's working set), when there
182    /// is a limit.
183    pub(crate) limited_used: Option<u64>,
184    /// Swap (total, free), when it was asked for.
185    pub(crate) swap: Option<(u64, u64)>,
186    /// `Host`, `Lxcfs`, or where the limit came from.
187    pub(crate) source: Option<MemorySource>,
188}
189
190/// The public memory values from a platform's raw reading.
191///
192/// - A limit at or above the host's memory is no limit (E-9).
193/// - Inside a limit, used is the limit's own usage, at most the limit (E-11).
194/// - `used + free == total`, `used <= total`, and the host's values obey the
195///   same rules, whatever the platform reported (threat T5: values read at
196///   different instants).
197pub(crate) fn from_raw(raw: MemRaw) -> Memory {
198    let host_total = raw.host_total;
199    let host_free = raw.host_available.min(host_total);
200    let limit = raw
201        .limit
202        .filter(|l| l.hard.raw() > 0 && l.hard.raw() < host_total);
203    let (total, used) = match (limit, raw.limited_used) {
204        (Some(l), Some(used)) => (l.hard.raw(), used.min(l.hard.raw())),
205        // A limit without its own usage: the host's usage, capped at the limit.
206        (Some(l), None) => (l.hard.raw(), (host_total - host_free).min(l.hard.raw())),
207        (None, _) => (host_total, host_total - host_free),
208    };
209    let source = match (limit, raw.source) {
210        (Some(l), _) => match l.source {
211            LimitSource::Cgroup1 => MemorySource::Cgroup1,
212            LimitSource::Cgroup2 => MemorySource::Cgroup2,
213            LimitSource::JobObject => MemorySource::JobObject,
214        },
215        (None, Some(MemorySource::Lxcfs)) => MemorySource::Lxcfs,
216        (None, _) => MemorySource::Host,
217    };
218    Memory {
219        total: Bytes::new(total),
220        used: Bytes::new(used),
221        free: Bytes::new(total - used),
222        host_total: Bytes::new(host_total),
223        host_free: Bytes::new(host_free),
224        unused: raw.host_unused.map(|u| Bytes::new(u.min(host_total))),
225        cached: raw.cached.map(|c| Bytes::new(c.min(host_total))),
226        limit,
227        swap: raw
228            .swap
229            .map_or_else(Swap::default, |(t, f)| Swap::new(t, f)),
230        source,
231    }
232}
233
234fn read(want: MemWant) -> Result<Memory> {
235    crate::sys::memory(want).map(from_raw)
236}
237
238/// What this process may use: the host's memory, or the container's (or job
239/// object's) limit when that is smaller. A live reading: the limit can change
240/// while a process runs (Kubernetes in-place resize, VM ballooning).
241///
242/// ```
243/// use sys_lib as sys;
244///
245/// // Size a cache to a quarter of what this process may use.
246/// let cache_bytes = sys::mem::total()?.raw() / 4;
247/// # Ok::<(), sys_lib::Error>(())
248/// ```
249///
250/// # Errors
251///
252/// `NotFound` or `PermissionDenied` when a sandbox hides the OS's memory
253/// counters; `Malformed` when they do not parse.
254pub fn total() -> Result<Bytes> {
255    read(MemWant::TOTAL).map(|m| m.total)
256}
257
258/// Memory in use, counted against [`total`]. Inside a limit it is the
259/// container's working set: current usage minus inactive file pages, the
260/// definition the kubelet uses for eviction.
261///
262/// # Errors
263///
264/// As [`total`].
265pub fn used() -> Result<Bytes> {
266    read(MemWant::USED).map(|m| m.used)
267}
268
269/// Memory available to new allocations without swapping: reclaimable cache
270/// counts as available (`MemAvailable` on Linux).
271///
272/// # Errors
273///
274/// As [`total`].
275pub fn free() -> Result<Bytes> {
276    read(MemWant::USED).map(|m| m.free)
277}
278
279/// [`used`] as a share of [`total`].
280///
281/// # Errors
282///
283/// As [`total`].
284pub fn used_percent() -> Result<Percent> {
285    read(MemWant::USED).map(|m| m.used_percent())
286}
287
288/// [`free`] as a share of [`total`].
289///
290/// ```
291/// use sys_lib as sys;
292///
293/// // Shed load before the out-of-memory killer does.
294/// if sys::mem::free_percent()?.value() < 5.0 { /* refuse new work */ }
295/// # Ok::<(), sys_lib::Error>(())
296/// ```
297///
298/// # Errors
299///
300/// As [`total`].
301pub fn free_percent() -> Result<Percent> {
302    read(MemWant::USED).map(|m| m.free_percent())
303}
304
305/// Every memory value from one set of reads, swap included. A caller who wants
306/// several values calls this once.
307///
308/// ```
309/// use sys_lib as sys;
310///
311/// let m = sys::mem::snapshot()?;
312/// println!("{} free of {} (host {} of {}), source {:?}", m.free, m.total, m.host_free, m.host_total, m.source);
313/// if let Some(limit) = m.limit {
314///     println!("limit {} from {:?}, throttles at {:?}", limit.hard, limit.source, limit.soft);
315/// }
316/// # Ok::<(), sys_lib::Error>(())
317/// ```
318///
319/// # Errors
320///
321/// As [`total`].
322pub fn snapshot() -> Result<Memory> {
323    read(MemWant::ALL)
324}
325
326/// The machine's memory, ignoring any limit.
327///
328/// # Errors
329///
330/// As [`total`].
331pub fn host_total() -> Result<Bytes> {
332    read(MemWant::HOST).map(|m| m.host_total)
333}
334
335/// Memory available on the machine, ignoring any limit.
336///
337/// # Errors
338///
339/// As [`total`].
340pub fn host_free() -> Result<Bytes> {
341    read(MemWant::HOST).map(|m| m.host_free)
342}
343
344/// The memory limit on this process, or `None` when there is none (or it is
345/// at or above the machine's memory). Linux: the smallest cgroup v2
346/// `memory.max` over the cgroup and its ancestors, or cgroup v1's
347/// `hierarchical_memory_limit`. Windows: the job object's process or job memory
348/// limit. macOS has no equivalent: `None`.
349///
350/// # Errors
351///
352/// As [`total`].
353pub fn limit() -> Result<Option<MemoryLimit>> {
354    read(MemWant::TOTAL).map(|m| m.limit)
355}
356
357/// Swap space. All zero when there is none (E-31). zram counts as swap; zswap
358/// is invisible to these counters (E-32).
359///
360/// # Errors
361///
362/// As [`total`].
363pub fn swap() -> Result<Swap> {
364    read(MemWant::SWAP).map(|m| m.swap)
365}
366
367/// The size of a memory page in bytes (a static fact).
368#[must_use]
369pub fn page_size() -> usize {
370    crate::sys::page_size()
371}
372
373/// How much work is stalled waiting for memory ([`Pressure`]). Linux: the
374/// cgroup's `memory.pressure`, else `/proc/pressure/memory`; `None` on kernels
375/// without pressure-stall information. macOS: the kernel's memory-pressure
376/// level, with no stall shares. Windows: `Critical` when the system signals low
377/// memory, else `Normal`, with no stall shares.
378///
379/// ```
380/// use sys_lib::{self as sys, PressureLevel};
381///
382/// if let Some(p) = sys::mem::pressure()? {
383///     if p.level >= PressureLevel::Warning { /* trim caches */ }
384/// }
385/// # Ok::<(), sys_lib::Error>(())
386/// ```
387///
388/// # Errors
389///
390/// `Malformed` when the kernel's file does not parse.
391pub fn pressure() -> Result<Option<Pressure>> {
392    crate::sys::mem_pressure()
393}
394
395/// Out-of-memory events, counted since the cgroup (or the machine) started.
396#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
397#[non_exhaustive]
398pub struct MemoryEvents {
399    /// Processes the out-of-memory killer ended.
400    pub oom_kills: u64,
401    /// Times the limit was reached and reclaim failed.
402    pub oom: u64,
403    /// Times usage hit the hard limit.
404    pub max: u64,
405    /// Times usage went over the throttle point (`memory.high`).
406    pub high: u64,
407    /// Whether the counts are this cgroup's or the whole machine's.
408    pub scope: EventScope,
409}
410
411/// What [`MemoryEvents`] count.
412#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
413#[non_exhaustive]
414pub enum EventScope {
415    /// This process's cgroup.
416    Cgroup,
417    /// The whole machine.
418    #[default]
419    Host,
420}
421
422/// Whether this container (or machine) has been running out of memory. A
423/// watchdog compares two readings and sheds load before the next kill.
424///
425/// Linux: cgroup v2 `memory.events`, cgroup v1 `memory.oom_control`, and
426/// outside a cgroup `/proc/vmstat` (`max` and `high` are then 0). macOS and
427/// Windows keep no such counters: `None`.
428///
429/// ```
430/// use sys_lib as sys;
431///
432/// if let Some(e) = sys::mem::events()? {
433///     println!("{} out-of-memory kills ({:?})", e.oom_kills, e.scope);
434/// }
435/// # Ok::<(), sys_lib::Error>(())
436/// ```
437///
438/// # Errors
439///
440/// `Malformed` when a counter file does not parse.
441pub fn events() -> Result<Option<MemoryEvents>> {
442    crate::sys::mem_events()
443}
444
445/// Swap and paging activity over an interval: whether the machine is
446/// thrashing.
447#[derive(Clone, Copy, PartialEq, Debug)]
448#[non_exhaustive]
449pub struct Activity {
450    /// Memory moved from swap back into RAM.
451    pub swap_in: Rate,
452    /// Memory moved from RAM out to swap.
453    pub swap_out: Rate,
454    /// Page faults that had to read from disk, per second, when reported.
455    pub major_faults_per_sec: Option<f64>,
456    /// The time the values cover.
457    pub interval: Duration,
458}
459
460/// Cumulative paging counters as a platform reports them.
461#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
462pub(crate) struct PagingRaw {
463    pub(crate) swap_in: u64,
464    pub(crate) swap_out: u64,
465    pub(crate) major_faults: Option<u64>,
466}
467
468/// The interval [`activity`] measures over.
469const ACTIVITY_WINDOW: Duration = Duration::from_secs(1);
470
471/// Swap and paging activity over the next second. **Blocks for one second**;
472/// a monitor keeps a [`Sampler`] instead.
473///
474/// # Errors
475///
476/// `Unsupported` where the OS has no system-wide paging counters; otherwise as
477/// [`Sampler::sample`].
478pub fn activity() -> Result<Activity> {
479    let mut sampler = Sampler::new()?;
480    std::thread::sleep(ACTIVITY_WINDOW);
481    sampler.sample()
482}
483
484/// Measures swap and paging activity between samples. Owned by the caller: two
485/// samplers never disturb each other. `sample` never blocks and allocates
486/// nothing.
487///
488/// ```no_run
489/// use std::time::Duration;
490/// use sys_lib as sys;
491///
492/// let mut paging = sys::mem::Sampler::new()?;
493/// std::thread::sleep(Duration::from_secs(5));
494/// let a = paging.sample()?;
495/// if a.swap_out.bytes_per_sec() > 0 && a.major_faults_per_sec.unwrap_or(0.0) > 100.0 {
496///     println!("thrashing: swapping out {}", a.swap_out);
497/// }
498/// # Ok::<(), sys_lib::Error>(())
499/// ```
500#[derive(Debug)]
501pub struct Sampler {
502    previous: PagingRaw,
503    at: Instant,
504}
505
506impl Sampler {
507    /// Takes the first reading.
508    ///
509    /// # Errors
510    ///
511    /// `Unsupported` where the OS has no system-wide paging counters.
512    pub fn new() -> Result<Sampler> {
513        Ok(Sampler {
514            previous: crate::sys::paging()?,
515            at: Instant::now(),
516        })
517    }
518
519    /// The activity since the previous sample. A counter that went backwards
520    /// re-bases the sampler and counts as no activity.
521    ///
522    /// # Errors
523    ///
524    /// `TooSoon` when no time passed since the previous sample.
525    pub fn sample(&mut self) -> Result<Activity> {
526        let now = crate::sys::paging()?;
527        let at = Instant::now();
528        let interval = at.duration_since(self.at);
529        if interval.is_zero() {
530            return Err(Error::TooSoon {
531                elapsed: interval,
532                minimum: Duration::from_millis(1),
533            });
534        }
535        let delta = |new: u64, old: u64| new.saturating_sub(old);
536        let activity = Activity {
537            swap_in: Rate::from_delta(delta(now.swap_in, self.previous.swap_in), interval),
538            swap_out: Rate::from_delta(delta(now.swap_out, self.previous.swap_out), interval),
539            major_faults_per_sec: match (now.major_faults, self.previous.major_faults) {
540                (Some(n), Some(o)) => Some(delta(n, o) as f64 / interval.as_secs_f64()),
541                _ => None,
542            },
543            interval,
544        };
545        self.previous = now;
546        self.at = at;
547        Ok(activity)
548    }
549}
550
551/// Explicit huge pages and the transparent-huge-page mode.
552#[derive(Clone, Copy, PartialEq, Eq, Debug)]
553#[non_exhaustive]
554pub struct HugePages {
555    /// The default huge page size (2 MiB on x86_64).
556    pub page_size: Bytes,
557    /// Huge pages in the pool.
558    pub total: u64,
559    /// Free huge pages.
560    pub free: u64,
561    /// Reserved but not yet allocated.
562    pub reserved: u64,
563    /// The transparent-huge-page mode (Linux).
564    pub transparent: Option<TransparentHugePages>,
565    /// The smallest large page (Windows `GetLargePageMinimum`).
566    pub large_page_minimum: Option<Bytes>,
567}
568
569/// The Linux transparent-huge-page mode.
570#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
571#[non_exhaustive]
572pub enum TransparentHugePages {
573    /// Used for every eligible mapping.
574    Always,
575    /// Used only where the program asks with `madvise`.
576    Madvise,
577    /// Not used.
578    Never,
579}
580
581/// Explicit huge pages and the transparent-huge-page mode, which databases and
582/// JIT runtimes care about. Linux: `/proc/meminfo` and
583/// `/sys/kernel/mm/transparent_hugepage/enabled`. Windows: the large page
584/// minimum (the pool counts are zero). macOS: `None`.
585///
586/// # Errors
587///
588/// `Malformed` when the kernel's files do not parse.
589pub fn huge_pages() -> Result<Option<HugePages>> {
590    crate::sys::huge_pages()
591}
592
593/// An installed memory module. Never the serial number.
594#[derive(Clone, Debug, PartialEq, Eq)]
595#[non_exhaustive]
596pub struct MemoryModule {
597    /// Its size.
598    pub size: Bytes,
599    /// Its technology.
600    pub kind: MemoryKind,
601    /// Its form.
602    pub form: MemoryForm,
603    /// Rated speed in mega-transfers per second.
604    pub speed_mts: Option<u32>,
605    /// The speed it is configured to run at.
606    pub configured_speed_mts: Option<u32>,
607    /// The slot: "DIMM_A1".
608    pub locator: Option<String>,
609    /// The maker.
610    pub manufacturer: Option<String>,
611    /// The part number.
612    pub part_number: Option<String>,
613}
614
615/// A memory technology.
616#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
617#[non_exhaustive]
618pub enum MemoryKind {
619    /// DDR3.
620    Ddr3,
621    /// DDR4.
622    Ddr4,
623    /// DDR5.
624    Ddr5,
625    /// LPDDR4.
626    Lpddr4,
627    /// LPDDR5.
628    Lpddr5,
629    /// LPDDR5X.
630    Lpddr5x,
631    /// High Bandwidth Memory.
632    Hbm,
633    /// Something else.
634    Other,
635    /// Not known.
636    Unknown,
637}
638
639/// A module's physical form.
640#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
641#[non_exhaustive]
642pub enum MemoryForm {
643    /// A DIMM.
644    Dimm,
645    /// A SO-DIMM.
646    SoDimm,
647    /// Soldered to the board.
648    Soldered,
649    /// Something else.
650    Other,
651    /// Not known.
652    Unknown,
653}
654
655/// The installed memory sticks, from the SMBIOS type 17 records; empty slots
656/// are left out.
657///
658/// # Errors
659///
660/// `PermissionDenied` on Linux unless the process runs as root (the raw table
661/// is mode 0400); `Unsupported` on Apple silicon (unified memory, one package).
662pub fn modules() -> Result<Vec<MemoryModule>> {
663    crate::sys::memory_modules()
664}
665
666/// A raw SMBIOS memory device as a public value.
667#[cfg_attr(target_vendor = "apple", allow(dead_code))]
668pub(crate) fn module_from(d: crate::parse::smbios::MemoryDevice) -> MemoryModule {
669    MemoryModule {
670        size: Bytes::new(d.bytes),
671        kind: match d.kind {
672            0x18 => MemoryKind::Ddr3,
673            0x1A => MemoryKind::Ddr4,
674            0x22 => MemoryKind::Ddr5,
675            0x1E => MemoryKind::Lpddr4,
676            0x23 => MemoryKind::Lpddr5,
677            0x20 | 0x21 | 0x24 => MemoryKind::Hbm,
678            0 | 2 => MemoryKind::Unknown,
679            _ => MemoryKind::Other,
680        },
681        form: match d.form {
682            0x09 | 0x0F => MemoryForm::Dimm,
683            0x0D => MemoryForm::SoDimm,
684            0x0B => MemoryForm::Soldered,
685            0 | 2 => MemoryForm::Unknown,
686            _ => MemoryForm::Other,
687        },
688        speed_mts: d.speed_mts,
689        configured_speed_mts: d.configured_speed_mts,
690        locator: d.locator,
691        manufacturer: d.manufacturer,
692        part_number: d.part_number,
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    fn limit(hard: u64, source: LimitSource) -> MemoryLimit {
701        MemoryLimit {
702            hard: Bytes::new(hard),
703            soft: None,
704            swap: None,
705            source,
706        }
707    }
708
709    const GIB: u64 = 1 << 30;
710
711    #[test]
712    fn test_mem_host_values_without_a_limit() {
713        let m = from_raw(MemRaw {
714            host_total: 16 * GIB,
715            host_available: 10 * GIB,
716            host_unused: Some(2 * GIB),
717            ..MemRaw::default()
718        });
719        assert_eq!(
720            (m.total.raw(), m.used.raw(), m.free.raw()),
721            (16 * GIB, 6 * GIB, 10 * GIB)
722        );
723        assert_eq!(m.source, MemorySource::Host);
724        assert_eq!(m.limit, None);
725        assert_eq!(m.swap, Swap::default());
726        assert_eq!(m.used_percent().to_string(), "37.5%");
727    }
728
729    #[test]
730    fn test_mem_limit_below_host_wins_with_its_own_usage() {
731        let m = from_raw(MemRaw {
732            host_total: 64 * GIB,
733            host_available: 60 * GIB,
734            limit: Some(limit(256 << 20, LimitSource::Cgroup2)),
735            limited_used: Some(100 << 20),
736            ..MemRaw::default()
737        });
738        assert_eq!((m.total.raw(), m.used.raw()), (256 << 20, 100 << 20));
739        assert_eq!(m.host_total.raw(), 64 * GIB);
740        assert_eq!(m.source, MemorySource::Cgroup2);
741    }
742
743    #[test]
744    fn test_mem_limit_at_or_above_host_is_no_limit() {
745        // E-9: a 1 TiB limit on a 64 GiB host.
746        let m = from_raw(MemRaw {
747            host_total: 64 * GIB,
748            host_available: 32 * GIB,
749            limit: Some(limit(1 << 40, LimitSource::Cgroup1)),
750            limited_used: Some(GIB),
751            ..MemRaw::default()
752        });
753        assert_eq!((m.total.raw(), m.used.raw()), (64 * GIB, 32 * GIB));
754        assert_eq!((m.limit, m.source), (None, MemorySource::Host));
755    }
756
757    #[test]
758    fn test_mem_invariants_hold_for_inconsistent_readings() {
759        // T5: available above total, usage above the limit, cache above total.
760        let m = from_raw(MemRaw {
761            host_total: 8 * GIB,
762            host_available: 9 * GIB,
763            cached: Some(20 * GIB),
764            limit: Some(limit(GIB, LimitSource::JobObject)),
765            limited_used: Some(2 * GIB),
766            swap: Some((GIB, 2 * GIB)),
767            ..MemRaw::default()
768        });
769        assert_eq!(m.used.saturating_add(m.free), m.total);
770        assert!(m.used <= m.total && m.host_free <= m.host_total);
771        assert_eq!(m.cached, Some(Bytes::new(8 * GIB)));
772        assert_eq!(m.swap.used.saturating_add(m.swap.free), m.swap.total);
773        assert_eq!(m.source, MemorySource::JobObject);
774    }
775
776    #[test]
777    fn test_mem_lxcfs_source_kept_without_a_limit() {
778        let m = from_raw(MemRaw {
779            host_total: GIB,
780            host_available: GIB / 2,
781            source: Some(MemorySource::Lxcfs),
782            ..MemRaw::default()
783        });
784        assert_eq!(m.source, MemorySource::Lxcfs);
785    }
786
787    #[test]
788    fn test_mem_live_readings_are_consistent() {
789        let m = snapshot().unwrap();
790        assert!(m.total.raw() > 0 && m.used <= m.total);
791        assert_eq!(m.used.saturating_add(m.free), m.total);
792        assert!(m.total <= m.host_total);
793        assert!(page_size().is_power_of_two() && page_size() >= 4096);
794    }
795}