Add individual CPU interface

This commit is contained in:
NGnius (Graham) 2024-06-19 20:10:32 -04:00
parent bafaccd54d
commit 7aa18d0294
9 changed files with 1417 additions and 84 deletions

View file

@ -8,4 +8,4 @@ description = "Power toolbox for Linux devices"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
sysfuss = { version = "0.3", path = "../../../sysfs-nav" } sysfuss = { version = "0.4", path = "../../../sysfs-nav" }

View file

@ -0,0 +1,37 @@
/// Boolean value represented as the number 1 or 0
#[derive(PartialEq, Eq, Debug)]
pub struct BoolNum(pub bool);
#[derive(Copy, Clone, Debug)]
pub struct ParseBoolNumError;
impl core::fmt::Display for ParseBoolNumError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "provided string was not `1` or `0`")
}
}
impl std::error::Error for ParseBoolNumError {}
impl core::str::FromStr for BoolNum {
type Err = ParseBoolNumError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.chars().next() {
Some('0') => Ok(Self(false)),
Some('1') => Ok(Self(true)),
Some(_) => Err(ParseBoolNumError),
None => Err(ParseBoolNumError),
}
}
}
impl core::fmt::Display for BoolNum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = match self.0 {
true => '1',
false => '0',
};
write!(f, "{}", c)
}
}

View file

@ -1,7 +1,13 @@
//! Primitive types for power control values //! Primitive types for power control values
mod boolean_number;
pub use boolean_number::BoolNum;
mod range; mod range;
pub use range::{Range, RangeList, RangeListParseErr, RangeListItem}; pub use range::{Range, RangeList, RangeListParseErr, RangeListItem, RangeListIter};
mod space_separated_list;
pub use space_separated_list::SpacedList;
mod value; mod value;
pub use value::Value; pub use value::Value;

View file

@ -37,6 +37,70 @@ impl <E> From<E> for RangeListParseErr<E> {
} }
} }
impl RangeList<usize> {
/// Convert range list into iterable and specificy assumption about range inclusiveness
/// (true -> ranges will be from min up to and including max; false -> from min up to max)
pub fn into_iter(self, inclusive: bool) -> RangeListIter<usize> {
RangeListIter {
range_list: self,
index: 0,
inclusive,
inner: None,
}
}
}
/// Iterator implementation for RangeList
pub struct RangeListIter<N> {
range_list: RangeList<N>,
index: usize,
inclusive: bool,
inner: Option<Box<dyn core::iter::Iterator<Item=N>>>,
}
impl core::iter::IntoIterator for RangeList<usize> {
type Item = usize;
type IntoIter = RangeListIter<usize>;
fn into_iter(self) -> Self::IntoIter {
RangeListIter {
range_list: self,
index: 0,
inclusive: true,
inner: None,
}
}
}
impl core::iter::Iterator for RangeListIter<usize> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut inner) = self.inner.take() {
if let Some(next) = inner.next() {
self.inner = Some(inner);
return Some(next);
}
}
if let Some(next_element) = self.range_list.items.get(self.index) {
self.index += 1;
match next_element {
RangeListItem::Single(num) => Some(*num),
RangeListItem::Range(range) => {
if self.inclusive {
self.inner = Some(Box::new(range.min..=range.max))
} else {
self.inner = Some(Box::new(range.min..range.max))
}
self.next()
}
}
} else {
None
}
}
}
impl <E: core::fmt::Display> core::fmt::Display for RangeListParseErr<E> { impl <E: core::fmt::Display> core::fmt::Display for RangeListParseErr<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
@ -126,4 +190,18 @@ mod test {
let parsed: Result<RangeList<usize>, _> = "1,2-".parse(); let parsed: Result<RangeList<usize>, _> = "1,2-".parse();
assert!(parsed.is_err_and(|e| matches!(e, RangeListParseErr::UnexpectedEnd))) assert!(parsed.is_err_and(|e| matches!(e, RangeListParseErr::UnexpectedEnd)))
} }
#[test]
fn iter_range() {
let range_list = RangeList {
items: vec![
RangeListItem::Single(2),
RangeListItem::Range(Range { min: 4, max: 7 }),
RangeListItem::Single(3),
RangeListItem::Range(Range { min: 20, max: 24 }),
],
};
let actual: Vec<usize> = range_list.into_iter(true).collect();
assert_eq!(actual, vec![2, 4, 5, 6, 7, 3, 20, 21, 22, 23, 24])
}
} }

