From 4a92f25127ac04c759d9790f4b1de4d81427ef2d Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Tue, 1 Oct 2024 10:39:00 -0400 Subject: [PATCH] Reduce duplication in `{nr,possible}_cpus` --- aya-log/src/lib.rs | 2 +- aya/src/bpf.rs | 14 ++++++-------- aya/src/maps/mod.rs | 23 ++++++++++++----------- aya/src/util.rs | 39 ++++++++++++++------------------------- xtask/public-api/aya.txt | 4 ++-- 5 files changed, 35 insertions(+), 47 deletions(-) diff --git a/aya-log/src/lib.rs b/aya-log/src/lib.rs index 37ec1b2c..52a89756 100644 --- a/aya-log/src/lib.rs +++ b/aya-log/src/lib.rs @@ -161,7 +161,7 @@ impl EbpfLogger { let mut logs: AsyncPerfEventArray<_> = map.try_into()?; let logger = Arc::new(logger); - for cpu_id in online_cpus().map_err(Error::InvalidOnlineCpu)? { + for cpu_id in online_cpus().map_err(|(_, error)| Error::InvalidOnlineCpu(error))? { let mut buf = logs.open(cpu_id, None)?; let log = logger.clone(); diff --git a/aya/src/bpf.rs b/aya/src/bpf.rs index e9cad2b5..58e2f58d 100644 --- a/aya/src/bpf.rs +++ b/aya/src/bpf.rs @@ -43,7 +43,7 @@ use crate::{ is_info_map_ids_supported, is_perf_link_supported, is_probe_read_kernel_supported, is_prog_id_supported, is_prog_name_supported, retry_with_verifier_logs, }, - util::{bytes_of, bytes_of_slice, page_size, possible_cpus, POSSIBLE_CPUS}, + util::{bytes_of, bytes_of_slice, nr_cpus, page_size}, }; pub(crate) const BPF_OBJ_NAME_LEN: usize = 16; @@ -465,13 +465,11 @@ impl<'a> EbpfLoader<'a> { { continue; } - let num_cpus = || -> Result { - Ok(possible_cpus() - .map_err(|error| EbpfError::FileError { - path: PathBuf::from(POSSIBLE_CPUS), - error, - })? - .len() as u32) + let num_cpus = || { + Ok(nr_cpus().map_err(|(path, error)| EbpfError::FileError { + path: PathBuf::from(path), + error, + })? as u32) }; let map_type: bpf_map_type = obj.map_type().try_into().map_err(MapError::from)?; if let Some(max_entries) = max_entries_override( diff --git a/aya/src/maps/mod.rs b/aya/src/maps/mod.rs index e74289bb..fb53c530 100644 --- a/aya/src/maps/mod.rs +++ b/aya/src/maps/mod.rs @@ -569,9 +569,9 @@ impl MapData { // // Otherwise, when the value is `0` or too large, we set it to the number of CPUs. if obj.map_type() == bpf_map_type::BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32 { - let ncpus = nr_cpus().map_err(MapError::IoError)? as u32; - if obj.max_entries() == 0 || obj.max_entries() > ncpus { - obj.set_max_entries(ncpus); + let nr_cpus = nr_cpus().map_err(|(_, error)| MapError::IoError(error))? as u32; + if obj.max_entries() == 0 || obj.max_entries() > nr_cpus { + obj.set_max_entries(nr_cpus); } }; @@ -891,7 +891,7 @@ impl TryFrom> for PerCpuValues { type Error = io::Error; fn try_from(values: Vec) -> Result { - let nr_cpus = nr_cpus()?; + let nr_cpus = nr_cpus().map_err(|(_, error)| error)?; if values.len() != nr_cpus { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -907,8 +907,9 @@ impl TryFrom> for PerCpuValues { impl PerCpuValues { pub(crate) fn alloc_kernel_mem() -> Result { let value_size = (mem::size_of::() + 7) & !7; + let nr_cpus = nr_cpus().map_err(|(_, error)| error)?; Ok(PerCpuKernelMem { - bytes: vec![0u8; nr_cpus()? * value_size], + bytes: vec![0u8; nr_cpus * value_size], }) } @@ -1086,9 +1087,9 @@ mod tests { _ => Err((-1, io::Error::from_raw_os_error(EFAULT))), }); - let ncpus = nr_cpus().unwrap(); + let nr_cpus = nr_cpus().unwrap(); - // Create with max_entries > ncpus is clamped to ncpus + // Create with max_entries > nr_cpus is clamped to nr_cpus assert_matches!( MapData::create(test_utils::new_obj_map_with_max_entries::( crate::generated::bpf_map_type::BPF_MAP_TYPE_PERF_EVENT_ARRAY, @@ -1099,11 +1100,11 @@ mod tests { fd, }) => { assert_eq!(fd.as_fd().as_raw_fd(), crate::MockableFd::mock_signed_fd()); - assert_eq!(obj.max_entries(), ncpus as u32) + assert_eq!(obj.max_entries(), nr_cpus as u32) } ); - // Create with max_entries = 0 is set to ncpus + // Create with max_entries = 0 is set to nr_cpus assert_matches!( MapData::create(test_utils::new_obj_map_with_max_entries::( crate::generated::bpf_map_type::BPF_MAP_TYPE_PERF_EVENT_ARRAY, @@ -1114,11 +1115,11 @@ mod tests { fd, }) => { assert_eq!(fd.as_fd().as_raw_fd(), crate::MockableFd::mock_signed_fd()); - assert_eq!(obj.max_entries(), ncpus as u32) + assert_eq!(obj.max_entries(), nr_cpus as u32) } ); - // Create with max_entries < ncpus is unchanged + // Create with max_entries < nr_cpus is unchanged assert_matches!( MapData::create(test_utils::new_obj_map_with_max_entries::( crate::generated::bpf_map_type::BPF_MAP_TYPE_PERF_EVENT_ARRAY, diff --git a/aya/src/util.rs b/aya/src/util.rs index 18de6002..10fc15ef 100644 --- a/aya/src/util.rs +++ b/aya/src/util.rs @@ -185,40 +185,29 @@ impl Display for KernelVersion { } const ONLINE_CPUS: &str = "/sys/devices/system/cpu/online"; -pub(crate) const POSSIBLE_CPUS: &str = "/sys/devices/system/cpu/possible"; +const POSSIBLE_CPUS: &str = "/sys/devices/system/cpu/possible"; /// Returns the numeric IDs of the CPUs currently online. -pub fn online_cpus() -> Result, io::Error> { - let data = fs::read_to_string(ONLINE_CPUS)?; - parse_cpu_ranges(data.trim()).map_err(|_| { - io::Error::new( - io::ErrorKind::Other, - format!("unexpected {ONLINE_CPUS} format"), - ) - }) +pub fn online_cpus() -> Result, (&'static str, io::Error)> { + read_cpu_ranges(ONLINE_CPUS) } /// Get the number of possible cpus. /// /// See `/sys/devices/system/cpu/possible`. -pub fn nr_cpus() -> Result { - Ok(possible_cpus()?.len()) +pub fn nr_cpus() -> Result { + read_cpu_ranges(POSSIBLE_CPUS).map(|cpus| cpus.len()) } -/// Get the list of possible cpus. -/// -/// See `/sys/devices/system/cpu/possible`. -pub(crate) fn possible_cpus() -> Result, io::Error> { - let data = fs::read_to_string(POSSIBLE_CPUS)?; - parse_cpu_ranges(data.trim()).map_err(|_| { - io::Error::new( - io::ErrorKind::Other, - format!("unexpected {POSSIBLE_CPUS} format"), - ) - }) +fn read_cpu_ranges(path: &'static str) -> Result, (&'static str, io::Error)> { + (|| { + let data = fs::read_to_string(path)?; + parse_cpu_ranges(&data).map_err(|range| io::Error::new(io::ErrorKind::InvalidData, range)) + })() + .map_err(|error| (path, error)) } -fn parse_cpu_ranges(data: &str) -> Result, ()> { +fn parse_cpu_ranges(data: &str) -> Result, &str> { let mut cpus = Vec::new(); for range in data.split(',') { cpus.extend({ @@ -226,10 +215,10 @@ fn parse_cpu_ranges(data: &str) -> Result, ()> { .splitn(2, '-') .map(u32::from_str) .collect::, _>>() - .map_err(|_| ())? + .map_err(|ParseIntError { .. }| range)? .as_slice() { - &[] | &[_, _, _, ..] => return Err(()), + &[] | &[_, _, _, ..] => return Err(range), &[start] => start..=start, &[start, end] => start..=end, } diff --git a/xtask/public-api/aya.txt b/xtask/public-api/aya.txt index c9ff22f4..4cf53afa 100644 --- a/xtask/public-api/aya.txt +++ b/xtask/public-api/aya.txt @@ -9026,8 +9026,8 @@ pub unsafe fn aya::util::KernelVersion::clone_to_uninit(&self, dst: *mut T) impl core::convert::From for aya::util::KernelVersion pub fn aya::util::KernelVersion::from(t: T) -> T pub fn aya::util::kernel_symbols() -> core::result::Result, std::io::error::Error> -pub fn aya::util::nr_cpus() -> core::result::Result -pub fn aya::util::online_cpus() -> core::result::Result, std::io::error::Error> +pub fn aya::util::nr_cpus() -> core::result::Result +pub fn aya::util::online_cpus() -> core::result::Result, (&'static str, std::io::error::Error)> pub fn aya::util::syscall_prefix() -> core::result::Result<&'static str, std::io::error::Error> pub macro aya::include_bytes_aligned! pub enum aya::EbpfError