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