Merge branch 'endrift/new-api' into 'master'

Implement new API

See merge request holo/steamos-manager!15
This commit is contained in:
Vicki Pfau 2024-04-05 21:39:05 +00:00
commit 1a41e6b05d
17 changed files with 1255 additions and 441 deletions

View file

@ -1,5 +1,6 @@
Copyright © 2023 Collabora Ltd. Copyright © 2023 Collabora Ltd.
Copyright © 2024 Valve Software Copyright © 2024 Valve Software
Copyright © 2024 Igalia S.L.
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in this software and associated documentation files (the “Software”), to deal in

View file

@ -5,5 +5,5 @@
# buffer_size: the size in kilobytes to use for the trace (if on galileo device). # buffer_size: the size in kilobytes to use for the trace (if on galileo device).
# Use 0 for buffer_size since it's only used when mode is 1 # Use 0 for buffer_size since it's only used when mode is 1
busctl call com.steampowered.SteamOSManager1 /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1 SetWifiDebugMode uu 0 0 busctl call com.steampowered.SteamOSManager1.Manager /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1.Manager SetWifiDebugMode uu 0 0

View file

@ -4,5 +4,5 @@
# mode: 1 for on, 0 for off # mode: 1 for on, 0 for off
# buffer_size: the size in kilobytes to use for the trace (if on galileo device). # buffer_size: the size in kilobytes to use for the trace (if on galileo device).
busctl call com.steampowered.SteamOSManager1 /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1 SetWifiDebugMode uu 1 20000 busctl call com.steampowered.SteamOSManager1.Manager /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1.Manager SetWifiDebugMode uu 1 20000

View file

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
# Get wifi debugmode from steamos-manager # Get wifi debugmode from steamos-manager
busctl call com.steampowered.SteamOSManager1 /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1 GetWifiDebugMode busctl call com.steampowered.SteamOSManager1.Manager /com/steampowered/SteamOSManager1 com.steampowered.SteamOSManager1.Manager GetWifiDebugMode

View file

@ -47,7 +47,7 @@
Controls the wifi chip's power management features. Controls the wifi chip's power management features.
Valid states: 0 = Unsupported Feature, 1 = Disabled, 2 = Enabled Valid states: 0 = Disabled, 1 = Enabled
Version available: 7 Version available: 7
--> -->
@ -58,7 +58,7 @@
Controls whether the OS or the BIOS should manage fan speed Controls whether the OS or the BIOS should manage fan speed
Valid states: 0 = Unsupported Feature, 1 = BIOS, 2 = OS Valid states: 0 = BIOS, 1 = OS
Version available: 7 Version available: 7
--> -->
@ -69,7 +69,7 @@
Reports whether the current hardware is supported or not. Reports whether the current hardware is supported or not.
Valid states: 0 = Unsupported Feature, 1 = Unsupported, 2 = Supported Valid states: 0 = Unsupported, 1 = Supported
Version available: 7 Version available: 7
--> -->
@ -100,17 +100,6 @@
<arg type="h" name="descriptor" direction="out"/> <arg type="h" name="descriptor" direction="out"/>
</method> </method>
<!--
BIOSUpdateStatus:
Reports whether a BIOS update is available.
Valid states: 0 = Unsupported Feature, 1 = Up to date, 2 = Update available
Version available: 7
-->
<property name="BIOSUpdateStatus" type="u" access="read"/>
<!-- <!--
UpdateBIOS: UpdateBIOS:
@ -120,30 +109,6 @@
--> -->
<method name="UpdateBIOS" /> <method name="UpdateBIOS" />
<!--
UpdateBIOSProgressNotification:
@percent_completed: Progress percent completed in the range [0-100]
Emitted whenever significant progress is made.
Version available: 7
-->
<signal name="UpdateBIOSProgressNotification">
<arg name="percent_completed" type="u" />
</signal>
<!--
DockUpdateStatus:
Reports whether a Dock Firmware update is available.
Valid states: 0 = Unsupported Feature, 1 = Up to date, 2 = Update available
Version available: 7
-->
<property name="DockUpdateStatus" type="u" access="read"/>
<!-- <!--
UpdateDock: UpdateDock:
@ -153,19 +118,6 @@
--> -->
<method name="UpdateDock" /> <method name="UpdateDock" />
<!--
UpdateDockProgressNotification:
@percent_completed: Progress percent completed in the range [0-100]
Emitted whenever significant progress is made.
Version available: 7
-->
<signal name="UpdateDockProgressNotification">
<arg name="percent_completed" type="u" />
</signal>
<!-- <!--
TrimDevices: TrimDevices:
@ -199,7 +151,7 @@
The current GPU performance level. The current GPU performance level.
Valid states: 0 = Feature Unsupported, 1 = Auto, 2 = Low, 3 = High, 4 = Manual, 5 = Profile Peak Valid states: 0 = Auto, 1 = Low, 2 = High, 3 = Manual, 4 = Profile Peak
Version available: 7 Version available: 7
--> -->
@ -238,7 +190,7 @@
Controls the system TDP limit. Controls the system TDP limit.
Valid states: 0 = Feature Unsupported, or in range of [ TDPLimitMin, TDPLimitMax ] Valid states: In range of [ TDPLimitMin, TDPLimitMax ]
Version available: 7 Version available: 7
--> -->
@ -268,7 +220,7 @@
Whether wifi debug mode is currently enabled. Whether wifi debug mode is currently enabled.
Valid states: 0 = Feature Unsupported, 1 = Disabled, 2 = Enabled Valid states: 0 = Disabled, 1 = Enabled
Version available: 7 Version available: 7
--> -->
@ -289,27 +241,12 @@
<arg type="u" name="buffer_size" direction="in"/> <arg type="u" name="buffer_size" direction="in"/>
</method> </method>
<!--
CaptureWifiDebugTrace:
@path: Output path to write the file
Captures the current contents of the wifi debug trace and dumps it
into @path. The buffers will be emptied and trace capture will resume
after this call returns.
Version available: 7
-->
<method name="CaptureWifiDebugTrace">
<arg type="s" name="path" direction="in"/>
</method>
<!-- <!--
WifiBackend: WifiBackend:
Controls which Wifi backend is used by NetworkManager Controls which Wifi backend is used by NetworkManager
Valid states: 0 = Feature Unsupported, 1 = iwd, 2 = wpa_supplicant Valid states: 0 = iwd, 1 = wpa_supplicant
Version available: 7 Version available: 7
--> -->

View file

@ -9,8 +9,8 @@
<allow own="com.steampowered.SteamOSManager1"/> <allow own="com.steampowered.SteamOSManager1"/>
</policy> </policy>
<!-- Anyone can send messages to the service --> <!-- Anyone can send messages to the service Manager object -->
<policy context="default"> <policy context="default">
<allow send_destination="com.steampowered.SteamOSManager1"/> <allow send_destination="com.steampowered.SteamOSManager1.Manager"/>
</policy> </policy>
</busconfig> </busconfig>

View file

@ -5,7 +5,7 @@ After=steamos-log-submitter.service
[Service] [Service]
Type=dbus Type=dbus
BusName=com.steampowered.SteamOSManager1 BusName=com.steampowered.SteamOSManager1.Manager
Environment=RUST_LOG='INFO' Environment=RUST_LOG='INFO'
ExecStart=/usr/lib/steamos-manager ExecStart=/usr/lib/steamos-manager
Restart=on-failure Restart=on-failure

View file

