i3status_rs/blocks/
memory.rs

1//! Memory and swap usage
2//!
3//! # Configuration
4//!
5//! Key | Values | Default
6//! ----|--------|--------
7//! `format` | A string to customise the output of this block when in "Memory" view. See below for available placeholders. | `" $icon $mem_used.eng(prefix:Mi)/$mem_total.eng(prefix:Mi)($mem_used_percents.eng(w:2)) "`
8//! `format_alt` | If set, block will switch between `format` and `format_alt` on every click | `None`
9//! `interval` | Update interval in seconds | `5`
10//! `warning_mem` | Percentage of memory usage, where state is set to warning | `80.0`
11//! `warning_swap` | Percentage of swap usage, where state is set to warning | `80.0`
12//! `critical_mem` | Percentage of memory usage, where state is set to critical | `95.0`
13//! `critical_swap` | Percentage of swap usage, where state is set to critical | `95.0`
14//!
15//! Placeholder               | Value                                                                           | Type   | Unit
16//! --------------------------|---------------------------------------------------------------------------------|--------|-------
17//! `icon`                    | Memory icon                                                                     | Icon   | -
18//! `icon_swap`               | Swap icon                                                                       | Icon   | -
19//! `mem_total`               | Total physical ram available                                                    | Number | Bytes
20//! `mem_free`                | Free memory not yet used by the kernel or userspace (in general you should use mem_avail) | Number | Bytes
21//! `mem_free_percents`       | as above but as a percentage of total memory                                    | Number | Percents
22//! `mem_avail`               | Kernel estimate of usable free memory which includes cached memory and buffers  | Number | Bytes
23//! `mem_avail_percents`      | as above but as a percentage of total memory                                    | Number | Percents
24//! `mem_total_used`          | mem_total - mem_free                                                            | Number | Bytes
25//! `mem_total_used_percents` | as above but as a percentage of total memory                                    | Number | Percents
26//! `mem_used`                | Memory used, excluding cached memory and buffers; same as htop's green bar      | Number | Bytes
27//! `mem_used_percents`       | as above but as a percentage of total memory                                    | Number | Percents
28//! `buffers`                 | Buffers, similar to htop's blue bar                                             | Number | Bytes
29//! `buffers_percent`         | as above but as a percentage of total memory                                    | Number | Percents
30//! `cached`                  | Cached memory (taking into account ZFS ARC cache), similar to htop's yellow bar | Number | Bytes
31//! `cached_percent`          | as above but as a percentage of total memory                                    | Number | Percents
32//! `swap_total`              | Swap total                                                                      | Number | Bytes
33//! `swap_free`               | Swap free                                                                       | Number | Bytes
34//! `swap_free_percents`      | as above but as a percentage of total memory                                    | Number | Percents
35//! `swap_used`               | Swap used                                                                       | Number | Bytes
36//! `swap_used_percents`      | as above but as a percentage of total memory                                    | Number | Percents
37//! `zram_compressed`         | Compressed zram memory usage                                                    | Number | Bytes
38//! `zram_decompressed`       | Decompressed zram memory usage                                                  | Number | Bytes
39//! 'zram_comp_ratio'         | Ratio of the decompressed/compressed zram memory                                | Number | -
40//! `zswap_compressed`        | Compressed zswap memory usage (>=Linux 5.19)                                    | Number | Bytes
41//! `zswap_decompressed`      | Decompressed zswap memory usage (>=Linux 5.19)                                  | Number | Bytes
42//! `zswap_decompressed_percents` | as above but as a percentage of total zswap memory  (>=Linux 5.19)          | Number | Percents
43//! 'zswap_comp_ratio'        | Ratio of the decompressed/compressed zswap memory (>=Linux 5.19)                | Number | -
44//!
45//! Action          | Description                               | Default button
46//! ----------------|-------------------------------------------|---------------
47//! `toggle_format` | Toggles between `format` and `format_alt` | Left
48//!
49//! # Examples
50//!
51//! ```toml
52//! [[block]]
53//! block = "memory"
54//! format = " $icon $mem_used_percents.eng(w:1) "
55//! format_alt = " $icon_swap $swap_free.eng(w:3,u:B,p:Mi)/$swap_total.eng(w:3,u:B,p:Mi)($swap_used_percents.eng(w:2)) "
56//! interval = 30
57//! warning_mem = 70
58//! critical_mem = 90
59//! ```
60//!
61//! Show swap and hide if it is zero:
62//!
63//! ```toml
64//! [[block]]
65//! block = "memory"
66//! format = " $icon $swap_used.eng(range:1..) |"
67//! ```
68//!
69//! # Icons Used
70//! - `memory_mem`
71//! - `memory_swap`
72
73use std::cmp::min;
74use std::str::FromStr as _;
75use tokio::fs::{File, read_dir};
76use tokio::io::{AsyncBufReadExt as _, BufReader};
77
78use super::prelude::*;
79use crate::util::read_file;
80
81#[derive(Deserialize, Debug, SmartDefault)]
82#[serde(deny_unknown_fields, default)]
83pub struct Config {
84    pub format: FormatConfig,
85    pub format_alt: Option<FormatConfig>,
86    #[default(5.into())]
87    pub interval: Seconds,
88    #[default(80.0)]
89    pub warning_mem: f64,
90    #[default(80.0)]
91    pub warning_swap: f64,
92    #[default(95.0)]
93    pub critical_mem: f64,
94    #[default(95.0)]
95    pub critical_swap: f64,
96}
97
98pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
99    let mut actions = api.get_actions()?;
100    api.set_default_actions(&[(MouseButton::Left, None, "toggle_format")])?;
101
102    let mut format = config.format.with_default(
103        " $icon $mem_used.eng(prefix:Mi)/$mem_total.eng(prefix:Mi)($mem_used_percents.eng(w:2)) ",
104    )?;
105    let mut format_alt = match &config.format_alt {
106        Some(f) => Some(f.with_default("")?),
107        None => None,
108    };
109
110    let mut timer = config.interval.timer();
111
112    loop {
113        let mem_state = Memstate::new().await?;
114
115        let mem_total = mem_state.mem_total as f64;
116        let mem_free = mem_state.mem_free as f64;
117
118        // TODO: possibly remove this as it is confusing to have `mem_total_used` and `mem_used`
119        // htop and such only display equivalent of `mem_used`
120        let mem_total_used = mem_total - mem_free;
121
122        // dev note: difference between avail and free:
123        // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
124        // same logic as htop
125        let mem_avail = if mem_state.mem_available != 0 {
126            min(mem_state.mem_available, mem_state.mem_total)
127        } else {
128            mem_state.mem_free
129        } as f64;
130
131        // While zfs_arc_cache can be considered "available" memory,
132        // it can only free a maximum of (zfs_arc_cache - zfs_arc_min) amount.
133        // see https://github.com/htop-dev/htop/pull/1003
134        let zfs_shrinkable_size = mem_state
135            .zfs_arc_cache
136            .saturating_sub(mem_state.zfs_arc_min) as f64;
137        let mem_avail = mem_avail + zfs_shrinkable_size;
138
139        let pagecache = mem_state.pagecache as f64;
140        let reclaimable = mem_state.s_reclaimable as f64;
141        let shmem = mem_state.shmem as f64;
142
143        // See https://lore.kernel.org/lkml/1455827801-13082-1-git-send-email-hannes@cmpxchg.org/
144        let cached = pagecache + reclaimable - shmem + zfs_shrinkable_size;
145
146        let buffers = mem_state.buffers as f64;
147
148        // Userspace should use `mem_avail` for estimating the memory that is available.
149        // See: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
150        let mem_used = mem_total - mem_avail;
151
152        let swap_total = mem_state.swap_total as f64;
153        let swap_free = mem_state.swap_free as f64;
154        let swap_cached = mem_state.swap_cached as f64;
155        let swap_used = swap_total - swap_free - swap_cached;
156
157        // Zswap usage
158        let zswap_compressed = mem_state.zswap_compressed as f64;
159        let zswap_decompressed = mem_state.zswap_decompressed as f64;
160
161        let zswap_comp_ratio = if zswap_compressed != 0.0 {
162            zswap_decompressed / zswap_compressed
163        } else {
164            0.0
165        };
166        let zswap_decompressed_percents = if (swap_used + swap_cached) != 0.0 {
167            zswap_decompressed / (swap_used + swap_cached) * 100.0
168        } else {
169            0.0
170        };
171
172        // Zram usage
173        let zram_compressed = mem_state.zram_compressed as f64;
174        let zram_decompressed = mem_state.zram_decompressed as f64;
175
176        let zram_comp_ratio = if zram_compressed != 0.0 {
177            zram_decompressed / zram_compressed
178        } else {
179            0.0
180        };
181
182        let mut widget = Widget::new().with_format(format.clone());
183        widget.set_values(map! {
184            "icon" => Value::icon("memory_mem"),
185            "icon_swap" => Value::icon("memory_swap"),
186            "mem_total" => Value::bytes(mem_total),
187            "mem_free" => Value::bytes(mem_free),
188            "mem_free_percents" => Value::percents(mem_free / mem_total * 100.),
189            "mem_total_used" => Value::bytes(mem_total_used),
190            "mem_total_used_percents" => Value::percents(mem_total_used / mem_total * 100.),
191            "mem_used" => Value::bytes(mem_used),
192            "mem_used_percents" => Value::percents(mem_used / mem_total * 100.),
193            "mem_avail" => Value::bytes(mem_avail),
194            "mem_avail_percents" => Value::percents(mem_avail / mem_total * 100.),
195            "swap_total" => Value::bytes(swap_total),
196            "swap_free" => Value::bytes(swap_free),
197            "swap_free_percents" => Value::percents(swap_free / swap_total * 100.),
198            "swap_used" => Value::bytes(swap_used),
199            "swap_used_percents" => Value::percents(swap_used / swap_total * 100.),
200            "buffers" => Value::bytes(buffers),
201            "buffers_percent" => Value::percents(buffers / mem_total * 100.),
202            "cached" => Value::bytes(cached),
203            "cached_percent" => Value::percents(cached / mem_total * 100.),
204            "zram_compressed" => Value::bytes(zram_compressed),
205            "zram_decompressed" => Value::bytes(zram_decompressed),
206            "zram_comp_ratio" => Value::number(zram_comp_ratio),
207            "zswap_compressed" => Value::bytes(zswap_compressed),
208            "zswap_decompressed" => Value::bytes(zswap_decompressed),
209            "zswap_decompressed_percents" => Value::percents(zswap_decompressed_percents),
210            "zswap_comp_ratio" => Value::number(zswap_comp_ratio),
211        });
212
213        let mem_state = match mem_used / mem_total * 100. {
214            x if x > config.critical_mem => State::Critical,
215            x if x > config.warning_mem => State::Warning,
216            _ => State::Idle,
217        };
218
219        let swap_state = match swap_used / swap_total * 100. {
220            x if x > config.critical_swap => State::Critical,
221            x if x > config.warning_swap => State::Warning,
222            _ => State::Idle,
223        };
224
225        widget.state = if mem_state == State::Critical || swap_state == State::Critical {
226            State::Critical
227        } else if mem_state == State::Warning || swap_state == State::Warning {
228            State::Warning
229        } else {
230            State::Idle
231        };
232
233        api.set_widget(widget)?;
234
235        loop {
236            select! {
237                _ = timer.tick() => break,
238                _ = api.wait_for_update_request() => break,
239                Some(action) = actions.recv() => match action.as_ref() {
240                    "toggle_format" => {
241                        if let Some(ref mut format_alt) = format_alt {
242                            std::mem::swap(format_alt, &mut format);
243                            break;
244                        }
245                    }
246                    _ => (),
247                }
248            }
249        }
250    }
251}
252
253#[derive(Clone, Copy, Debug, Default)]
254struct Memstate {
255    mem_total: u64,
256    mem_free: u64,
257    mem_available: u64,
258    buffers: u64,
259    pagecache: u64,
260    s_reclaimable: u64,
261    shmem: u64,
262    swap_total: u64,
263    swap_free: u64,
264    swap_cached: u64,
265    zram_compressed: u64,
266    zram_decompressed: u64,
267    zswap_compressed: u64,
268    zswap_decompressed: u64,
269    zfs_arc_cache: u64,
270    zfs_arc_min: u64,
271}
272
273impl Memstate {
274    async fn new() -> Result<Self> {
275        // Reference: https://www.kernel.org/doc/Documentation/filesystems/proc.txt
276        let mut file = BufReader::new(
277            File::open("/proc/meminfo")
278                .await
279                .error("/proc/meminfo does not exist")?,
280        );
281
282        let mut mem_state = Memstate::default();
283        let mut line = String::new();
284
285        while file
286            .read_line(&mut line)
287            .await
288            .error("failed to read /proc/meminfo")?
289            != 0
290        {
291            let mut words = line.split_whitespace();
292
293            let name = match words.next() {
294                Some(name) => name,
295                None => {
296                    line.clear();
297                    continue;
298                }
299            };
300            let val = words
301                .next()
302                .and_then(|x| u64::from_str(x).ok())
303                .error("failed to parse /proc/meminfo")?;
304
305            // These values are reported as “kB” but are actually “kiB”.
306            // Convert them into bytes to avoid having to handle this later.
307            // Source: https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/6/html/deployment_guide/s2-proc-meminfo#s2-proc-meminfo
308            const KIB: u64 = 1024;
309            match name {
310                "MemTotal:" => mem_state.mem_total = val * KIB,
311                "MemFree:" => mem_state.mem_free = val * KIB,
312                "MemAvailable:" => mem_state.mem_available = val * KIB,
313                "Buffers:" => mem_state.buffers = val * KIB,
314                "Cached:" => mem_state.pagecache = val * KIB,
315                "SReclaimable:" => mem_state.s_reclaimable = val * KIB,
316                "Shmem:" => mem_state.shmem = val * KIB,
317                "SwapTotal:" => mem_state.swap_total = val * KIB,
318                "SwapFree:" => mem_state.swap_free = val * KIB,
319                "SwapCached:" => mem_state.swap_cached = val * KIB,
320                "Zswap:" => mem_state.zswap_compressed = val * KIB,
321                "Zswapped:" => mem_state.zswap_decompressed = val * KIB,
322                _ => (),
323            }
324
325            line.clear();
326        }
327
328        // For ZRAM
329        let mut entries = read_dir("/sys/block/")
330            .await
331            .error("Could not read /sys/block")?;
332        while let Some(entry) = entries
333            .next_entry()
334            .await
335            .error("Could not get next file /sys/block")?
336        {
337            let Ok(file_name) = entry.file_name().into_string() else {
338                continue;
339            };
340            if !file_name.starts_with("zram") {
341                continue;
342            }
343
344            let zram_file_path = entry.path().join("mm_stat");
345            let Ok(file) = File::open(zram_file_path).await else {
346                continue;
347            };
348
349            let mut buf = BufReader::new(file);
350            let mut line = String::new();
351            if buf.read_to_string(&mut line).await.is_err() {
352                continue;
353            }
354
355            let mut values = line.split_whitespace().map(|s| s.parse::<u64>());
356            if let Some(Ok(zram_swap_size)) = values.next() && let Some(Ok(zram_comp_size)) = values.next()
357                // zram initializes with small amount by default, return 0 then
358                && zram_swap_size >= 65_536
359            {
360                mem_state.zram_decompressed += zram_swap_size;
361                mem_state.zram_compressed += zram_comp_size;
362            }
363        }
364
365        // For ZFS
366        if let Ok(arcstats) = read_file("/proc/spl/kstat/zfs/arcstats").await {
367            let size_re = regex!(r"size\s+\d+\s+(\d+)");
368            let size = &size_re
369                .captures(&arcstats)
370                .error("failed to find zfs_arc_cache size")?[1];
371            mem_state.zfs_arc_cache = size.parse().error("failed to parse zfs_arc_cache size")?;
372            let c_min_re = regex!(r"c_min\s+\d+\s+(\d+)");
373            let c_min = &c_min_re
374                .captures(&arcstats)
375                .error("failed to find zfs_arc_min size")?[1];
376            mem_state.zfs_arc_min = c_min.parse().error("failed to parse zfs_arc_min size")?;
377        }
378
379        Ok(mem_state)
380    }
381}