health: fix learned capacity backup/restore

The code was only allowing the Learned Capacity to decrease while
QCOM FG learned capacity may actually go up for some reasons.
Ensure we use the FG learned capacity on update and always restore
the saved one on boot.

Bug: 109734601
Change-Id: I13ff3f662e423fda59779b8c9a491956ebd65c5a
Signed-off-by: Thierry Strudel <tstrudel@google.com>
diff --git a/health/LearnedCapacityBackupRestore.cpp b/health/LearnedCapacityBackupRestore.cpp
index f34b909..bf72526 100644
--- a/health/LearnedCapacityBackupRestore.cpp
+++ b/health/LearnedCapacityBackupRestore.cpp
@@ -25,17 +25,28 @@
 static constexpr char kSysCFPersistFile[] = "/persist/battery/qcom_charge_full";
 static constexpr int kBuffSize = 256;
 
-LearnedCapacityBackupRestore::LearnedCapacityBackupRestore() {}
+LearnedCapacityBackupRestore::LearnedCapacityBackupRestore() : sw_cap_(0), hw_cap_(0) {}
 
 void LearnedCapacityBackupRestore::Restore() {
     ReadFromStorage();
     ReadFromSRAM();
-    UpdateAndSave();
+    if (sw_cap_ == 0) {
+        // First backup
+        sw_cap_ = hw_cap_;
+        SaveToStorage();
+    } else {
+        // Always restore backup value
+        SaveToSRAM();
+    }
 }
 
 void LearnedCapacityBackupRestore::Backup() {
     ReadFromSRAM();
-    UpdateAndSave();
+    if (sw_cap_ != hw_cap_) {
+        // Always backup the new FG computed learned capacity
+        sw_cap_ = hw_cap_;
+        SaveToStorage();
+    }
 }
 
 void LearnedCapacityBackupRestore::ReadFromStorage() {
@@ -90,24 +101,6 @@
         LOG(ERROR) << "Write data error: " << strerror(errno);
 }
 
-void LearnedCapacityBackupRestore::UpdateAndSave() {
-    bool backup = false;
-    bool restore = false;
-    if (hw_cap_) {
-        if ((hw_cap_ < sw_cap_) || (sw_cap_ == 0)) {
-            sw_cap_ = hw_cap_;
-            backup = true;
-        } else if (hw_cap_ > sw_cap_) {
-            hw_cap_ = sw_cap_;
-            restore = true;
-        }
-    }
-    if (restore)
-        SaveToSRAM();
-    if (backup)
-        SaveToStorage();
-}
-
 }  // namespace health
 }  // namespace marlin
 }  // namespace google
diff --git a/health/LearnedCapacityBackupRestore.h b/health/LearnedCapacityBackupRestore.h
index 4e40ab5..8b52343 100644
--- a/health/LearnedCapacityBackupRestore.h
+++ b/health/LearnedCapacityBackupRestore.h
@@ -41,7 +41,6 @@
     void SaveToStorage();
     void ReadFromSRAM();
     void SaveToSRAM();
-    void UpdateAndSave();
 };
 
 }  // namespace health