linuxutils-system 0.1.0

System utilities from linuxutils
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use linuxutils_common::man::ManContent;

pub const MAN: ManContent = ManContent::empty();

use clap::Parser;
use cols::{OutputMode, Table, WidthHint, print_table};
use crate::sysfs::SysfsDevice;
use std::{
    path::{Path, PathBuf},
    process::ExitCode,
};

#[derive(Parser)]
#[command(
    name = "lsmem",
    about = "List the ranges of available memory with their online status"
)]
pub struct Args {
    /// List each individual memory block
    #[arg(short, long)]
    all: bool,

    /// Print SIZE in bytes rather than human-readable format
    #[arg(short, long)]
    bytes: bool,

    /// Use JSON output format
    #[arg(short = 'J', long)]
    json: bool,

    /// Don't print headings
    #[arg(short = 'n', long)]
    noheadings: bool,

    /// Output columns to print
    #[arg(short, long, value_delimiter = ',')]
    output: Option<Vec<String>>,

    /// Output all available columns
    #[arg(long)]
    output_all: bool,

    /// Use key="value" output format
    #[arg(short = 'P', long)]
    pairs: bool,

    /// Use raw output format
    #[arg(short, long)]
    raw: bool,

    /// Split ranges by specified columns
    #[arg(short = 'S', long, value_delimiter = ',')]
    split: Option<Vec<String>>,

    /// Use specified directory as system root
    #[arg(short, long)]
    sysroot: Option<PathBuf>,

    /// Print summary information (never, always, only)
    #[arg(long, default_value = "always")]
    summary: SummaryMode,
}

#[derive(Clone, Debug)]
enum SummaryMode {
    Never,
    Always,
    Only,
}

impl std::str::FromStr for SummaryMode {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, String> {
        match s {
            "never" => Ok(Self::Never),
            "always" => Ok(Self::Always),
            "only" => Ok(Self::Only),
            _ => Err(format!("invalid summary mode: {s}")),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Col {
    Range,
    Size,
    State,
    Removable,
    Block,
    Node,
    Zones,
}

impl Col {
    fn name(self) -> &'static str {
        match self {
            Col::Range => "RANGE",
            Col::Size => "SIZE",
            Col::State => "STATE",
            Col::Removable => "REMOVABLE",
            Col::Block => "BLOCK",
            Col::Node => "NODE",
            Col::Zones => "ZONES",
        }
    }

    fn whint(self) -> WidthHint {
        match self {
            Col::Range => WidthHint::Auto,
            Col::Size => WidthHint::Fixed(5),
            Col::State => WidthHint::Fixed(6),
            Col::Removable => WidthHint::Fixed(9),
            Col::Block => WidthHint::Auto,
            Col::Node => WidthHint::Fixed(4),
            Col::Zones => WidthHint::Auto,
        }
    }

    fn is_right(self) -> bool {
        matches!(self, Col::Size | Col::Removable | Col::Block)
    }

    fn from_name(name: &str) -> Option<Self> {
        match name.to_uppercase().as_str() {
            "RANGE" => Some(Col::Range),
            "SIZE" => Some(Col::Size),
            "STATE" => Some(Col::State),
            "REMOVABLE" => Some(Col::Removable),
            "BLOCK" => Some(Col::Block),
            "NODE" => Some(Col::Node),
            "ZONES" => Some(Col::Zones),
            _ => None,
        }
    }
}

const DEFAULT_COLUMNS: &[Col] = &[
    Col::Range,
    Col::Size,
    Col::State,
    Col::Removable,
    Col::Block,
];
const ALL_COLUMNS: &[Col] = &[
    Col::Range,
    Col::Size,
    Col::State,
    Col::Removable,
    Col::Block,
    Col::Node,
    Col::Zones,
];

/// Attributes that control how memory blocks are split into ranges.
const DEFAULT_SPLIT: &[Col] = &[Col::State, Col::Removable, Col::Node];

#[derive(Debug)]
struct MemBlock {
    index: u64,
    state: String,
    removable: bool,
    node: Option<u64>,
    zones: String,
    block_size: u64,
}

impl MemBlock {
    fn start_addr(&self) -> u64 {
        self.index * self.block_size
    }

