[PATCH] Fix battery runtime estimation with negative sysfs values

Anthony Ruhier <[email protected]> Mon, 24 Feb 2025 02:25:53 +0100
Newsgroups dev.linux.lists.powertop
Message-ID <[email protected]>
Some drivers (example: qualcomm-battmgr, present on Snapdragon X1
laptops) expose the current_now and power_now values in sysfs as
negative int when the device is discharging, positive when charging.

This breaks the battery runtime estimation in Powertop, as it expects a
uint for power_now.

Change the battery module to use the absolute values of current_now and
power_now.

---
Signed-off-by: Anthony Ruhier <[email protected]>
---
 src/measurement/sysfs.cpp | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/src/measurement/sysfs.cpp b/src/measurement/sysfs.cpp
index c5a7a12d08db2f3cea10746d16591e28465c610c..6cc7f433910d35edf7e9f2c2d04c107c27ec797a 100644
--- a/src/measurement/sysfs.cpp
+++ b/src/measurement/sysfs.cpp
@@ -75,8 +75,10 @@ bool sysfs_power_meter::set_rate_from_power()
 	if (!get_sysfs_attr("power_now", &power))
 		return false;

-	/* µW to W */
-	rate = power / 1000000.0;
+	/* µW to W
+	 * Some drivers (example: Qualcomm) exposes use a negative value when
+	 * discharging, positive value when charging, so use the absolute value. */
+	rate = std::abs(power) / 1000000.0;
 	return true;
 }

@@ -89,8 +91,10 @@ bool sysfs_power_meter::set_rate_from_current(double voltage)

 	/* current: µA
 	 * voltage: V
-	 * rate: W */
-	rate = (current / 1000000.0) * voltage;
+	 * rate: W
+	 * Documentation ABI allows a negative value when discharging, positive
+	 * value when charging, so use the absolute value. */
+	rate = (std::abs(current) / 1000000.0) * voltage;
 	return true;
 }


---
base-commit: 9beafe3bd5e9d4c6cf2596dacdf6ab9c9be0c85e
change-id: 20250224-patch-sysfs-7489fdab01aa

Best regards,
--
Anthony Ruhier <[email protected]>