RESTRICT AUTOMERGE: maxfg: add mutex while logs the latest entry am: 6702fca80e

Original change: https://partner-android-review.googlesource.com/c/kernel/private/google-modules/bms/+/2762295

Change-Id: Ie6907d64d0033e8bbd0ecf143362bf0b84ddf96f
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/max1720x_battery.c b/max1720x_battery.c
index a5601e1..8db5461 100644
--- a/max1720x_battery.c
+++ b/max1720x_battery.c
@@ -2274,19 +2274,28 @@
 
 static int max1720x_monitor_log_learning(struct max1720x_chip *chip, bool force)
 {
-	const bool seed = !chip->cb_lh.latest_entry;
-	bool log_it;
+	bool log_it, seed;
 	char *buf;
 	int ret;
+	u16* last_entry;
+
+	mutex_lock(&chip->cb_lh.cb_wr_lock);
+	seed = !chip->cb_lh.latest_entry;
 
 	/* do nothing if no changes on dpacc/dqacc or relaxation */
 	log_it = force || seed ||
 	         maxfg_ce_relaxed(&chip->regmap,  MAX_M5_FSTAT_RELDT | MAX_M5_FSTAT_RELDT2,
 				(u16 *)chip->cb_lh.latest_entry);
-	if (!log_it)
+	if (!log_it) {
+		mutex_unlock(&chip->cb_lh.cb_wr_lock);
 		return 0;
+	}
 
 	ret = maxfg_capture_registers(&chip->cb_lh);
+	last_entry = chip->cb_lh.latest_entry;
+
+	mutex_unlock(&chip->cb_lh.cb_wr_lock);
+
 	if (ret < 0) {
 		dev_dbg(chip->dev, "cannot read learning parameters (%d)\n", ret);
 		return ret;
@@ -2301,7 +2310,7 @@
 		return -ENOMEM;
 
 	ret = maxfg_capture_to_cstr(&chip->cb_lh.config,
-				    (u16 *)chip->cb_lh.latest_entry,
+				    last_entry,
 				    buf, PAGE_SIZE);
 	if (ret > 0)
 		gbms_logbuffer_devlog(chip->monitor_log, chip->dev,
diff --git a/maxfg_logging.c b/maxfg_logging.c
index d4acc0a..17f5a8b 100644
--- a/maxfg_logging.c
+++ b/maxfg_logging.c
@@ -73,15 +73,25 @@
 
 void maxfg_clear_capture_buf(struct maxfg_capture_buf *buf)
 {
+	int head, tail;
 	if (!buf)
 		return;
 
 	mutex_lock(&buf->cb_wr_lock);
 	mutex_lock(&buf->cb_rd_lock);
 
-	buf->latest_entry = NULL;
-	buf->cb.head = 0;
-	buf->cb.tail = 0;
+	head = buf->cb.head;
+	tail = buf->cb.tail;
+
+	if (CIRC_CNT(head, tail, buf->slots)) {
+		head = (head + 1) & (buf->slots - 1);
+
+		smp_wmb();
+
+		/* make buffer empty by (head == tail) while preserving latest_entry as a seed */
+		WRITE_ONCE(buf->cb.head, head);
+		WRITE_ONCE(buf->cb.tail, head);
+	}
 
 	mutex_unlock(&buf->cb_rd_lock);
 	mutex_unlock(&buf->cb_wr_lock);
@@ -125,8 +135,6 @@
 	int head, tail, ret;
 	u16 *reg_val;
 
-	mutex_lock(&buf->cb_wr_lock);
-
 	head = buf->cb.head;
 	tail = READ_ONCE(buf->cb.tail);
 
@@ -156,7 +164,6 @@
 	buf->latest_entry = latest_entry;
 
 exit_done:
-	mutex_unlock(&buf->cb_wr_lock);
 	return ret;
 }