    fn end_addr(&self) -> u64 {
        (self.index + 1) * self.block_size - 1
    }
}

#[derive(Debug)]
struct MemRange {
    start_block: u64,
    end_block: u64,
    start_addr: u64,
    end_addr: u64,
    size: u64,
    state: String,
    removable: bool,
    node: Option<u64>,
    zones: String,
}

fn read_memory_blocks(sysroot: &Path) -> Result<(u64, Vec<MemBlock>), String> {
    let mem_dir = SysfsDevice::new(sysroot.join("sys/devices/system/memory"));

    let block_size = mem_dir
        .read_attr_hex("block_size_bytes")
        .map_err(|e| format!("failed to read block_size_bytes: {e}"))?;

    let children = mem_dir
        .children_with_prefix("memory")
        .map_err(|e| format!("failed to list memory blocks: {e}"))?;

    let mut blocks = Vec::new();
    for child in children {
        let index = child
            .read_attr_hex("phys_index")
            .map_err(|e| format!("failed to read phys_index: {e}"))?;
        let state = child
            .read_attr("state")
            .map_err(|e| format!("failed to read state: {e}"))?;
        let removable = child.read_attr_bool("removable").unwrap_or(false);
        let node = find_node(&child);
        let zones = child.read_attr("valid_zones").unwrap_or_default();
        // Only the first zone matters for display.
        let zones = zones.split_whitespace().next().unwrap_or("").to_string();

        blocks.push(MemBlock {
            index,
            state,
            removable,
            node,
            zones,
            block_size,
        });
    }

    blocks.sort_by_key(|b| b.index);
    Ok((block_size, blocks))
}

fn find_node(dev: &SysfsDevice) -> Option<u64> {
    // NUMA node is in a symlink like /sys/devices/system/memory/memoryN/nodeN
    let path = dev.path();
    if let Ok(entries) = std::fs::read_dir(path) {
        for entry in entries.flatten() {
            if let Some(name) = entry.file_name().to_str()
                && let Some(n) = name.strip_prefix("node")
                && let Ok(num) = n.parse::<u64>()
            {
                return Some(num);
            }
        }
    }
    None
}

fn merge_blocks(blocks: &[MemBlock], split_cols: &[Col]) -> Vec<MemRange> {
    if blocks.is_empty() {
        return Vec::new();
    }

    let mut ranges = Vec::new();
    let mut start = 0;

    for i in 1..blocks.len() {
        let should_split = blocks[i].index != blocks[i - 1].index + 1
            || split_cols.iter().any(|col| match col {
                Col::State => blocks[i].state != blocks[start].state,
                Col::Removable => {
                    blocks[i].removable != blocks[start].removable
                }
                Col::Node => blocks[i].node != blocks[start].node,
                Col::Zones => blocks[i].zones != blocks[start].zones,
                _ => false,
            });

        if should_split {
            ranges.push(make_range(&blocks[start..i]));
            start = i;
        }
    }
    ranges.push(make_range(&blocks[start..]));
    ranges
}

fn make_range(blocks: &[MemBlock]) -> MemRange {
    let first = &blocks[0];
    let last = &blocks[blocks.len() - 1];
    MemRange {
        start_block: first.index,
        end_block: last.index,
        start_addr: first.start_addr(),
        end_addr: last.end_addr(),
        size: (last.index - first.index + 1) * first.block_size,
        state: first.state.clone(),
        removable: first.removable,
        node: first.node,
        zones: first.zones.clone(),
    }
}

fn format_size(bytes: u64, human: bool) -> String {
    if !human {
        return bytes.to_string();
    }
    const UNITS: &[&str] = &["B", "K", "M", "G", "T", "P", "E"];
    let mut val = bytes as f64;
    for unit in UNITS {
        if val < 1024.0 || *unit == "E" {
            if (val - val.round()).abs() < 0.05 {
                return format!("{}{unit}", val.round() as u64);
            }
            // Use C-style rounding (half-up) instead of Rust's default
            // banker's rounding: add a tiny epsilon before formatting.
            let rounded = (val * 10.0 + 0.5).floor() / 10.0;
            return format!("{rounded:.1}{unit}");
        }
        val /= 1024.0;
    }
    unreachable!()
}

pub fn run(args: Args) -> ExitCode {
    let sysroot = args.sysroot.as_deref().unwrap_or(Path::new("/"));

    let (block_size, blocks) = match read_memory_blocks(sysroot) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("lsmem: {e}");
            return ExitCode::FAILURE;
        }
    };

