From 50437164a91ddf92554de6f354d81bc76040ba9b Mon Sep 17 00:00:00 2001
From: Ondrej Jirman <megi@xff.cz>
Date: Tue, 2 Aug 2022 09:37:05 +0200
Subject: [PATCH 333/463] power: supply: rk818-charger: Delay applying input
 current limit until first BC detection finishes

When the phone boots for the first time, we only want to react to
changes in charger power supply max current after the USB power supply
type detection finishes. This allows us to keep the limit set by
the bootloader, until we know better.

This is part of the workaround for Pinephone Pro boot loops on low battery.
The other part is bootloader raising the input current limit to 2A.

Signed-off-by: Ondrej Jirman <megi@xff.cz>
---
 drivers/power/supply/rk818_charger.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/drivers/power/supply/rk818_charger.c b/drivers/power/supply/rk818_charger.c
index 15b0cce6aecc2..0325225fe53ab 100644
--- a/drivers/power/supply/rk818_charger.c
+++ b/drivers/power/supply/rk818_charger.c
@@ -52,6 +52,8 @@ struct rk818_charger {
 
 	struct power_supply *usb_psy;
 	struct power_supply *charger_psy;
+
+	bool apply_ilim;
 };
 
 // {{{ USB supply
@@ -73,6 +75,8 @@ static int rk818_usb_set_input_current_max(struct rk818_charger *cg,
 	else
 		reg = 11;
 
+	dev_info(cg->dev, "applying input current limit %d mA\n", val / 1000);
+
 	ret = regmap_update_bits(cg->regmap, RK818_USB_CTRL_REG,
 				 RK818_USB_CTRL_USB_ILIM_MASK, reg);
 	if (ret)
@@ -243,6 +247,19 @@ static void rk818_usb_power_external_power_changed(struct power_supply *psy)
 	if (ret)
 		return;
 
+	/*
+	 * We only want to start applying input current limit after we get first
+	 * non-0 value from the supplier. Until then, we keep the limit applied
+	 * by the bootloader. If we lower the limit before the charger is properly
+	 * detected, we risk boot failure due to insufficient power.
+	 */
+	if (!cg->apply_ilim) {
+		if (!val.intval)
+			return;
+
+		cg->apply_ilim = true;
+	}
+
 	if (val.intval < 500000)
 		val.intval = 500000;
 
-- 
2.46.0

