From 97147f5880f1f1f65541e49ea9141508baf648ad Mon Sep 17 00:00:00 2001
From: Ondrej Jirman <megi@xff.cz>
Date: Thu, 7 Sep 2023 17:37:59 +0200
Subject: [PATCH 411/463] power: supply: rk817-charger: Take input current
 limit from parent supply

This allows automatic input current limit setting based on USB PD.

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

diff --git a/drivers/power/supply/rk817_charger.c b/drivers/power/supply/rk817_charger.c
index 833b12cfccedc..9de86fc8f3fa5 100644
--- a/drivers/power/supply/rk817_charger.c
+++ b/drivers/power/supply/rk817_charger.c
@@ -53,6 +53,7 @@ struct rk817_charger {
 	struct power_supply *chg_ps;
 	bool plugged_in;
 	bool battery_present;
+	bool apply_ilim;
 
 	/*
 	 * voltage_k and voltage_b values are used to calibrate the ADC
@@ -677,6 +678,38 @@ static int rk817_chg_set_prop(struct power_supply *ps,
 
 }
 
+/* Sync the input-current-limit with our parent supply (if we have one) */
+static void rk817_usb_power_external_power_changed(struct power_supply *psy)
+{
+        struct rk817_charger *charger = power_supply_get_drvdata(psy);
+	union power_supply_propval val;
+	int ret;
+
+	ret = power_supply_get_property_from_supplier(charger->chg_ps,
+						      POWER_SUPPLY_PROP_CURRENT_MAX,
+						      &val);
+	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 (!charger->apply_ilim) {
+		if (!val.intval)
+			return;
+
+		charger->apply_ilim = true;
+	}
+
+	if (val.intval < 500000)
+		val.intval = 500000;
+
+	rk817_chg_set_prop(charger->chg_ps, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
+}
+
 static irqreturn_t rk817_plug_in_isr(int irq, void *cg)
 {
 	struct rk817_charger *charger;
@@ -784,6 +817,7 @@ static const struct power_supply_desc rk817_chg_desc = {
 	.property_is_writeable	= rk817_charger_prop_writeable,
 	.get_property = rk817_chg_get_prop,
 	.set_property = rk817_chg_set_prop,
+	.external_power_changed	= rk817_usb_power_external_power_changed,
 };
 
 static int rk817_read_battery_nvram_values(struct rk817_charger *charger)
@@ -1290,6 +1324,8 @@ static int rk817_charger_probe(struct platform_device *pdev)
 	/* Force the first update immediately. */
 	mod_delayed_work(system_wq, &charger->work, 0);
 
+	rk817_usb_power_external_power_changed(charger->chg_ps);
+
 	return 0;
 }
 
-- 
2.46.0