    let columns = if args.output_all {
        ALL_COLUMNS.to_vec()
    } else if let Some(ref names) = args.output {
        let mut cols = Vec::new();
        for name in names {
            let name = name.trim();
            match Col::from_name(name) {
                Some(c) => cols.push(c),
                None => {
                    eprintln!("lsmem: unknown column: {name}");
                    return ExitCode::FAILURE;
                }
            }
        }
        cols
    } else {
        DEFAULT_COLUMNS.to_vec()
    };

    let split_cols = if let Some(ref names) = args.split {
        if names.len() == 1 && names[0].eq_ignore_ascii_case("none") {
            Vec::new()
        } else {
            names
                .iter()
                .filter_map(|n| Col::from_name(n.trim()))
                .collect()
        }
    } else {
        DEFAULT_SPLIT.to_vec()
    };

    let ranges = if args.all {
        // --all: each block is its own range
        blocks
            .iter()
            .map(|b| MemRange {
                start_block: b.index,
                end_block: b.index,
                start_addr: b.start_addr(),
                end_addr: b.end_addr(),
                size: b.block_size,
                state: b.state.clone(),
                removable: b.removable,
                node: b.node,
                zones: b.zones.clone(),
            })
            .collect()
    } else {
        merge_blocks(&blocks, &split_cols)
    };

    let human = !args.bytes;
    let show_summary = match args.summary {
        SummaryMode::Never => false,
        SummaryMode::Only => true,
        SummaryMode::Always => !args.raw && !args.pairs && !args.json,
    };
    let show_table = !matches!(args.summary, SummaryMode::Only);

    if show_table {
        let mut table = Table::new();
        table.name_set("memory");

        if args.json {
            table.output_mode_set(OutputMode::Json);
        } else if args.pairs {
            table.output_mode_set(OutputMode::Export);
        } else if args.raw {
            table.output_mode_set(OutputMode::Raw);
        }

        if args.noheadings {
            table.headings_set(false);
        }

        for col in &columns {
            let idx = table.new_column(col.name());
            table.column_mut(idx).unwrap().width_hint_set(col.whint());
            if col.is_right() {
                table.column_mut(idx).unwrap().right_set(true);
            }
        }

        for range in &ranges {
            let line_id = table.new_line(None);
            let line = table.line_mut(line_id);

            for (ci, col) in columns.iter().enumerate() {
                let val = match col {
                    Col::Range => format!(
                        "0x{:016x}-0x{:016x}",
                        range.start_addr, range.end_addr
                    ),
                    Col::Size => format_size(range.size, human),
                    Col::State => range.state.clone(),
                    Col::Removable => {
                        if range.removable { "yes" } else { "no" }.to_string()
                    }
                    Col::Block => {
                        if range.start_block == range.end_block {
                            range.start_block.to_string()
                        } else {
                            format!("{}-{}", range.start_block, range.end_block)
                        }
                    }
                    Col::Node => {
                        range.node.map_or(String::new(), |n| n.to_string())
                    }
                    Col::Zones => range.zones.clone(),
                };
                line.data_set(ci, &val);
            }
        }

        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        if let Err(e) = print_table(&table, &mut out) {
            eprintln!("lsmem: {e}");
            return ExitCode::FAILURE;
        }
    }

    if show_summary {
        let total_online: u64 = blocks
            .iter()
            .filter(|b| b.state == "online")
            .map(|b| b.block_size)
            .sum();
        let total_offline: u64 = blocks
            .iter()
            .filter(|b| b.state != "online")
            .map(|b| b.block_size)
            .sum();

        if show_table {
            println!();
        }
        let w = 38;
        println!(
            "Memory block size:{:>pad$}",
            format_size(block_size, human),
            pad = w - 18,
        );
        println!(
            "Total online memory:{:>pad$}",
            format_size(total_online, human),
            pad = w - 20,
        );
        println!(
            "Total offline memory:{:>pad$}",
            format_size(total_offline, human),
            pad = w - 21,
        );
    }

    ExitCode::SUCCESS
}