@ -302,14 +302,14 @@ mod test {
use tokio::time::sleep; use tokio::time::sleep;
async fn nyield(times: u32) { async fn nyield(times: u32) {
for i in 0..times { for _ in 0..times {
sleep(Duration::from_millis(1)).await; sleep(Duration::from_millis(1)).await;
} }
} }
#[tokio::test] #[tokio::test]
async fn hid_nodes() { async fn hid_nodes() {
let h = testing::start(); let _h = testing::start();
let hid = HidNode::new(0); let hid = HidNode::new(0);
let sys_base = hid.sys_base(); let sys_base = hid.sys_base();
@ -326,7 +326,7 @@ mod test {
#[tokio::test] #[tokio::test]
async fn hid_can_inhibit() { async fn hid_can_inhibit() {
let h = testing::start(); let _h = testing::start();
let hids = [ let hids = [
HidNode::new(0), HidNode::new(0),
@ -363,7 +363,7 @@ mod test {
#[tokio::test] #[tokio::test]
async fn hid_inhibit() { async fn hid_inhibit() {
let h = testing::start(); let _h = testing::start();
let hid = HidNode::new(0); let hid = HidNode::new(0);
let sys_base = hid.sys_base(); let sys_base = hid.sys_base();
@ -373,12 +373,12 @@ mod test {
assert!(hid.can_inhibit().await); assert!(hid.can_inhibit().await);
hid.inhibit().await; hid.inhibit().await.expect("inhibit");
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"),
"1\n" "1\n"
); );
hid.uninhibit().await; hid.uninhibit().await.expect("uninhibit");
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"),
"0\n" "0\n"
@ -387,7 +387,7 @@ mod test {
#[tokio::test] #[tokio::test]
async fn hid_inhibit_error_continue() { async fn hid_inhibit_error_continue() {
let h = testing::start(); let _h = testing::start();
let hid = HidNode::new(0); let hid = HidNode::new(0);
let sys_base = hid.sys_base(); let sys_base = hid.sys_base();
@ -399,12 +399,12 @@ mod test {
assert!(hid.can_inhibit().await); assert!(hid.can_inhibit().await);
hid.inhibit().await; assert!(hid.inhibit().await.is_err());
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input1/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input1/inhibited")).expect("inhibited"),
"1\n" "1\n"
); );
hid.uninhibit().await; assert!(hid.uninhibit().await.is_err());
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input1/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input1/inhibited")).expect("inhibited"),
"0\n" "0\n"
@ -496,7 +496,7 @@ mod test {
let mut inhibitor = Inhibitor::init().await.expect("init"); let mut inhibitor = Inhibitor::init().await.expect("init");
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
inhibitor.run().await; inhibitor.run().await.expect("run");
}); });
nyield(1).await; nyield(1).await;
@ -540,7 +540,7 @@ mod test {
let mut inhibitor = Inhibitor::init().await.expect("init"); let mut inhibitor = Inhibitor::init().await.expect("init");
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
inhibitor.run().await; inhibitor.run().await.expect("run");
}); });
nyield(1).await; nyield(1).await;
@ -548,7 +548,7 @@ mod test {
File::create(hid.hidraw()).expect("hidraw"); File::create(hid.hidraw()).expect("hidraw");
symlink(hid.hidraw(), path.join("proc/1/fd/3")).expect("symlink"); symlink(hid.hidraw(), path.join("proc/1/fd/3")).expect("symlink");
let f = File::open(hid.hidraw()).expect("hidraw"); let _f = File::open(hid.hidraw()).expect("hidraw");
nyield(4).await; nyield(4).await;
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"),
@ -560,21 +560,20 @@ mod test {
#[tokio::test] #[tokio::test]
async fn inhibitor_create() { async fn inhibitor_create() {
let h = testing::start(); let _h = testing::start();
let path = h.test.path();
let hid = HidNode::new(0); let hid = HidNode::new(0);
let sys_base = hid.sys_base(); let sys_base = hid.sys_base();
create_dir_all(path.join("dev")).expect("dev"); create_dir_all(path("/dev")).expect("dev");
create_dir_all(sys_base.join("input/input0/mouse0")).expect("mouse0"); create_dir_all(sys_base.join("input/input0/mouse0")).expect("mouse0");
symlink("sony", sys_base.join("driver")).expect("driver"); symlink("sony", sys_base.join("driver")).expect("driver");
create_dir_all(path.join("proc/1/fd")).expect("fd"); create_dir_all(path("/proc/1/fd")).expect("fd");
write(path.join("proc/1/comm"), "steam\n").expect("comm"); write(path("/proc/1/comm"), "steam\n").expect("comm");
let mut inhibitor = Inhibitor::init().await.expect("init"); let mut inhibitor = Inhibitor::init().await.expect("init");
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
inhibitor.run().await; inhibitor.run().await.expect("run");
}); });
nyield(3).await; nyield(3).await;
@ -582,8 +581,8 @@ mod test {
File::create(hid.hidraw()).expect("hidraw"); File::create(hid.hidraw()).expect("hidraw");
nyield(3).await; nyield(3).await;
symlink(hid.hidraw(), path.join("proc/1/fd/3")).expect("symlink"); symlink(hid.hidraw(), path("/proc/1/fd/3")).expect("symlink");
let f = File::open(hid.hidraw()).expect("hidraw"); let _f = File::open(hid.hidraw()).expect("hidraw");
nyield(3).await; nyield(3).await;
assert_eq!( assert_eq!(
read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"), read_to_string(sys_base.join("input/input0/inhibited")).expect("inhibited"),

View file

@ -6,10 +6,12 @@
*/ */
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use tokio::fs; use tokio::fs;
use crate::path; use crate::path;
use crate::process::script_exit_code;
const BOARD_VENDOR_PATH: &str = "/sys/class/dmi/id/board_vendor"; const BOARD_VENDOR_PATH: &str = "/sys/class/dmi/id/board_vendor";
const BOARD_NAME_PATH: &str = "/sys/class/dmi/id/board_name"; const BOARD_NAME_PATH: &str = "/sys/class/dmi/id/board_name";
@ -21,6 +23,13 @@ pub enum HardwareVariant {
Galileo, Galileo,
} }
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
pub enum HardwareCurrentlySupported {
Unsupported = 0,
Supported = 1,
}
impl FromStr for HardwareVariant { impl FromStr for HardwareVariant {
type Err = Error; type Err = Error;
fn from_str(input: &str) -> Result<HardwareVariant, Self::Err> { fn from_str(input: &str) -> Result<HardwareVariant, Self::Err> {
@ -32,6 +41,30 @@ impl FromStr for HardwareVariant {
} }
} }
impl TryFrom<u32> for HardwareCurrentlySupported {
type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> {
match v {
x if x == HardwareCurrentlySupported::Unsupported as u32 => {
Ok(HardwareCurrentlySupported::Unsupported)
}
x if x == HardwareCurrentlySupported::Supported as u32 => {
Ok(HardwareCurrentlySupported::Supported)
}
_ => Err("No enum match for value {v}"),
}
}
}
impl fmt::Display for HardwareCurrentlySupported {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
HardwareCurrentlySupported::Unsupported => write!(f, "Unsupported"),
HardwareCurrentlySupported::Supported => write!(f, "Supported"),
}
}
}
pub async fn variant() -> Result<HardwareVariant> { pub async fn variant() -> Result<HardwareVariant> {
let board_vendor = fs::read_to_string(path(BOARD_VENDOR_PATH)).await?; let board_vendor = fs::read_to_string(path(BOARD_VENDOR_PATH)).await?;
if board_vendor.trim_end() != "Valve" { if board_vendor.trim_end() != "Valve" {
@ -42,6 +75,17 @@ pub async fn variant() -> Result<HardwareVariant> {
HardwareVariant::from_str(board_name.trim_end()) HardwareVariant::from_str(board_name.trim_end())
} }
pub async fn check_support() -> Result<HardwareCurrentlySupported> {
// Run jupiter-check-support note this script does exit 1 for "Support: No" case
// so no need to parse output, etc.
let res = script_exit_code("/usr/bin/jupiter-check-support", &[] as &[String; 0]).await?;
Ok(match res {
0 => HardwareCurrentlySupported::Supported,
_ => HardwareCurrentlySupported::Unsupported,
})
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
@ -50,7 +94,7 @@ mod test {
#[tokio::test] #[tokio::test]
async fn board_lookup() { async fn board_lookup() {
let h = testing::start(); let _h = testing::start();
create_dir_all(crate::path("/sys/class/dmi/id")) create_dir_all(crate::path("/sys/class/dmi/id"))
.await .await

View file

@ -26,6 +26,7 @@ mod manager;
mod power; mod power;
mod process; mod process;
mod sls; mod sls;
mod systemd;
mod wifi; mod wifi;
#[cfg(test)] #[cfg(test)]
@ -123,15 +124,25 @@ async fn reload() -> Result<()> {
} }
} }
async fn create_connection() -> Result<Connection> { pub fn anyhow_to_zbus(error: Error) -> zbus::Error {
let manager = manager::SMManager::new().await?; zbus::Error::Failure(error.to_string())
}
ConnectionBuilder::system()? pub fn anyhow_to_zbus_fdo(error: Error) -> zbus::fdo::Error {
.name("com.steampowered.SteamOSManager1")? zbus::fdo::Error::Failed(error.to_string())
.serve_at("/com/steampowered/SteamOSManager1", manager)? }
async fn create_connection() -> Result<Connection> {
let connection = ConnectionBuilder::system()?
.name("com.steampowered.SteamOSManager1.Manager")?
.build() .build()
.await .await?;
.map_err(|e| e.into()) let manager = manager::SteamOSManager::new(connection.clone()).await?;
connection
.object_server()
.at("/com/steampowered/SteamOSManager1", manager)
.await?;
Ok(connection)
} }
#[tokio::main] #[tokio::main]

View file

@ -1,104 +1,176 @@
/* /*
* Copyright © 2023 Collabora Ltd. * Copyright © 2023 Collabora Ltd.
* Copyright © 2024 Valve Software * Copyright © 2024 Valve Software
* Copyright © 2024 Igalia S.L.
* *
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
*/ */
use anyhow::Result; use anyhow::Result;
use std::fmt;
use tokio::fs::File; use tokio::fs::File;
use tracing::{error, warn}; use tracing::error;
use zbus::{interface, zvariant::Fd}; use zbus::zvariant::Fd;
use zbus::{interface, Connection, SignalContext};
use crate::hardware::{variant, HardwareVariant}; use crate::hardware::{check_support, variant, HardwareVariant};
use crate::power::{set_gpu_clocks, set_gpu_performance_level, set_tdp_limit}; use crate::power::{
use crate::process::{run_script, script_output, SYSTEMCTL_PATH}; get_gpu_clocks, get_gpu_performance_level, get_tdp_limit, set_gpu_clocks,
use crate::wifi::{restart_iwd, setup_iwd_config, start_tracing, stop_tracing, WifiDebugMode}; set_gpu_performance_level, set_tdp_limit, GPUPerformanceLevel,
};
use crate::process::{run_script, script_output};
use crate::systemd::SystemdUnit;
use crate::wifi::{
get_wifi_backend, set_wifi_backend, set_wifi_debug_mode, WifiBackend, WifiDebugMode,
WifiPowerManagement,
};
use crate::{anyhow_to_zbus, anyhow_to_zbus_fdo};
pub struct SMManager { #[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
enum PrepareFactoryReset {
Unknown = 0,
RebootRequired = 1,
}
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
enum FanControl {
BIOS = 0,
OS = 1,
}
impl TryFrom<u32> for FanControl {
type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> {
match v {
x if x == FanControl::BIOS as u32 => Ok(FanControl::BIOS),
x if x == FanControl::OS as u32 => Ok(FanControl::BIOS),
_ => Err("No enum match for value {v}"),
}
}
}
impl fmt::Display for FanControl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FanControl::BIOS => write!(f, "BIOS"),
FanControl::OS => write!(f, "OS"),
}
}
}
pub struct SteamOSManager {
connection: Connection,
wifi_debug_mode: WifiDebugMode, wifi_debug_mode: WifiDebugMode,
// Whether we should use trace-cmd or not. // Whether we should use trace-cmd or not.
// True on galileo devices, false otherwise // True on galileo devices, false otherwise
should_trace: bool, should_trace: bool,
} }
impl SMManager { impl SteamOSManager {
pub async fn new() -> Result<Self> { pub async fn new(connection: Connection) -> Result<Self> {
Ok(SMManager { Ok(SteamOSManager {
connection,
wifi_debug_mode: WifiDebugMode::Off, wifi_debug_mode: WifiDebugMode::Off,
should_trace: variant().await? == HardwareVariant::Galileo, should_trace: variant().await? == HardwareVariant::Galileo,
}) })
} }
} }
const MIN_BUFFER_SIZE: u32 = 100;
const ALS_INTEGRATION_PATH: &str = "/sys/devices/platform/AMDI0010:00/i2c-0/i2c-PRP0001:01/iio:device0/in_illuminance_integration_time"; const ALS_INTEGRATION_PATH: &str = "/sys/devices/platform/AMDI0010:00/i2c-0/i2c-PRP0001:01/iio:device0/in_illuminance_integration_time";
#[interface(name = "com.steampowered.SteamOSManager1")] #[interface(name = "com.steampowered.SteamOSManager1.Manager")]
impl SMManager { impl SteamOSManager {
const API_VERSION: u32 = 1; const API_VERSION: u32 = 7;
async fn say_hello(&self, name: &str) -> String { async fn prepare_factory_reset(&self) -> u32 {
format!("Hello {}!", name)
}
async fn factory_reset(&self) -> bool {
// Run steamos factory reset script and return true on success // Run steamos factory reset script and return true on success
run_script( let res = run_script("/usr/bin/steamos-factory-reset-config", &[""]).await;
"factory reset", match res {
"/usr/bin/steamos-factory-reset-config", Ok(_) => PrepareFactoryReset::RebootRequired as u32,
&[""], Err(_) => PrepareFactoryReset::Unknown as u32,
)
.await
.unwrap_or(false)
}
async fn disable_wifi_power_management(&self) -> bool {
// Run polkit helper script and return true on success
run_script(
"disable wifi power management",
"/usr/bin/steamos-polkit-helpers/steamos-disable-wireless-power-management",
&[""],
)
.await
.unwrap_or(false)
}
async fn enable_fan_control(&self, enable: bool) -> bool {
// Run what steamos-polkit-helpers/jupiter-fan-control does
if enable {
run_script(
"enable fan control",
SYSTEMCTL_PATH,
&["start", "jupiter-fan-control-service"],
)
.await
.unwrap_or(false)
} else {
run_script(
"disable fan control",
SYSTEMCTL_PATH,
&["stop", "jupiter-fan-control.service"],
)
.await
.unwrap_or(false)
} }
} }
async fn hardware_check_support(&self) -> bool { #[zbus(property(emits_changed_signal = "false"))]
// Run jupiter-check-support note this script does exit 1 for "Support: No" case async fn wifi_power_management_state(&self) -> zbus::fdo::Result<u32> {
// so no need to parse output, etc. let output = script_output("/usr/bin/iwconfig", &["wlan0"])
run_script( .await
"check hardware support", .map_err(anyhow_to_zbus_fdo)?;
"/usr/bin/jupiter-check-support", for line in output.lines() {
&[""], return Ok(match line.trim() {
) "Power Management:on" => WifiPowerManagement::Enabled as u32,
.await "Power Management:off" => WifiPowerManagement::Disabled as u32,
.unwrap_or(false) _ => continue,
});
}
Err(zbus::fdo::Error::Failed(String::from(
"Failed to query power management state",
)))
} }
async fn read_als_calibration(&self) -> f32 { #[zbus(property)]
async fn set_wifi_power_management_state(&self, state: u32) -> zbus::Result<()> {
let state = match WifiPowerManagement::try_from(state) {
Ok(state) => state,
Err(err) => return Err(zbus::fdo::Error::InvalidArgs(err.to_string()).into()),
};
let state = match state {
WifiPowerManagement::Disabled => "off",
WifiPowerManagement::Enabled => "on",
};
run_script("/usr/bin/iwconfig", &["wlan0", "power", state])
.await
.inspect_err(|message| error!("Error setting wifi power management state: {message}"))
.map_err(anyhow_to_zbus)
}
#[zbus(property(emits_changed_signal = "false"))]
async fn fan_control_state(&self) -> zbus::fdo::Result<u32> {
let jupiter_fan_control =
SystemdUnit::new(self.connection.clone(), "jupiter_2dfan_2dcontrol_2eservice")
.await
.map_err(anyhow_to_zbus_fdo)?;
let active = jupiter_fan_control
.active()
.await
.map_err(anyhow_to_zbus_fdo)?;
Ok(match active {
true => FanControl::OS as u32,
false => FanControl::BIOS as u32,
})
}
#[zbus(property)]
async fn set_fan_control_state(&self, state: u32) -> zbus::Result<()> {
let state = match FanControl::try_from(state) {
Ok(state) => state,
Err(err) => return Err(zbus::fdo::Error::InvalidArgs(err.to_string()).into()),
};
// Run what steamos-polkit-helpers/jupiter-fan-control does
let jupiter_fan_control =
SystemdUnit::new(self.connection.clone(), "jupiter_2dfan_2dcontrol_2eservice")
.await
.map_err(anyhow_to_zbus)?;
match state {
FanControl::OS => jupiter_fan_control.start().await,
FanControl::BIOS => jupiter_fan_control.stop().await,
}
.map_err(anyhow_to_zbus)
}
#[zbus(property(emits_changed_signal = "const"))]
async fn hardware_currently_supported(&self) -> zbus::fdo::Result<u32> {
match check_support().await {
Ok(res) => Ok(res as u32),
Err(e) => Err(anyhow_to_zbus_fdo(e)),
}
}
#[zbus(property(emits_changed_signal = "false"))]
async fn als_calibration_gain(&self) -> f64 {
// Run script to get calibration value // Run script to get calibration value
let result = script_output( let result = script_output(
"/usr/bin/steamos-polkit-helpers/jupiter-get-als-gain", "/usr/bin/steamos-polkit-helpers/jupiter-get-als-gain",
@ -114,67 +186,7 @@ impl SMManager {
} }
} }
async fn update_bios(&self) -> bool { async fn get_als_integration_time_file_descriptor(&self) -> zbus::fdo::Result<Fd> {
// Update the bios as needed
// Return true if the script was successful (though that might mean no update was needed), false otherwise
run_script(
"update bios",
"/usr/bin/steamos-potlkit-helpers/jupiter-biosupdate",
&["--auto"],
)
.await
.unwrap_or(false)
}
async fn update_dock(&self) -> bool {
// Update the dock firmware as needed
// Retur true if successful, false otherwise
run_script(
"update dock firmware",
"/usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
&[""],
)
.await
.unwrap_or(false)
}
async fn trim_devices(&self) -> bool {
// Run steamos-trim-devices script
// return true on success, false otherwise
run_script(
"trim devices",
"/usr/bin/steamos-polkit-helpers/steamos-trim-devices",
&[""],
)
.await
.unwrap_or(false)
}
async fn format_sdcard(&self) -> bool {
// Run steamos-format-sdcard script
// return true on success, false otherwise
run_script(
"format sdcard",
"/usr/bin/steamos-polkit-helpers/steamos-format-sdcard",
&[""],
)
.await
.unwrap_or(false)
}
async fn set_gpu_performance_level(&self, level: i32) -> bool {
set_gpu_performance_level(level).await.is_ok()
}
async fn set_gpu_clocks(&self, clocks: i32) -> bool {
set_gpu_clocks(clocks).await.is_ok()
}
async fn set_tdp_limit(&self, limit: i32) -> bool {
set_tdp_limit(limit).await.is_ok()
}
async fn get_als_integration_time_file_descriptor(&self) -> Result<Fd, zbus::fdo::Error> {
// Get the file descriptor for the als integration time sysfs path // Get the file descriptor for the als integration time sysfs path
let result = File::create(ALS_INTEGRATION_PATH).await; let result = File::create(ALS_INTEGRATION_PATH).await;
match result { match result {
@ -186,109 +198,348 @@ impl SMManager {
} }
} }
async fn get_wifi_debug_mode(&mut self) -> u32 { async fn update_bios(&self) -> zbus::fdo::Result<()> {
// Update the bios as needed
run_script(
"/usr/bin/steamos-potlkit-helpers/jupiter-biosupdate",
&["--auto"],
)
.await
.inspect_err(|message| error!("Error updating BIOS: {message}"))
.map_err(anyhow_to_zbus_fdo)
}
async fn update_dock(&self) -> zbus::fdo::Result<()> {
// Update the dock firmware as needed
run_script(
"/usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
&[""],
)
.await
.inspect_err(|message| error!("Error updating dock: {message}"))
.map_err(anyhow_to_zbus_fdo)
}
async fn trim_devices(&self) -> zbus::fdo::Result<()> {
// Run steamos-trim-devices script
run_script(
"/usr/bin/steamos-polkit-helpers/steamos-trim-devices",
&[""],
)
.await
.inspect_err(|message| error!("Error updating trimming devices: {message}"))
.map_err(anyhow_to_zbus_fdo)
}
async fn format_device(
&self,
device: &str,
label: &str,
validate: bool,
) -> zbus::fdo::Result<()> {
let mut args = vec!["--label", label, "--device", device];
if !validate {
args.push("--skip-validation");
}
run_script("/usr/lib/hwsupport/format-device.sh", args.as_ref())
.await
.inspect_err(|message| error!("Error formatting {device}: {message}"))
.map_err(anyhow_to_zbus_fdo)
}
#[zbus(property(emits_changed_signal = "false"), name = "GPUPerformanceLevel")]
async fn gpu_performance_level(&self) -> zbus::fdo::Result<u32> {
match get_gpu_performance_level().await {
Ok(level) => Ok(level as u32),
Err(e) => {
error!("Error getting GPU performance level: {e}");
Err(anyhow_to_zbus_fdo(e))
}
}
}
#[zbus(property, name = "GPUPerformanceLevel")]
async fn set_gpu_performance_level(&self, level: u32) -> zbus::Result<()> {
let level = match GPUPerformanceLevel::try_from(level) {
Ok(level) => level,
Err(e) => return Err(zbus::Error::Failure(e.to_string())),
};
set_gpu_performance_level(level)
.await
.inspect_err(|message| error!("Error setting GPU performance level: {message}"))
.map_err(anyhow_to_zbus)
}
#[zbus(property(emits_changed_signal = "false"), name = "ManualGPUClock")]
async fn manual_gpu_clock(&self) -> zbus::fdo::Result<u32> {
get_gpu_clocks()
.await
.inspect_err(|message| error!("Error getting manual GPU clock: {message}"))
.map_err(anyhow_to_zbus_fdo)
}
#[zbus(property, name = "ManualGPUClock")]
async fn set_manual_gpu_clock(&self, clocks: u32) -> zbus::Result<()> {
set_gpu_clocks(clocks)
.await
.inspect_err(|message| error!("Error setting manual GPU clock: {message}"))
.map_err(anyhow_to_zbus)
}
#[zbus(property(emits_changed_signal = "const"), name = "ManualGPUClockMin")]
async fn manual_gpu_clock_min(&self) -> u32 {
// TODO: Can this be queried from somewhere?
200
}
#[zbus(property(emits_changed_signal = "const"), name = "ManualGPUClockMax")]
async fn manual_gpu_clock_max(&self) -> u32 {
// TODO: Can this be queried from somewhere?
1600
}
#[zbus(property(emits_changed_signal = "false"), name = "TDPLimit")]
async fn tdp_limit(&self) -> zbus::fdo::Result<u32> {
get_tdp_limit().await.map_err(anyhow_to_zbus_fdo)
}
#[zbus(property, name = "TDPLimit")]
async fn set_tdp_limit(&self, limit: u32) -> zbus::Result<()> {
set_tdp_limit(limit).await.map_err(anyhow_to_zbus)
}
#[zbus(property(emits_changed_signal = "const"), name = "TDPLimitMin")]
async fn tdp_limit_min(&self) -> u32 {
// TODO: Can this be queried from somewhere?
3
}
#[zbus(property(emits_changed_signal = "const"), name = "TDPLimitMax")]
async fn tdp_limit_max(&self) -> u32 {
// TODO: Can this be queried from somewhere?
15
}
#[zbus(property)]
async fn wifi_debug_mode_state(&self) -> u32 {
// Get the wifi debug mode // Get the wifi debug mode
self.wifi_debug_mode as u32 self.wifi_debug_mode as u32
} }
async fn set_wifi_debug_mode(&mut self, mode: u32, buffer_size: u32) -> bool { async fn set_wifi_debug_mode(
&mut self,
mode: u32,
buffer_size: u32,
#[zbus(signal_context)] ctx: SignalContext<'_>,
) -> zbus::fdo::Result<()> {
// Set the wifi debug mode to mode, using an int for flexibility going forward but only // Set the wifi debug mode to mode, using an int for flexibility going forward but only
// doing things on 0 or 1 for now // doing things on 0 or 1 for now
// Return false on error // Return false on error
match get_wifi_backend().await {
let wanted_mode = WifiDebugMode::try_from(mode); Ok(WifiBackend::IWD) => (),
match wanted_mode { Ok(backend) => {
Ok(WifiDebugMode::Off) => { return Err(zbus::fdo::Error::Failed(format!(
// If mode is 0 disable wifi debug mode "Setting wifi debug mode not supported when backend is {backend}",
// Stop any existing trace and flush to disk. )));
if self.should_trace {
let result = match stop_tracing().await {
Ok(result) => result,
Err(message) => {
error!("stop_tracing command got an error: {message}");
return false;
}
};
if !result {
error!("stop_tracing command returned non-zero");
return false;
}
}
// Stop_tracing was successful
if let Err(message) = setup_iwd_config(false).await {
error!("setup_iwd_config false got an error: {message}");
return false;
}
// setup_iwd_config false worked
let value = match restart_iwd().await {
Ok(value) => value,
Err(message) => {
error!("restart_iwd got an error: {message}");
return false;
}
};
if value {
// restart iwd worked
self.wifi_debug_mode = WifiDebugMode::Off;
} else {
// restart_iwd failed
error!("restart_iwd failed, check log above");
return false;
}
}
Ok(WifiDebugMode::On) => {
// If mode is 1 enable wifi debug mode
if buffer_size < MIN_BUFFER_SIZE {
return false;
}
if let Err(message) = setup_iwd_config(true).await {
error!("setup_iwd_config true got an error: {message}");
return false;
}
// setup_iwd_config worked
let value = match restart_iwd().await {
Ok(value) => value,
Err(message) => {
error!("restart_iwd got an error: {message}");
return false;
}
};
if !value {
error!("restart_iwd failed");
return false;
}
// restart_iwd worked
if self.should_trace {
let value = match start_tracing(buffer_size).await {
Ok(value) => value,
Err(message) => {
error!("start_tracing got an error: {message}");
return false;
}
};
if !value {
// start_tracing failed
error!("start_tracing failed");
return false;
}
}
// start_tracing worked
self.wifi_debug_mode = WifiDebugMode::On;
}
Err(_) => {
// Invalid mode requested, more coming later, but add this catch-all for now
warn!("Invalid wifi debug mode {mode} requested");
return false;
} }
Err(e) => return Err(anyhow_to_zbus_fdo(e)),
} }
true let wanted_mode = match WifiDebugMode::try_from(mode) {
Ok(mode) => mode,
Err(e) => return Err(zbus::fdo::Error::InvalidArgs(e.to_string())),
};
match set_wifi_debug_mode(
wanted_mode,
buffer_size,
self.should_trace,
self.connection.clone(),
)
.await
{
Ok(()) => {
self.wifi_debug_mode = wanted_mode;
self.wifi_debug_mode_state_changed(&ctx).await?;
Ok(())
}
Err(e) => {
error!("Error setting wifi debug mode: {e}");
Err(anyhow_to_zbus_fdo(e))
}
}
}
/// WifiBackend property.
#[zbus(property(emits_changed_signal = "false"))]
async fn wifi_backend(&self) -> zbus::fdo::Result<u32> {
match get_wifi_backend().await {
Ok(backend) => Ok(backend as u32),
Err(e) => Err(anyhow_to_zbus_fdo(e)),
}
}
#[zbus(property)]
async fn set_wifi_backend(&mut self, backend: u32) -> zbus::fdo::Result<()> {
if self.wifi_debug_mode == WifiDebugMode::On {
return Err(zbus::fdo::Error::Failed(String::from(
"operation not supported when wifi_debug_mode=on",
)));
}
let backend = match WifiBackend::try_from(backend) {
Ok(backend) => backend,
Err(e) => return Err(zbus::fdo::Error::InvalidArgs(e.to_string())),
};
set_wifi_backend(backend)
.await
.inspect_err(|message| error!("Error setting wifi backend: {message}"))
.map_err(anyhow_to_zbus_fdo)
} }
/// A version property. /// A version property.
#[zbus(property)] #[zbus(property(emits_changed_signal = "const"))]
async fn version(&self) -> u32 { async fn version(&self) -> u32 {
SMManager::API_VERSION SteamOSManager::API_VERSION
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{power, testing};
use tokio::fs::{create_dir_all, write};
use zbus::connection::Connection;
use zbus::ConnectionBuilder;
struct TestHandle {
_handle: testing::TestHandle,
connection: Connection,
}
async fn start(name: &str) -> TestHandle {
let handle = testing::start();
create_dir_all(crate::path("/sys/class/dmi/id"))
.await
.expect("create_dir_all");
write(crate::path("/sys/class/dmi/id/board_vendor"), "Valve\n")
.await
.expect("write");
write(crate::path("/sys/class/dmi/id/board_name"), "Jupiter\n")
.await
.expect("write");
create_dir_all(crate::path("/etc/NetworkManager/conf.d"))
.await
.expect("create_dir_all");
write(
crate::path("/etc/NetworkManager/conf.d/wifi_backend.conf"),
"wifi.backend=iwd\n",
)
.await
.expect("write");
let connection = ConnectionBuilder::session()
.unwrap()
.name(format!("com.steampowered.SteamOSManager1.Test.{name}"))
.unwrap()
.build()
.await
.unwrap();
let manager = SteamOSManager::new(connection.clone()).await.unwrap();
connection
.object_server()
.at("/com/steampowered/SteamOSManager1", manager)
.await
.expect("object_server at");
TestHandle {
_handle: handle,
connection,
}
}
#[zbus::proxy(
interface = "com.steampowered.SteamOSManager1.Manager",
default_service = "com.steampowered.SteamOSManager1.Test.GPUPerformanceLevel",
default_path = "/com/steampowered/SteamOSManager1"
)]
trait GPUPerformanceLevel {
#[zbus(property, name = "GPUPerformanceLevel")]
fn gpu_performance_level(&self) -> zbus::Result<u32>;
#[zbus(property, name = "GPUPerformanceLevel")]
fn set_gpu_performance_level(&self, level: u32) -> zbus::Result<()>;
}
#[tokio::test]
async fn gpu_performance_level() {
let test = start("GPUPerformanceLevel").await;
power::test::setup().await;
let proxy = GPUPerformanceLevelProxy::new(&test.connection)
.await
.unwrap();
set_gpu_performance_level(GPUPerformanceLevel::Auto)
.await
.expect("set");
assert_eq!(
proxy.gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::Auto as u32
);
proxy
.set_gpu_performance_level(GPUPerformanceLevel::Low as u32)
.await
.expect("proxy_set");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::Low
);
}
#[zbus::proxy(
interface = "com.steampowered.SteamOSManager1.Manager",
default_service = "com.steampowered.SteamOSManager1.Test.ManualGPUClock",
default_path = "/com/steampowered/SteamOSManager1"
)]
trait ManualGPUClock {
#[zbus(property, name = "ManualGPUClock")]
fn manual_gpu_clock(&self) -> zbus::Result<u32>;
#[zbus(property, name = "ManualGPUClock")]
fn set_manual_gpu_clock(&self, clocks: u32) -> zbus::Result<()>;
}
#[tokio::test]
async fn manual_gpu_clock() {
let test = start("ManualGPUClock").await;
let proxy = ManualGPUClockProxy::new(&test.connection).await.unwrap();
assert!(proxy.manual_gpu_clock().await.is_err());
power::test::write_clocks(1600).await;
assert_eq!(proxy.manual_gpu_clock().await.unwrap(), 1600);
proxy.set_manual_gpu_clock(200).await.expect("proxy_set");
power::test::expect_clocks(200).await;
assert!(proxy.set_manual_gpu_clock(100).await.is_err());
power::test::expect_clocks(200).await;
}
#[zbus::proxy(
interface = "com.steampowered.SteamOSManager1.Manager",
default_service = "com.steampowered.SteamOSManager1.Test.Version",
default_path = "/com/steampowered/SteamOSManager1"
)]
trait Version {
#[zbus(property)]
fn version(&self) -> zbus::Result<u32>;
}
#[tokio::test]
async fn version() {
let test = start("Version").await;
let proxy = VersionProxy::new(&test.connection).await.unwrap();
assert_eq!(proxy.version().await, Ok(SteamOSManager::API_VERSION));
} }
} }

View file

@ -5,9 +5,11 @@
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
*/ */
use anyhow::{bail, ensure, Result}; use anyhow::{anyhow, bail, ensure, Error, Result};
use std::path::PathBuf;
use std::str::FromStr;
use tokio::fs::{self, File}; use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tracing::error; use tracing::error;
use crate::path; use crate::path;
@ -18,33 +20,89 @@ const GPU_PERFORMANCE_LEVEL_PATH: &str =
"/sys/class/drm/card0/device/power_dpm_force_performance_level"; "/sys/class/drm/card0/device/power_dpm_force_performance_level";
const GPU_CLOCKS_PATH: &str = "/sys/class/drm/card0/device/pp_od_clk_voltage"; const GPU_CLOCKS_PATH: &str = "/sys/class/drm/card0/device/pp_od_clk_voltage";
pub async fn set_gpu_performance_level(level: i32) -> Result<()> { const TDP_LIMIT1: &str = "power1_cap";
// Set given GPU performance level const TDP_LIMIT2: &str = "power2_cap";
// Levels are defined below
// return true if able to write, false otherwise or if level is out of range, etc.
let levels = ["auto", "low", "high", "manual", "peak_performance"];
ensure!(
level >= 0 && level < levels.len() as i32,
"Invalid performance level"
);
let mut myfile = File::create(GPU_PERFORMANCE_LEVEL_PATH) #[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
pub enum GPUPerformanceLevel {
Auto = 0,
Low = 1,
High = 2,
Manual = 3,
ProfilePeak = 4,
}
impl TryFrom<u32> for GPUPerformanceLevel {
type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> {
match v {
x if x == GPUPerformanceLevel::Auto as u32 => Ok(GPUPerformanceLevel::Auto),
x if x == GPUPerformanceLevel::Low as u32 => Ok(GPUPerformanceLevel::Low),
x if x == GPUPerformanceLevel::High as u32 => Ok(GPUPerformanceLevel::High),
x if x == GPUPerformanceLevel::Manual as u32 => Ok(GPUPerformanceLevel::Manual),
x if x == GPUPerformanceLevel::ProfilePeak as u32 => {
Ok(GPUPerformanceLevel::ProfilePeak)
}
_ => Err("No enum match for value {v}"),
}
}
}
impl FromStr for GPUPerformanceLevel {
type Err = Error;
fn from_str(input: &str) -> Result<GPUPerformanceLevel, Self::Err> {
match input {
"auto" => Ok(GPUPerformanceLevel::Auto),
"low" => Ok(GPUPerformanceLevel::Low),
"high" => Ok(GPUPerformanceLevel::High),
"manual" => Ok(GPUPerformanceLevel::Manual),
"peak_performance" => Ok(GPUPerformanceLevel::ProfilePeak),
v => Err(anyhow!("No enum match for value {v}")),
}
}
}
impl ToString for GPUPerformanceLevel {
fn to_string(&self) -> String {
String::from(match self {
GPUPerformanceLevel::Auto => "auto",
GPUPerformanceLevel::Low => "low",
GPUPerformanceLevel::High => "high",
GPUPerformanceLevel::Manual => "manual",
GPUPerformanceLevel::ProfilePeak => "peak_performance",
})
}
}
pub async fn get_gpu_performance_level() -> Result<GPUPerformanceLevel> {
let level = fs::read_to_string(path(GPU_PERFORMANCE_LEVEL_PATH))
.await
.inspect_err(|message| error!("Error opening sysfs file for reading: {message}"))?;
GPUPerformanceLevel::from_str(level.trim().as_ref())
}
pub async fn set_gpu_performance_level(level: GPUPerformanceLevel) -> Result<()> {
let mut myfile = File::create(path(GPU_PERFORMANCE_LEVEL_PATH))
.await .await
.inspect_err(|message| error!("Error opening sysfs file for writing: {message}"))?; .inspect_err(|message| error!("Error opening sysfs file for writing: {message}"))?;
let level: String = level.to_string();
myfile myfile
.write_all(levels[level as usize].as_bytes()) .write_all(level.as_bytes())
.await .await
.inspect_err(|message| error!("Error writing to sysfs file: {message}"))?; .inspect_err(|message| error!("Error writing to sysfs file: {message}"))?;
Ok(()) Ok(())
} }
pub async fn set_gpu_clocks(clocks: i32) -> Result<()> { pub async fn set_gpu_clocks(clocks: u32) -> Result<()> {
// Set GPU clocks to given value valid between 200 - 1600 // Set GPU clocks to given value valid between 200 - 1600
// Only used when GPU Performance Level is manual, but write whenever called. // Only used when GPU Performance Level is manual, but write whenever called.
ensure!((200..=1600).contains(&clocks), "Invalid clocks"); ensure!((200..=1600).contains(&clocks), "Invalid clocks");
let mut myfile = File::create(GPU_CLOCKS_PATH) let mut myfile = File::create(path(GPU_CLOCKS_PATH))
.await .await
.inspect_err(|message| error!("Error opening sysfs file for writing: {message}"))?; .inspect_err(|message| error!("Error opening sysfs file for writing: {message}"))?;
@ -67,25 +125,63 @@ pub async fn set_gpu_clocks(clocks: i32) -> Result<()> {
Ok(()) Ok(())
} }
pub async fn set_tdp_limit(limit: i32) -> Result<()> { pub async fn get_gpu_clocks() -> Result<u32> {
// Set TDP limit given if within range (3-15) let clocks_file = File::open(path(GPU_CLOCKS_PATH)).await?;
// Returns false on error or out of range let mut reader = BufReader::new(clocks_file);
ensure!((3..=15).contains(&limit), "Invalid limit"); loop {
let mut line = String::new();
if reader.read_line(&mut line).await? == 0 {
break;
}
if line != "OD_SCLK:\n" {
continue;
}
let mut line = String::new();
if reader.read_line(&mut line).await? == 0 {
break;
}
let mhz = match line.split_whitespace().nth(1) {
Some(mhz) if mhz.ends_with("Mhz") => mhz.trim_end_matches("Mhz"),
_ => break,
};
match mhz.parse() {
Ok(mhz) => return Ok(mhz),
Err(e) => return Err(e.into()),
}
}
Err(anyhow!("Couldn't find GPU clocks"))
}
async fn find_hwmon() -> Result<PathBuf> {
let mut dir = fs::read_dir(path(GPU_HWMON_PREFIX)).await?; let mut dir = fs::read_dir(path(GPU_HWMON_PREFIX)).await?;
let base = loop { loop {
let base = match dir.next_entry().await? { let base = match dir.next_entry().await? {
Some(entry) => entry.path(), Some(entry) => entry.path(),
None => bail!("hwmon not found"), None => bail!("hwmon not found"),
}; };
if fs::try_exists(base.join("power1_cap")).await? { if fs::try_exists(base.join(TDP_LIMIT1)).await? {
break base; return Ok(base);
} }
}; }
}
pub async fn get_tdp_limit() -> Result<u32> {
let base = find_hwmon().await?;
let power1cap = fs::read_to_string(base.join(TDP_LIMIT1)).await?;
let power1cap: u32 = power1cap.parse()?;
Ok(power1cap / 1000000)
}
pub async fn set_tdp_limit(limit: u32) -> Result<()> {
// Set TDP limit given if within range (3-15)
// Returns false on error or out of range
ensure!((3..=15).contains(&limit), "Invalid limit");
let data = format!("{limit}000000"); let data = format!("{limit}000000");
let mut power1file = File::create(base.join("power1_cap")) let base = find_hwmon().await?;
let mut power1file = File::create(base.join(TDP_LIMIT1))
.await .await
.inspect_err(|message| { .inspect_err(|message| {
error!("Error opening sysfs power1_cap file for writing TDP limits {message}") error!("Error opening sysfs power1_cap file for writing TDP limits {message}")
@ -95,7 +191,7 @@ pub async fn set_tdp_limit(limit: i32) -> Result<()> {
.await .await
.inspect_err(|message| error!("Error writing to power1_cap file: {message}"))?; .inspect_err(|message| error!("Error writing to power1_cap file: {message}"))?;
if let Ok(mut power2file) = File::create(base.join("power2_cap")).await { if let Ok(mut power2file) = File::create(base.join(TDP_LIMIT2)).await {
power2file power2file
.write(data.as_bytes()) .write(data.as_bytes())
.await .await
@ -105,15 +201,153 @@ pub async fn set_tdp_limit(limit: i32) -> Result<()> {
} }
#[cfg(test)] #[cfg(test)]
mod test { pub mod test {
use super::*; use super::*;
use crate::testing; use crate::testing;
use anyhow::anyhow; use anyhow::anyhow;
use tokio::fs::{create_dir_all, read_to_string, remove_dir, write}; use tokio::fs::{create_dir_all, read_to_string, remove_dir, write};
pub async fn setup() {
let filename = path(GPU_PERFORMANCE_LEVEL_PATH);
create_dir_all(filename.parent().unwrap())
.await
.expect("create_dir_all");
}
pub async fn write_clocks(mhz: u32) {
let filename = path(GPU_CLOCKS_PATH);
create_dir_all(filename.parent().unwrap())
.await
.expect("create_dir_all");
let contents = format!(
"OD_SCLK:
0: {mhz}Mhz
1: {mhz}Mhz
OD_RANGE:
SCLK: 200Mhz 1600Mhz
CCLK: 1400Mhz 3500Mhz
CCLK_RANGE in Core0:
0: 1400Mhz
1: 3500Mhz\n"
);
write(filename.as_path(), contents).await.expect("write");
}
pub async fn expect_clocks(mhz: u32) {
let clocks = read_to_string(path(GPU_CLOCKS_PATH)).await.expect("read");
assert_eq!(clocks, format!("s 0 {mhz}\ns 1 {mhz}\nc\n"));
}
#[tokio::test]
async fn test_get_gpu_performance_level() {
let _h = testing::start();
let filename = path(GPU_PERFORMANCE_LEVEL_PATH);
setup().await;
assert!(get_gpu_performance_level().await.is_err());
write(filename.as_path(), "auto\n").await.expect("write");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::Auto
);
write(filename.as_path(), "low\n").await.expect("write");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::Low
);
write(filename.as_path(), "high\n").await.expect("write");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::High
);
write(filename.as_path(), "manual\n").await.expect("write");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::Manual
);
write(filename.as_path(), "peak_performance\n")
.await
.expect("write");
assert_eq!(
get_gpu_performance_level().await.unwrap(),
GPUPerformanceLevel::ProfilePeak
);
write(filename.as_path(), "nothing\n").await.expect("write");
assert!(get_gpu_performance_level().await.is_err());
}
#[tokio::test]
async fn test_set_gpu_performance_level() {
let _h = testing::start();
let filename = path(GPU_PERFORMANCE_LEVEL_PATH);
setup().await;
set_gpu_performance_level(GPUPerformanceLevel::Auto)
.await
.expect("set");
assert_eq!(
read_to_string(filename.as_path()).await.unwrap().trim(),
"auto"
);
set_gpu_performance_level(GPUPerformanceLevel::Low)
.await
.expect("set");
assert_eq!(
read_to_string(filename.as_path()).await.unwrap().trim(),
"low"
);
set_gpu_performance_level(GPUPerformanceLevel::High)
.await
.expect("set");
assert_eq!(
read_to_string(filename.as_path()).await.unwrap().trim(),
"high"
);
set_gpu_performance_level(GPUPerformanceLevel::Manual)
.await
.expect("set");
assert_eq!(
read_to_string(filename.as_path()).await.unwrap().trim(),
"manual"
);
set_gpu_performance_level(GPUPerformanceLevel::ProfilePeak)
.await
.expect("set");
assert_eq!(
read_to_string(filename.as_path()).await.unwrap().trim(),
"peak_performance"
);
}
#[tokio::test]
async fn test_get_tdp_limit() {
let _h = testing::start();
let hwmon = path(GPU_HWMON_PREFIX);
create_dir_all(hwmon.join("hwmon5").as_path())
.await
.expect("create_dir_all");
assert!(get_tdp_limit().await.is_err());
write(hwmon.join("hwmon5").join(TDP_LIMIT1), "15000000")
.await
.expect("write");
assert_eq!(get_tdp_limit().await.unwrap(), 15);
}
#[tokio::test] #[tokio::test]
async fn test_set_tdp_limit() { async fn test_set_tdp_limit() {
let h = testing::start(); let _h = testing::start();
assert_eq!( assert_eq!(
set_tdp_limit(2).await.unwrap_err().to_string(), set_tdp_limit(2).await.unwrap_err().to_string(),
@ -135,10 +369,10 @@ mod test {
); );
let hwmon = hwmon.join("hwmon5"); let hwmon = hwmon.join("hwmon5");
create_dir_all(hwmon.join("power1_cap")) create_dir_all(hwmon.join(TDP_LIMIT1))
.await .await
.expect("create_dir_all"); .expect("create_dir_all");
create_dir_all(hwmon.join("power2_cap")) create_dir_all(hwmon.join(TDP_LIMIT2))
.await .await
.expect("create_dir_all"); .expect("create_dir_all");
assert_eq!( assert_eq!(
@ -146,28 +380,56 @@ mod test {
anyhow!("Is a directory (os error 21)").to_string() anyhow!("Is a directory (os error 21)").to_string()
); );
remove_dir(hwmon.join("power1_cap")) remove_dir(hwmon.join(TDP_LIMIT1))
.await .await
.expect("remove_dir"); .expect("remove_dir");
write(hwmon.join("power1_cap"), "0").await.expect("write"); write(hwmon.join(TDP_LIMIT1), "0").await.expect("write");
assert!(set_tdp_limit(10).await.is_ok()); assert!(set_tdp_limit(10).await.is_ok());
let power1_cap = read_to_string(hwmon.join("power1_cap")) let power1_cap = read_to_string(hwmon.join(TDP_LIMIT1))
.await .await
.expect("power1_cap"); .expect("power1_cap");
assert_eq!(power1_cap, "10000000"); assert_eq!(power1_cap, "10000000");
remove_dir(hwmon.join("power2_cap")) remove_dir(hwmon.join(TDP_LIMIT2))
.await .await
.expect("remove_dir"); .expect("remove_dir");
write(hwmon.join("power2_cap"), "0").await.expect("write"); write(hwmon.join(TDP_LIMIT2), "0").await.expect("write");
assert!(set_tdp_limit(15).await.is_ok()); assert!(set_tdp_limit(15).await.is_ok());
let power1_cap = read_to_string(hwmon.join("power1_cap")) let power1_cap = read_to_string(hwmon.join(TDP_LIMIT1))
.await .await
.expect("power1_cap"); .expect("power1_cap");
assert_eq!(power1_cap, "15000000"); assert_eq!(power1_cap, "15000000");
let power2_cap = read_to_string(hwmon.join("power2_cap")) let power2_cap = read_to_string(hwmon.join(TDP_LIMIT2))
.await .await
.expect("power2_cap"); .expect("power2_cap");
assert_eq!(power2_cap, "15000000"); assert_eq!(power2_cap, "15000000");
} }
#[tokio::test]
async fn test_get_gpu_clocks() {
let _h = testing::start();
setup().await;
assert!(get_gpu_clocks().await.is_err());
write_clocks(1600).await;
assert_eq!(get_gpu_clocks().await.unwrap(), 1600);
}
#[tokio::test]
async fn test_set_gpu_clocks() {
let _h = testing::start();
assert!(set_gpu_clocks(1600).await.is_err());
setup().await;
assert!(set_gpu_clocks(100).await.is_err());
assert!(set_gpu_clocks(2000).await.is_err());
assert!(set_gpu_clocks(200).await.is_ok());
expect_clocks(200).await;
assert!(set_gpu_clocks(1600).await.is_ok());
expect_clocks(1600).await;
}
} }

View file

@ -5,28 +5,38 @@
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
*/ */
use anyhow::Result; use anyhow::{anyhow, Result};
use std::ffi::OsStr; use std::ffi::OsStr;
#[cfg(not(test))]
use tokio::process::Command; use tokio::process::Command;
use tracing::warn;
pub const SYSTEMCTL_PATH: &str = "/usr/bin/systemctl"; #[cfg(not(test))]
pub async fn script_exit_code(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<i32> {
pub async fn script_exit_code(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<bool> { // Run given script and return the exit code
// Run given script and return true on success
let mut child = Command::new(executable).args(args).spawn()?; let mut child = Command::new(executable).args(args).spawn()?;
let status = child.wait().await?; let status = child.wait().await?;
Ok(status.success()) status.code().ok_or(anyhow!("Killed by signal"))
} }
pub async fn run_script(name: &str, executable: &str, args: &[impl AsRef<OsStr>]) -> Result<bool> { #[cfg(test)]
pub async fn script_exit_code(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<i32> {
let test = crate::testing::current();
let args: Vec<&OsStr> = args.iter().map(|arg| arg.as_ref()).collect();
let cb = test.process_cb.get();
cb(executable, args.as_ref()).map(|(res, _)| res)
}
pub async fn run_script(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<()> {
// Run given script to get exit code and return true on success. // Run given script to get exit code and return true on success.
// Return false on failure, but also print an error if needed // Return Err on failure, but also print an error if needed
script_exit_code(executable, args) match script_exit_code(executable, args).await {
.await Ok(0) => Ok(()),
.inspect_err(|message| warn!("Error running {name} {message}")) Ok(code) => Err(anyhow!("Exited {code}")),
Err(message) => Err(message),
}
} }
#[cfg(not(test))]
pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<String> { pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<String> {
// Run given command and return the output given // Run given command and return the output given
let output = Command::new(executable).args(args).output(); let output = Command::new(executable).args(args).output();
@ -36,3 +46,55 @@ pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Resu
let s = std::str::from_utf8(&output.stdout)?; let s = std::str::from_utf8(&output.stdout)?;
Ok(s.to_string()) Ok(s.to_string())
} }
#[cfg(test)]
pub async fn script_output(executable: &str, args: &[impl AsRef<OsStr>]) -> Result<String> {
let test = crate::testing::current();
let args: Vec<&OsStr> = args.iter().map(|arg| arg.as_ref()).collect();
let cb = test.process_cb.get();
cb(executable, args.as_ref()).map(|(_, res)| res)
}
#[cfg(test)]
mod test {
use super::*;
use crate::testing;
fn ok(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Ok((0, String::from("ok")))
}
fn code(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Ok((1, String::from("code")))
}
fn exit(_: &str, args: &[&OsStr]) -> Result<(i32, String)> {
Err(anyhow!("oops!"))
}
#[tokio::test]
async fn test_run_script() {
let h = testing::start();
h.test.process_cb.set(ok);
assert!(run_script("", &[] as &[&OsStr]).await.is_ok());
h.test.process_cb.set(code);
assert_eq!(
run_script("", &[] as &[&OsStr])
.await
.unwrap_err()
.to_string(),
"Exited 1"
);
h.test.process_cb.set(exit);
assert_eq!(
run_script("", &[] as &[&OsStr])
.await
.unwrap_err()
.to_string(),
"oops!"
);
}
}

View file

@ -117,10 +117,8 @@ mod test {
use crate::testing; use crate::testing;
use nix::sys::stat::Mode; use nix::sys::stat::Mode;
use nix::unistd; use nix::unistd;
use std::cell::Cell; use tokio::fs::{create_dir_all, read_to_string, write};
use std::fs; use tokio::sync::mpsc::{error, unbounded_channel, UnboundedSender};
use std::path::PathBuf;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
struct MockTrace { struct MockTrace {
traces: UnboundedSender<(String, HashMap<String, zvariant::OwnedValue>)>, traces: UnboundedSender<(String, HashMap<String, zvariant::OwnedValue>)>,
@ -133,7 +131,7 @@ mod test {
trace: &str, trace: &str,
data: HashMap<&str, zvariant::Value<'_>>, data: HashMap<&str, zvariant::Value<'_>>,
) -> zbus::fdo::Result<()> { ) -> zbus::fdo::Result<()> {
self.traces.send(( let _ = self.traces.send((
String::from(trace), String::from(trace),
HashMap::from_iter( HashMap::from_iter(
data.iter() data.iter()
@ -146,18 +144,31 @@ mod test {
#[tokio::test] #[tokio::test]
async fn handle_pid() { async fn handle_pid() {
let h = testing::start(); let _h = testing::start();
let path = h.test.path();
fs::create_dir_all(path.join("proc/1234")).expect("create_dir_all"); create_dir_all(path("/proc/1234"))
fs::write(path.join("proc/1234/comm"), "ftrace\n").expect("write comm"); .await
fs::write(path.join("proc/1234/environ"), "SteamGameId=5678").expect("write environ"); .expect("create_dir_all");
write(path("/proc/1234/comm"), "ftrace\n")
.await
.expect("write comm");
write(path("/proc/1234/environ"), "SteamGameId=5678")
.await
.expect("write environ");
fs::create_dir_all(path.join("proc/1235")).expect("create_dir_all"); create_dir_all(path("/proc/1235"))
fs::write(path.join("proc/1235/comm"), "ftrace\n").expect("write comm"); .await
.expect("create_dir_all");
write(path("/proc/1235/comm"), "ftrace\n")
.await
.expect("write comm");
fs::create_dir_all(path.join("proc/1236")).expect("create_dir_all"); create_dir_all(path("/proc/1236"))
fs::write(path.join("proc/1236/environ"), "SteamGameId=5678").expect("write environ"); .await
.expect("create_dir_all");
write(path("/proc/1236/environ"), "SteamGameId=5678")
.await
.expect("write environ");
let mut map = HashMap::new(); let mut map = HashMap::new();
assert!(Ftrace::handle_pid(&mut map, 1234).await.is_ok()); assert!(Ftrace::handle_pid(&mut map, 1234).await.is_ok());
@ -189,43 +200,53 @@ mod test {
#[tokio::test] #[tokio::test]
async fn ftrace_init() { async fn ftrace_init() {
let h = testing::start(); let _h = testing::start();
let path = h.test.path();
let tracefs = Ftrace::base(); let tracefs = Ftrace::base();
fs::create_dir_all(tracefs.join("events/oom/mark_victim")).expect("create_dir_all"); create_dir_all(tracefs.join("events/oom/mark_victim"))
.await
.expect("create_dir_all");
unistd::mkfifo( unistd::mkfifo(
tracefs.join("trace_pipe").as_path(), tracefs.join("trace_pipe").as_path(),
Mode::S_IRUSR | Mode::S_IWUSR, Mode::S_IRUSR | Mode::S_IWUSR,
) )
.expect("trace_pipe"); .expect("trace_pipe");
let dbus = Connection::session().await.expect("dbus"); let dbus = Connection::session().await.expect("dbus");
let ftrace = Ftrace::init(dbus).await.expect("ftrace"); let _ftrace = Ftrace::init(dbus).await.expect("ftrace");
assert_eq!( assert_eq!(
fs::read_to_string(tracefs.join("events/oom/mark_victim/enable")).unwrap(), read_to_string(tracefs.join("events/oom/mark_victim/enable"))
.await
.unwrap(),
"1" "1"
); );
} }
#[tokio::test] #[tokio::test]
async fn ftrace_relay() { async fn ftrace_relay() {
let h = testing::start(); let _h = testing::start();
let path = h.test.path();
let tracefs = Ftrace::base(); let tracefs = Ftrace::base();
fs::create_dir_all(tracefs.join("events/oom/mark_victim")).expect("create_dir_all"); create_dir_all(tracefs.join("events/oom/mark_victim"))
.await
.expect("create_dir_all");
unistd::mkfifo( unistd::mkfifo(
tracefs.join("trace_pipe").as_path(), tracefs.join("trace_pipe").as_path(),
Mode::S_IRUSR | Mode::S_IWUSR, Mode::S_IRUSR | Mode::S_IWUSR,
) )
.expect("trace_pipe"); .expect("trace_pipe");
fs::create_dir_all(path.join("proc/14351")).expect("create_dir_all"); create_dir_all(path("/proc/14351"))
fs::write(path.join("proc/14351/comm"), "ftrace\n").expect("write comm"); .await
fs::write(path.join("proc/14351/environ"), "SteamGameId=5678").expect("write environ"); .expect("create_dir_all");
write(path("/proc/14351/comm"), "ftrace\n")
.await
.expect("write comm");
write(path("/proc/14351/environ"), "SteamGameId=5678")
.await
.expect("write environ");
let (sender, mut receiver) = unbounded_channel(); let (sender, mut receiver) = unbounded_channel();
let trace = MockTrace { traces: sender }; let trace = MockTrace { traces: sender };
@ -241,7 +262,7 @@ mod test {
let mut ftrace = Ftrace::init(dbus).await.expect("ftrace"); let mut ftrace = Ftrace::init(dbus).await.expect("ftrace");
assert!(match receiver.try_recv() { assert!(match receiver.try_recv() {
Empty => true, Err(error::TryRecvError::Empty) => true,
_ => false, _ => false,
}); });
ftrace ftrace

76
src/systemd.rs Normal file
View file

@ -0,0 +1,76 @@
/*
* Copyright © 2023 Collabora Ltd.
* Copyright © 2024 Valve Software
*
* SPDX-License-Identifier: MIT
*/
use anyhow::{anyhow, Result};
use std::path::PathBuf;
use zbus::zvariant::OwnedObjectPath;
use zbus::Connection;
#[zbus::proxy(
interface = "org.freedesktop.systemd1.Unit",
default_service = "org.freedesktop.systemd1"
)]
trait SystemdUnit {
#[zbus(property)]
fn active_state(&self) -> Result<String>;
async fn restart(&self, mode: &str) -> Result<OwnedObjectPath>;
async fn start(&self, mode: &str) -> Result<OwnedObjectPath>;
async fn stop(&self, mode: &str) -> Result<OwnedObjectPath>;
}
#[zbus::proxy(
interface = "org.freedesktop.systemd1.Manager",
default_service = "org.freedesktop.systemd1",
default_path = "/org/freedesktop/systemd1"
)]
trait SystemdManager {
async fn reload(&self) -> Result<()>;
}
pub struct SystemdUnit<'dbus> {
proxy: SystemdUnitProxy<'dbus>,
}
pub async fn daemon_reload(connection: &Connection) -> Result<()> {
let proxy = SystemdManagerProxy::new(&connection).await?;
proxy.reload().await?;
Ok(())
}
impl<'dbus> SystemdUnit<'dbus> {
pub async fn new(connection: Connection, name: &str) -> Result<SystemdUnit<'dbus>> {
let path = PathBuf::from("/org/freedesktop/systemd1/unit").join(name);
let path = String::from(path.to_str().ok_or(anyhow!("Unit name {name} invalid"))?);
Ok(SystemdUnit {
proxy: SystemdUnitProxy::builder(&connection)
.cache_properties(zbus::CacheProperties::No)
.path(path)?
.build()
.await?,
})
}
pub async fn restart(&self) -> Result<()> {
self.proxy.restart("fail").await?;
Ok(())
}
pub async fn start(&self) -> Result<()> {
self.proxy.start("fail").await?;
Ok(())
}
pub async fn stop(&self) -> Result<()> {
self.proxy.stop("fail").await?;
Ok(())
}
pub async fn active(&self) -> Result<bool> {
Ok(self.proxy.active_state().await? == "active")
}
}

View file

@ -1,4 +1,6 @@
use std::cell::RefCell; use anyhow::{anyhow, Result};
use std::cell::{Cell, RefCell};
use std::ffi::OsStr;
use std::path::Path; use std::path::Path;
use std::rc::Rc; use std::rc::Rc;
use tempfile::{tempdir, TempDir}; use tempfile::{tempdir, TempDir};
@ -12,6 +14,7 @@ pub fn start() -> TestHandle {
assert!(lock.borrow().as_ref().is_none()); assert!(lock.borrow().as_ref().is_none());
let test: Rc<Test> = Rc::new(Test { let test: Rc<Test> = Rc::new(Test {
base: tempdir().expect("Couldn't create test directory"), base: tempdir().expect("Couldn't create test directory"),
process_cb: Cell::new(|_, _| Err(anyhow!("No current process_cb"))),
}); });
*lock.borrow_mut() = Some(test.clone()); *lock.borrow_mut() = Some(test.clone());
TestHandle { test } TestHandle { test }
@ -28,6 +31,7 @@ pub fn current() -> Rc<Test> {
pub struct Test { pub struct Test {
base: TempDir, base: TempDir,
pub process_cb: Cell<fn(&str, &[&OsStr]) -> Result<(i32, String)>>,
} }
pub struct TestHandle { pub struct TestHandle {

View file

@ -5,12 +5,16 @@
* SPDX-License-Identifier: MIT * SPDX-License-Identifier: MIT
*/ */
use anyhow::Result; use anyhow::{bail, ensure, Error, Result};
use std::fmt; use std::fmt;
use std::str::FromStr;
use tokio::fs; use tokio::fs;
use tracing::error; use tracing::error;
use zbus::Connection;
use crate::process::{run_script, SYSTEMCTL_PATH}; use crate::path;
use crate::process::run_script;
use crate::systemd::{daemon_reload, SystemdUnit};
const OVERRIDE_CONTENTS: &str = "[Service] const OVERRIDE_CONTENTS: &str = "[Service]
ExecStart= ExecStart=
@ -24,19 +28,29 @@ const OVERRIDE_PATH: &str = "/etc/systemd/system/iwd.service.d/override.conf";
const OUTPUT_FILE: &str = "/var/log/wifitrace.dat"; const OUTPUT_FILE: &str = "/var/log/wifitrace.dat";
const TRACE_CMD_PATH: &str = "/usr/bin/trace-cmd"; const TRACE_CMD_PATH: &str = "/usr/bin/trace-cmd";
const MIN_BUFFER_SIZE: u32 = 100;
const WIFI_BACKEND_PATH: &str = "/etc/NetworkManager/conf.d/wifi_backend.conf";
#[derive(PartialEq, Debug, Copy, Clone)] #[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)] #[repr(u32)]
pub enum WifiDebugMode { pub enum WifiDebugMode {
Off, Off = 0,
On, On = 1,
} }
#[derive(PartialEq, Debug, Copy, Clone)] #[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)] #[repr(u32)]
pub enum WifiPowerManagement { pub enum WifiPowerManagement {
UnsupportedFeature = 0, Disabled = 0,
Disabled = 1, Enabled = 1,
Enabled = 2, }
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
pub enum WifiBackend {
IWD = 0,
WPASupplicant = 1,
} }
impl TryFrom<u32> for WifiDebugMode { impl TryFrom<u32> for WifiDebugMode {
@ -63,9 +77,6 @@ impl TryFrom<u32> for WifiPowerManagement {
type Error = &'static str; type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> { fn try_from(v: u32) -> Result<Self, Self::Error> {
match v { match v {
x if x == WifiPowerManagement::UnsupportedFeature as u32 => {
Ok(WifiPowerManagement::UnsupportedFeature)
}
x if x == WifiPowerManagement::Disabled as u32 => Ok(WifiPowerManagement::Disabled), x if x == WifiPowerManagement::Disabled as u32 => Ok(WifiPowerManagement::Disabled),
x if x == WifiPowerManagement::Enabled as u32 => Ok(WifiPowerManagement::Enabled), x if x == WifiPowerManagement::Enabled as u32 => Ok(WifiPowerManagement::Enabled),
_ => Err("No enum match for value {v}"), _ => Err("No enum match for value {v}"),
@ -76,13 +87,43 @@ impl TryFrom<u32> for WifiPowerManagement {
impl fmt::Display for WifiPowerManagement { impl fmt::Display for WifiPowerManagement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
WifiPowerManagement::UnsupportedFeature => write!(f, "Unsupported feature"),
WifiPowerManagement::Disabled => write!(f, "Disabled"), WifiPowerManagement::Disabled => write!(f, "Disabled"),
WifiPowerManagement::Enabled => write!(f, "Enabled"), WifiPowerManagement::Enabled => write!(f, "Enabled"),
} }
} }
} }
impl TryFrom<u32> for WifiBackend {
type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> {
match v {
x if x == WifiBackend::IWD as u32 => Ok(WifiBackend::IWD),
x if x == WifiBackend::WPASupplicant as u32 => Ok(WifiBackend::WPASupplicant),
_ => Err("No enum match for WifiBackend value {v}"),
}
}
}
impl FromStr for WifiBackend {
type Err = Error;
fn from_str(input: &str) -> Result<WifiBackend, Self::Err> {
Ok(match input {
"iwd" => WifiBackend::IWD,
"wpa_supplicant" => WifiBackend::WPASupplicant,
_ => bail!("Unknown backend"),
})
}
}
impl fmt::Display for WifiBackend {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WifiBackend::IWD => write!(f, "iwd"),
WifiBackend::WPASupplicant => write!(f, "wpa_supplicant"),
}
}
}
pub async fn setup_iwd_config(want_override: bool) -> std::io::Result<()> { pub async fn setup_iwd_config(want_override: bool) -> std::io::Result<()> {
// Copy override.conf file into place or out of place depending // Copy override.conf file into place or out of place depending
// on install value // on install value
@ -90,55 +131,160 @@ pub async fn setup_iwd_config(want_override: bool) -> std::io::Result<()> {
if want_override { if want_override {
// Copy it in // Copy it in
// Make sure the folder exists // Make sure the folder exists
fs::create_dir_all(OVERRIDE_FOLDER).await?; fs::create_dir_all(path(OVERRIDE_FOLDER)).await?;
// Then write the contents into the file // Then write the contents into the file
fs::write(OVERRIDE_PATH, OVERRIDE_CONTENTS).await fs::write(path(OVERRIDE_PATH), OVERRIDE_CONTENTS).await
} else { } else {
// Delete it // Delete it
fs::remove_file(OVERRIDE_PATH).await fs::remove_file(path(OVERRIDE_PATH)).await
} }
} }
pub async fn restart_iwd() -> Result<bool> { async fn restart_iwd(connection: Connection) -> Result<()> {
// First reload systemd since we modified the config most likely // First reload systemd since we modified the config most likely
// otherwise we wouldn't be restarting iwd. // otherwise we wouldn't be restarting iwd.
match run_script("reload systemd", SYSTEMCTL_PATH, &["daemon-reload"]).await { daemon_reload(&connection)
Ok(value) => { .await
if value { .inspect_err(|message| error!("restart_iwd: reload systemd got an error: {message}"))?;
// worked, now restart iwd
run_script("restart iwd", SYSTEMCTL_PATH, &["restart", "iwd"]).await // worked, now restart iwd
} else { let unit = SystemdUnit::new(connection, "iwd_2eservice").await?;
// reload failed unit.restart()
error!("restart_iwd: reload systemd failed with non-zero exit code"); .await
Ok(false) .inspect_err(|message| error!("restart_iwd: restart unit got an error: {message}"))
}
}
Err(message) => {
error!("restart_iwd: reload systemd got an error: {message}");
Err(message)
}
}
} }
pub async fn stop_tracing() -> Result<bool> { async fn stop_tracing() -> Result<()> {
// Stop tracing and extract ring buffer to disk for capture // Stop tracing and extract ring buffer to disk for capture
run_script("stop tracing", TRACE_CMD_PATH, &["stop"]).await?; run_script(TRACE_CMD_PATH, &["stop"]).await?;
// stop tracing worked // stop tracing worked
run_script( run_script(TRACE_CMD_PATH, &["extract", "-o", OUTPUT_FILE]).await
"extract traces",
TRACE_CMD_PATH,
&["extract", "-o", OUTPUT_FILE],
)
.await
} }
pub async fn start_tracing(buffer_size: u32) -> Result<bool> { async fn start_tracing(buffer_size: u32) -> Result<()> {
// Start tracing // Start tracing
let size_str = format!("{}", buffer_size); let size_str = buffer_size.to_string();
run_script( run_script(
"start tracing",
TRACE_CMD_PATH, TRACE_CMD_PATH,
&["start", "-e", "ath11k_wmi_diag", "-b", &size_str], &["start", "-e", "ath11k_wmi_diag", "-b", &size_str],
) )
.await .await
} }
pub async fn set_wifi_debug_mode(
mode: WifiDebugMode,
buffer_size: u32,
should_trace: bool,
connection: Connection,
) -> Result<()> {
// Set the wifi debug mode to mode, using an int for flexibility going forward but only
// doing things on 0 or 1 for now
// Return false on error
match mode {
WifiDebugMode::Off => {
// If mode is 0 disable wifi debug mode
// Stop any existing trace and flush to disk.
if should_trace {
if let Err(message) = stop_tracing().await {
bail!("stop_tracing command got an error: {message}");
};
}
// Stop_tracing was successful
if let Err(message) = setup_iwd_config(false).await {
bail!("setup_iwd_config false got an error: {message}");
};
// setup_iwd_config false worked
if let Err(message) = restart_iwd(connection).await {
bail!("restart_iwd got an error: {message}");
};
}
WifiDebugMode::On => {
ensure!(buffer_size > MIN_BUFFER_SIZE, "Buffer size too small");
if let Err(message) = setup_iwd_config(true).await {
bail!("setup_iwd_config true got an error: {message}");
}
// setup_iwd_config worked
if let Err(message) = restart_iwd(connection).await {
bail!("restart_iwd got an error: {message}");
};
// restart_iwd worked
if should_trace {
if let Err(message) = start_tracing(buffer_size).await {
bail!("start_tracing got an error: {message}");
};
}
}
}
Ok(())
}
pub async fn get_wifi_backend() -> Result<WifiBackend> {
let wifi_backend_contents = fs::read_to_string(path(WIFI_BACKEND_PATH))
.await?
.trim()
.to_string();
for line in wifi_backend_contents.lines() {
if line.starts_with("wifi.backend=") {
let backend = line.trim_start_matches("wifi.backend=").trim();
return WifiBackend::from_str(backend);
}
}
bail!("WiFi backend not found in config");
}
pub async fn set_wifi_backend(backend: WifiBackend) -> Result<()> {
run_script("/usr/bin/steamos-wifi-set-backend", &[backend.to_string()]).await
}
#[cfg(test)]
mod test {
use super::*;
use crate::testing;
use tokio::fs::{create_dir_all, write};
#[tokio::test]
async fn test_wifi_backend_to_string() {
assert_eq!(WifiBackend::IWD.to_string(), "iwd");
assert_eq!(WifiBackend::WPASupplicant.to_string(), "wpa_supplicant");
}
#[tokio::test]
async fn test_get_wifi_backend() {
let _h = testing::start();
create_dir_all(path(WIFI_BACKEND_PATH).parent().unwrap())
.await
.expect("create_dir_all");
assert!(get_wifi_backend().await.is_err());
write(path(WIFI_BACKEND_PATH), "[device]")
.await
.expect("write");
assert!(get_wifi_backend().await.is_err());
write(path(WIFI_BACKEND_PATH), "[device]\nwifi.backend=fake\n")
.await
.expect("write");
assert!(get_wifi_backend().await.is_err());
write(path(WIFI_BACKEND_PATH), "[device]\nwifi.backend=iwd\n")
.await
.expect("write");
assert_eq!(get_wifi_backend().await.unwrap(), WifiBackend::IWD);
write(
path(WIFI_BACKEND_PATH),
"[device]\nwifi.backend=wpa_supplicant\n",
)
.await
.expect("write");
assert_eq!(
get_wifi_backend().await.unwrap(),
WifiBackend::WPASupplicant
);
}
}