Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 142 additions & 61 deletions src/uu/lscpu/src/sysfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ pub fn system_path(root: &Path, path: &str) -> PathBuf {
root.join(path.trim_start_matches('/'))
}

fn read_trimmed(path: &Path) -> Option<String> {
fs::read_to_string(path)
.ok()
.map(|contents| contents.trim().to_string())
}

pub struct CpuVulnerability {
pub name: String,
pub mitigation: String,
Expand All @@ -34,7 +40,9 @@ pub struct Cpu {
// i64 rather than usize: the kernel reports -1 when the architecture
// does not expose physical package information
pub pkg_id: i64,
pub core_id: usize,
// `None` when sysfs does not report a core id for this CPU; such a CPU is
// treated as its own core instead of falling back to its index.
pub core_id: Option<usize>,
pub caches: Vec<CpuCache>,
}

Expand All @@ -60,22 +68,20 @@ impl CpuTopology {
pub fn new(root: &Path) -> UResult<Self> {
let mut out: Vec<Cpu> = vec![];

let online_cpus = parse_cpu_list(&read_online_cpus(root)?);
let online_cpus = parse_cpu_list(&read_online_cpus(root)?)?;

for cpu_index in online_cpus {
let cpu_dir = system_path(root, &format!("/sys/devices/system/cpu/cpu{cpu_index}/"));

let pkg_id = fs::read_to_string(cpu_dir.join("topology/physical_package_id"))
.unwrap()
.trim()
.parse::<i64>()
.unwrap();
// Keep reporting partial topology when sysfs is incomplete: -1
// means an unknown package, and a CPU without core_id is treated
// as its own core instead of failing the whole command.
let pkg_id = read_trimmed(&cpu_dir.join("topology/physical_package_id"))
.and_then(|value| value.parse::<i64>().ok())
.unwrap_or(-1);

let core_id = fs::read_to_string(cpu_dir.join("topology/core_id"))
.unwrap()
.trim()
.parse::<usize>()
.unwrap();
let core_id = read_trimmed(&cpu_dir.join("topology/core_id"))
.and_then(|value| value.parse::<usize>().ok());

let caches = read_cpu_caches(root, cpu_index);

Expand All @@ -98,8 +104,18 @@ impl CpuTopology {
}

pub fn core_count(&self) -> usize {
let core_ids: HashSet<_> = self.cpus.iter().map(|cpu| cpu.core_id).collect();
core_ids.len()
// core_id is only unique within a package, so known cores are keyed by
// (package, core) to avoid merging same-numbered cores from different
// sockets. A CPU without a core_id is counted as its own core; using
// its index as the id could collide with a real core_id of another
// CPU.
let known_cores: HashSet<(i64, usize)> = self
.cpus
.iter()
.filter_map(|cpu| cpu.core_id.map(|core_id| (cpu.pkg_id, core_id)))
.collect();
let unknown_cores = self.cpus.iter().filter(|cpu| cpu.core_id.is_none()).count();
known_cores.len() + unknown_cores
}
}

Expand All @@ -108,8 +124,8 @@ impl CacheSize {
Self(size)
}

fn parse(s: &str) -> Self {
Self(parse_size::parse_size_u64(s).expect("Could not parse cache size"))
fn parse(s: &str) -> Option<Self> {
parse_size::parse_size_u64(s).ok().map(Self)
}

pub fn size_bytes(&self) -> u64 {
Expand Down Expand Up @@ -145,7 +161,9 @@ pub fn read_online_cpus(root: &Path) -> UResult<String> {

fn read_cpu_caches(root: &Path, cpu_index: usize) -> Vec<CpuCache> {
let cpu_dir = system_path(root, &format!("/sys/devices/system/cpu/cpu{cpu_index}/"));
let cache_dir = fs::read_dir(cpu_dir.join("cache")).unwrap();
let Ok(cache_dir) = fs::read_dir(cpu_dir.join("cache")) else {
return Vec::new();
};
let cache_paths = cache_dir
.flatten()
.filter(|x| x.path().is_dir())
Expand All @@ -154,26 +172,34 @@ fn read_cpu_caches(root: &Path, cpu_index: usize) -> Vec<CpuCache> {
let mut caches: Vec<CpuCache> = vec![];

for cache_path in cache_paths {
let type_string = fs::read_to_string(cache_path.join("type")).unwrap();

let c_type = match type_string.trim() {
"Unified" => CacheType::Unified,
"Data" => CacheType::Data,
"Instruction" => CacheType::Instruction,
_ => panic!("Unrecognized cache type: {type_string}"),
// Ignore entries with unknown or missing metadata rather than failing
// the command; new kernel cache types should not break lscpu.
let Some(c_type) =
read_trimmed(&cache_path.join("type")).and_then(|value| match value.as_str() {
"Unified" => Some(CacheType::Unified),
"Data" => Some(CacheType::Data),
"Instruction" => Some(CacheType::Instruction),
_ => None,
})
else {
continue;
};

let c_level = fs::read_to_string(cache_path.join("level"))
.map(|s| s.trim().parse::<usize>().unwrap())
.unwrap();
let Some(c_level) =
read_trimmed(&cache_path.join("level")).and_then(|value| value.parse::<usize>().ok())
else {
continue;
};

let size_string = fs::read_to_string(cache_path.join("size")).unwrap();
let c_size = CacheSize::parse(size_string.trim());
let Some(c_size) =
read_trimmed(&cache_path.join("size")).and_then(|value| CacheSize::parse(&value))
else {
continue;
};

let shared_cpu_map = fs::read_to_string(cache_path.join("shared_cpu_map"))
.unwrap()
.trim()
.to_string();
let Some(shared_cpu_map) = read_trimmed(&cache_path.join("shared_cpu_map")) else {
continue;
};

caches.push(CpuCache {
level: c_level,
Expand Down Expand Up @@ -206,10 +232,12 @@ pub fn read_cpu_vulnerabilities(root: &Path) -> Vec<CpuVulnerability> {

for file in files {
if let Ok(content) = fs::read_to_string(&file) {
let name = file.file_name().unwrap().to_str().unwrap();
let Some(name) = file.file_name().and_then(|name| name.to_str()) else {
continue;
};

out.push(CpuVulnerability {
name: (name[..1].to_uppercase() + &name[1..]).replace("_", " "),
name: vulnerability_name(name),
mitigation: content.trim().to_string(),
});
}
Expand All @@ -230,48 +258,83 @@ pub fn read_cpu_byte_order(root: &Path) -> Option<&'static str> {
None
}

fn vulnerability_name(file_name: &str) -> String {
let mut chars = file_name.chars();
let Some(first) = chars.next() else {
return String::new();
};

let mut name = first.to_uppercase().collect::<String>();
name.push_str(chars.as_str());
name.replace('_', " ")
}

fn parse_cpu_index(value: &str) -> UResult<usize> {
value
.trim()
.parse::<usize>()
.map_err(|_| USimpleError::new(1, format!("Invalid CPU index value: {value}")))
}

// Takes in a human-readable list of CPUs, and returns a list of indices parsed from that list
// These can come in the form of a plain range like `X-Y`, or a comma-separated ranges and indices ie. `1,3-4,7-8,10`
// Kernel docs with examples: https://www.kernel.org/doc/html/latest/admin-guide/cputopology.html
fn parse_cpu_list(list: &str) -> Vec<usize> {
fn parse_cpu_list(list: &str) -> UResult<Vec<usize>> {
let mut out: Vec<usize> = vec![];
let list = list.trim();

if list.is_empty() {
return out;
return Ok(out);
}

for part in list.trim().split(",") {
if part.contains("-") {
let bounds: Vec<_> = part.split("-").flat_map(|x| x.parse::<usize>()).collect();
assert_eq!(bounds.len(), 2);
for idx in bounds[0]..bounds[1] + 1 {
out.push(idx)
for part in list.split(',') {
let part = part.trim();

if part.is_empty() {
return Err(USimpleError::new(1, "Invalid empty CPU list entry"));
}

if let Some((start, end)) = part.split_once('-') {
let start = parse_cpu_index(start)?;
let end = parse_cpu_index(end)?;

if start > end {
return Err(USimpleError::new(1, format!("Invalid CPU range: {part}")));
}

out.extend(start..=end);
} else {
let idx = part.parse::<usize>().expect("Invalid CPU index value");
out.push(idx);
out.push(parse_cpu_index(part)?);
}
}

out
Ok(out)
}

#[test]
fn test_parse_cache_size() {
assert_eq!(CacheSize::parse("512").size_bytes(), 512);
assert_eq!(CacheSize::parse("1K").size_bytes(), 1024);
assert_eq!(CacheSize::parse("1M").size_bytes(), 1024 * 1024);
assert_eq!(CacheSize::parse("1G").size_bytes(), 1024 * 1024 * 1024);
assert_eq!(CacheSize::parse("512").unwrap().size_bytes(), 512);
assert_eq!(CacheSize::parse("1K").unwrap().size_bytes(), 1024);
assert_eq!(CacheSize::parse("1M").unwrap().size_bytes(), 1024 * 1024);
assert_eq!(
CacheSize::parse("1T").size_bytes(),
CacheSize::parse("1G").unwrap().size_bytes(),
1024 * 1024 * 1024
);
assert_eq!(
CacheSize::parse("1T").unwrap().size_bytes(),
1024 * 1024 * 1024 * 1024
);
assert_eq!(CacheSize::parse("123K").size_bytes(), 123 * 1024);
assert_eq!(CacheSize::parse("32M").size_bytes(), 32 * 1024 * 1024);
assert_eq!(CacheSize::parse("123K").unwrap().size_bytes(), 123 * 1024);
assert_eq!(
CacheSize::parse("32M").unwrap().size_bytes(),
32 * 1024 * 1024
);
assert_eq!(
CacheSize::parse("345G").size_bytes(),
CacheSize::parse("345G").unwrap().size_bytes(),
345 * 1024 * 1024 * 1024
);

assert!(CacheSize::parse("not-a-size").is_none());
}

#[test]
Expand Down Expand Up @@ -302,13 +365,13 @@ fn test_socket_count_with_unknown_package_id() {
Cpu {
_index: 0,
pkg_id: -1,
core_id: 0,
core_id: Some(0),
caches: vec![],
},
Cpu {
_index: 1,
pkg_id: -1,
core_id: 1,
core_id: Some(1),
caches: vec![],
},
],
Expand All @@ -317,17 +380,35 @@ fn test_socket_count_with_unknown_package_id() {
assert_eq!(topology.core_count(), 2);
}

#[test]
fn test_vulnerability_name() {
assert_eq!(vulnerability_name("spectre_v1"), "Spectre v1");
assert_eq!(vulnerability_name("meltdown"), "Meltdown");
assert_eq!(vulnerability_name(""), "");
}

#[test]
fn test_parse_cpu_list() {
assert_eq!(parse_cpu_list(""), Vec::<usize>::new());
assert_eq!(parse_cpu_list("1-3"), Vec::<usize>::from([1, 2, 3]));
assert_eq!(parse_cpu_list("1,2,3"), Vec::<usize>::from([1, 2, 3]));
assert_eq!(parse_cpu_list("").unwrap(), Vec::<usize>::new());
assert_eq!(
parse_cpu_list("1,3-6,8"),
parse_cpu_list("1-3").unwrap(),
Vec::<usize>::from([1, 2, 3])
);
assert_eq!(
parse_cpu_list("1,2,3").unwrap(),
Vec::<usize>::from([1, 2, 3])
);
assert_eq!(
parse_cpu_list("1,3-6,8").unwrap(),
Vec::<usize>::from([1, 3, 4, 5, 6, 8])
);
assert_eq!(
parse_cpu_list("1-2,3-5,7"),
parse_cpu_list("1-2,3-5,7").unwrap(),
Vec::<usize>::from([1, 2, 3, 4, 5, 7])
);

assert!(parse_cpu_list("1-").is_err());
assert!(parse_cpu_list("a").is_err());
assert!(parse_cpu_list("3-1").is_err());
assert!(parse_cpu_list("1,,2").is_err());
}
Loading
Loading