View file

@ -0,0 +1,35 @@
use std::str::FromStr;
/// A list of items separated by a list
pub struct SpacedList<T>(pub Vec<T>);
impl <T: FromStr> FromStr for SpacedList<T> {
type Err = <T as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut results = Vec::new();
for chars in s.split(' ') {
if !chars.is_empty() {
results.push(T::from_str(chars)?);
}
}
Ok(Self(results))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_list_of_str() {
let strings: SpacedList<String> = "abcd wxyz".parse().expect("fail");
assert_eq!(strings.0, vec!["abcd", "wxyz"]);
}
#[test]
fn parse_list_of_num() {
let strings: SpacedList<usize> = "1 2 3 4 5 6 7 8 9 10 11".parse().expect("fail");
assert_eq!(strings.0, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
}
}

View file

@ -7,4 +7,4 @@ description = "Power toolbox for processors"
[dependencies] [dependencies]
powerbox = { version = "0.1", path = "../core" } powerbox = { version = "0.1", path = "../core" }
sysfuss = { version = "0.3", path = "../../../sysfs-nav" } sysfuss = { version = "0.4", path = "../../../sysfs-nav" }

View file

@ -4,7 +4,7 @@ use sysfuss::{BasicEntityPath, SysEntityAttributesExt};
use super::{CpuPower, CpuPowerOp}; use super::{CpuPower, CpuPowerOp};
const DEFAULT_CPU_ROOT: &str = "/sys/devices/system/cpu"; pub(super) const DEFAULT_CPU_ROOT: &str = "/sys/devices/system/cpu";
const CPUS_PRESENT: &str = "present"; const CPUS_PRESENT: &str = "present";
const CPUS_POSSIBLE: &str = "possible"; const CPUS_POSSIBLE: &str = "possible";
const CPUS_KERNEL_MAX: &str = "kernel_max"; const CPUS_KERNEL_MAX: &str = "kernel_max";
@ -20,7 +20,7 @@ pub struct BasicCpus {
impl BasicCpus { impl BasicCpus {
fn is_online(&self) -> bool { fn is_online(&self) -> bool {
self.sysfs.attribute::<String, _>(CPUS_PRESENT).is_ok_and(|s| s.trim_end() != "") self.sysfs.attribute::<String>(CPUS_PRESENT).is_ok_and(|s| s.trim_end() != "")
} }
fn is_exists(&self) -> bool { fn is_exists(&self) -> bool {
@ -204,7 +204,7 @@ impl Power<GetSMT, bool> for BasicCpus {
fn act(&self, _: GetSMT) -> Result<bool, powerbox::PowerError> { fn act(&self, _: GetSMT) -> Result<bool, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_SMT_ACTIVE) { if self.sysfs.exists(&CPUS_SMT_ACTIVE) {
match self.sysfs.attribute::<String, _>(CPUS_SMT_ACTIVE) { match self.sysfs.attribute::<String>(CPUS_SMT_ACTIVE) {
Ok(s) => Ok(s.trim_end() == "1"), Ok(s) => Ok(s.trim_end() == "1"),
Err(sysfuss::EitherErr2::First(e)) => Err(powerbox::PowerError::Io(e)), Err(sysfuss::EitherErr2::First(e)) => Err(powerbox::PowerError::Io(e)),
Err(sysfuss::EitherErr2::Second(_)) => panic!("Infallible error"), Err(sysfuss::EitherErr2::Second(_)) => panic!("Infallible error"),
@ -298,7 +298,7 @@ impl Power<GetPresent, RangeList<usize>> for BasicCpus {
fn act(&self, _: GetPresent) -> Result<RangeList<usize>, powerbox::PowerError> { fn act(&self, _: GetPresent) -> Result<RangeList<usize>, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_PRESENT) { if self.sysfs.exists(&CPUS_PRESENT) {
self.sysfs.attribute::<RangeList<usize>, _>(CPUS_PRESENT).map_err(|e| match e { self.sysfs.attribute::<RangeList<usize>>(CPUS_PRESENT).map_err(|e| match e {
sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e), sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e),
sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown, sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown,
}) })
@ -353,7 +353,7 @@ impl Power<GetPossible, RangeList<usize>> for BasicCpus {
fn act(&self, _: GetPossible) -> Result<RangeList<usize>, powerbox::PowerError> { fn act(&self, _: GetPossible) -> Result<RangeList<usize>, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_POSSIBLE) { if self.sysfs.exists(&CPUS_POSSIBLE) {
self.sysfs.attribute::<RangeList<usize>, _>(CPUS_POSSIBLE).map_err(|e| match e { self.sysfs.attribute::<RangeList<usize>>(CPUS_POSSIBLE).map_err(|e| match e {
sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e), sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e),
sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown, sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown,
}) })
@ -410,7 +410,7 @@ impl Power<GetKernelMax, usize> for BasicCpus {
fn act(&self, _: GetKernelMax) -> Result<usize, powerbox::PowerError> { fn act(&self, _: GetKernelMax) -> Result<usize, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_KERNEL_MAX) { if self.sysfs.exists(&CPUS_KERNEL_MAX) {
self.sysfs.attribute::<usize, _>(CPUS_KERNEL_MAX).map_err(|e| match e { self.sysfs.attribute::<usize>(CPUS_KERNEL_MAX).map_err(|e| match e {
sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e), sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e),
sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown, sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown,
}) })
@ -464,7 +464,7 @@ impl Power<GetCpusOnline, RangeList<usize>> for BasicCpus {
fn act(&self, _: GetCpusOnline) -> Result<RangeList<usize>, powerbox::PowerError> { fn act(&self, _: GetCpusOnline) -> Result<RangeList<usize>, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_ONLINE) { if self.sysfs.exists(&CPUS_ONLINE) {
self.sysfs.attribute::<RangeList<usize>, _>(CPUS_ONLINE).map_err(|e| match e { self.sysfs.attribute::<RangeList<usize>>(CPUS_ONLINE).map_err(|e| match e {
sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e), sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e),
sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown, sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown,
}) })
@ -519,7 +519,7 @@ impl Power<GetCpusOffline, RangeList<usize>> for BasicCpus {
fn act(&self, _: GetCpusOffline) -> Result<RangeList<usize>, powerbox::PowerError> { fn act(&self, _: GetCpusOffline) -> Result<RangeList<usize>, powerbox::PowerError> {
if self.sysfs.exists(&CPUS_OFFLINE) { if self.sysfs.exists(&CPUS_OFFLINE) {
self.sysfs.attribute::<RangeList<usize>, _>(CPUS_OFFLINE).map_err(|e| match e { self.sysfs.attribute::<RangeList<usize>>(CPUS_OFFLINE).map_err(|e| match e {
sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e), sysfuss::EitherErr2::First(e) => powerbox::PowerError::Io(e),
sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown, sysfuss::EitherErr2::Second(_) => powerbox::PowerError::Unknown,
}) })
@ -549,85 +549,68 @@ mod test_cpus_offline {
} }
} }
/// General single CPU functionality /// Get CPU by index
pub struct BasicCpu { pub struct GetCpu(usize);
impl PowerOp for GetCpu {
fn is_eq_op(&self, _: &Self) -> bool {
true
}
} }
pub enum BasicCpuOp { impl CpuPowerOp for GetCpu {}
Online(Online),
CpuFreq(CpuFreq), impl Power<GetCpu, super::BasicCpu> for BasicCpus {
//CpuIdle(), fn is_on(&self) -> bool {
//ACPI(), self.is_online()
} }
pub struct SetCpuOnline(pub bool); fn is_available(&self) -> bool {
pub struct GetCpuOnline; self.is_exists()
pub enum Online {
Get(GetCpuOnline),
Set(SetCpuOnline),
} }
pub struct GetAffectedCpus; // range or number?? fn supported_operations(&self) -> Box<dyn core::iter::Iterator<Item=GetCpu>> {
pub struct GetRelatedCpus; // range or number?? if let Ok(possible_cpus) = self.act(GetPossible) {
pub enum CpuFreq { Box::new(possible_cpus.into_iter(true)
AffectedCpus(GetAffectedCpus), .map(|index| GetCpu(index)))
RelatedCpus(GetRelatedCpus), } else {
CpuInfo(CpuInfo), Box::new(core::iter::empty())
Energy(EnergyPerf), }
Scaling(),
} }
pub struct GetCpuInfoMinFreq; // number fn act(&self, i: GetCpu) -> Result<super::BasicCpu, powerbox::PowerError> {
pub struct GetCpuInfoMaxFreq; // number Ok(super::BasicCpu::with_root(self.sysfs.as_ref().join(format!("cpu{}", i.0))))
pub enum CpuInfo { }
MinFreq(GetCpuInfoMinFreq),
MaxFreq(GetCpuInfoMaxFreq),
} }
pub struct GetEnergyPerfAvailablePreferences; // list of string /// Get all CPUs present in the system
pub enum EnergyPerf { pub struct GetCpus;
AvailablePreferences(GetEnergyPerfAvailablePreferences), impl PowerOp for GetCpus {
Preference(EnergyPerfPreference), fn is_eq_op(&self, _: &Self) -> bool {
true
}
} }
pub struct GetEnergyPerfPreference; // string impl CpuPowerOp for GetCpus {}
pub struct SetEnergyPerfPreference(String);
pub enum EnergyPerfPreference { impl Power<GetCpus, Vec<super::BasicCpu>> for BasicCpus {
Get(GetEnergyPerfPreference), fn is_on(&self) -> bool {
Set(SetEnergyPerfPreference) self.is_online()
} }
pub struct GetScalingAvailableGovernors; // list of string fn is_available(&self) -> bool {
pub struct GetScalingCurFreq; // number self.is_exists()
pub struct GetScalingDriver; // string
pub enum Scaling {
AvailableGovernors(GetScalingAvailableGovernors),
CurFreq(GetScalingCurFreq),
Driver(GetScalingDriver),
Governor(ScalingGovernor),
MaxFreq(ScalingMaxFreq),
MinFreq(ScalingMinFreq),
//Setspeed(),
} }
pub struct GetScalingGovernor; // string fn supported_operations(&self) -> Box<dyn core::iter::Iterator<Item=GetCpus>> {
pub struct SetScalingGovernor(String); Box::new(core::iter::once(GetCpus))
pub enum ScalingGovernor {
Get(GetScalingGovernor),
Set(SetScalingGovernor),
} }
pub struct GetScalingMaxFreq; // number fn act(&self, _: GetCpus) -> Result<Vec<super::BasicCpu>, powerbox::PowerError> {
pub struct SetScalingMaxFreq(usize); let possible_cpus: Vec<_> = Power::<GetCpu, _>::supported_operations(self).collect();
pub enum ScalingMaxFreq { let mut results = Vec::with_capacity(possible_cpus.len());
Get(GetScalingMaxFreq), for cpu in possible_cpus {
Set(SetScalingMaxFreq), results.push(Power::<GetCpu, _>::act(self, cpu)?);
}
Ok(results)
} }
pub struct GetScalingMinFreq; // number
pub struct SetScalingMinFreq(usize);
pub enum ScalingMinFreq {
Get(GetScalingMinFreq),
Set(SetScalingMinFreq),
} }

File diff suppressed because it is too large Load diff

View file

@ -3,5 +3,9 @@ mod cpu_trait;
pub use cpu_trait::{CpuPower, CpuPowerOp}; pub use cpu_trait::{CpuPower, CpuPowerOp};
#[allow(missing_docs)] #[allow(missing_docs)]
pub mod basic; pub mod basic_general;
pub use basic::{BasicCpus, BasicCpu}; pub use basic_general::BasicCpus;
#[allow(missing_docs)]
pub mod basic_single;
pub use basic_single::BasicCpu;