From ebf0be8ba5fd18829a2ef5f206f8a58fea964df0 Mon Sep 17 00:00:00 2001 From: Claudius Date: Tue, 24 Nov 2026 16:06:18 +0000 Subject: [PATCH] STARLTE: the charger watched and guarded (sweetchg=2, on by default), the fast-charge path (sweetafc=1, off) iOS 27 only read the S9's fuel gauge. S-Boot leaves the MAX77705 charger's watchdog on and nothing kicked it, so the charger stopped about 70 s after every boot (DETAILS_01 0x33 -> 0x3b, measured on phone 2), and iOS was told a fixed 25 C battery with nothing to stop charging when hot or cold. bsd/dev/starlte_charger.c, every second, on starlte_muic.c's bus (its lock, now shared): - sweetchg=1: read only. The charger, the MUIC, the gauge and the two thermistors (CMGP's ADC, channels 4 and 3, the phone's own table) read; SweetBattery gets the real battery temperature, "charging" and "full" from the charger's own state, and the adapter's details (type, volts, amps); the log says what the guard would do. - sweetchg=2 (now in the kernel's default line): the guard. Volatile charger registers only, each write read back: the watchdog kicked every 10 s and re-armed if it expired; charging on or off by Samsung's temperature bands (off at 41 C until 39 C, at 5 C until 10 C; 700 mA at 15 C), session timers, full and recharge; the input limit and charge current set to Samsung's for the charger type (SDP 475/550, CDP 1500/1500, DCP 1800/2100) or less. A fault, 45 C, the float above 4350 mV or a read-back that differs latches charging off until the cable goes. The float voltage, the timers and every other register are never written; nothing non-volatile. - sweetafc=1 (off by default): on a DCP inside its band (battery 15-39 C, charger under 44 C, under 98 %, no fault), the switch opened and Samsung's 9 V request sent; 9 V taken only on result 0 with VBUS 7.5-10.5 V in the answer and in USBC_STATUS1, then 1650/2150 mA; dropped back (500 mA, 5 V asked) the second any condition stops holding. Never on a computer port. Not run against a fast charger yet (phone 2 is on a computer). - sweetchg_drain=MIN (a test): the first MIN minutes on the battery (input 100 mA, charging off). - kern.hakios.chg_* for the console. The rules are bsd/dev/hakios.max77705_charge.h, a copy of scion-kernel's drivers/power/max77705/hakios.max77705_charge.h, which tools/max77705-charge-test.sh tests on a computer. starlte_muic.c leaves the switch open on a DCP when the 9 V path is on. Facts and the owner's test plan: scion-kernel docs/ios27/CHARGING.md and CHARGING-TEST.md. --- bsd/conf/files | 1 + bsd/dev/hakios.max77705_charge.h | 488 ++++++++++++++++++++++++++ bsd/dev/starlte_charger.c | 555 ++++++++++++++++++++++++++++++ bsd/dev/starlte_muic.c | 29 ++ iokit/Kernel/arm/SweetBattery.cpp | 86 ++++- osfmk/arm/arm_init.c | 3 + 6 files changed, 1158 insertions(+), 4 deletions(-) create mode 100644 bsd/dev/hakios.max77705_charge.h create mode 100644 bsd/dev/starlte_charger.c diff --git a/bsd/conf/files b/bsd/conf/files index f966983e8..c825b2b47 100644 --- a/bsd/conf/files +++ b/bsd/conf/files @@ -120,6 +120,7 @@ bsd/dev/starlte_usbcon.c optional scion_generic_arm64 bsd/dev/starlte_warm.c optional scion_generic_arm64 bsd/dev/starlte_guard.c optional scion_generic_arm64 bsd/dev/starlte_muic.c optional scion_generic_arm64 +bsd/dev/starlte_charger.c optional scion_generic_arm64 bsd/dev/hakios.exynos_hsi2c.c optional scion_generic_arm64 bsd/dev/hakios.exynos_camera.c optional scion_generic_arm64 bsd/dev/hakios.ak737x.c optional scion_generic_arm64 diff --git a/bsd/dev/hakios.max77705_charge.h b/bsd/dev/hakios.max77705_charge.h new file mode 100644 index 000000000..3c9a7e67b --- /dev/null +++ b/bsd/dev/hakios.max77705_charge.h @@ -0,0 +1,488 @@ +/* SPDX-License-Identifier: MIT-0 */ +/* + * The Galaxy S9's charging rules: what the MAX77705's charger may be told, for each kind of charger and each battery + * temperature. Plain C, no kernel: the iOS 27 fork's charger guard (bsd/dev/starlte_muic.c, sweetchg= and sweetafc=) asks + * these functions, and tools/max77705_charge_test.c checks them on a computer (tools/max77705-charge-test.sh). + * docs/ios27/CHARGING.md has the facts and where each number comes from. + * + * Every number is Samsung's own for this phone (exynos9810-starlte_eur_open_26.dts of its kernel: cable-info's current + * groups, the battery node's temperature bands and timers; drivers/battery_v2/max77705_charger.c for the register + * encodings; drivers/muic/max77705-muic*.c for the charger types and the AFC answer). Nothing here goes above them: + * - the input limit and the charge current of each charger type, at most Samsung's for that type; + * - charging stopped at 41.0 C and above or 5.0 C and below (Samsung's "swelling" block; stricter than its 50/0 C + * health limits, and without its reduced-float recharging there), back at 39.0 C and below and 10.0 C and above; + * 700 mA at most at 15.0 C and below (back above it at 20.0 C); + * - a charging session's time limited (Samsung's software timers: its hardware one is switched off by its driver); + * - 9 V (Samsung Adaptive Fast Charging) only on a charger the MUIC calls a dedicated charger (DCP), with the battery + * between 15.0 C and 39.0 C, the charger chip's own thermistor under 44.0 C, the battery not full, the chip + * reporting no fault, and only after the charger answered the 9 V request with VBUS read in the 7.5-10.5 V band. + * On any doubt: 5 V and the standard limits, or less. + * The float voltage (CNFG_04) is never written: it is only read, and charging is stopped if it reads above 4350 mV. + * Nothing of the chip's non-volatile memory is touched by anything that uses this file. + */ +#ifndef HAKIOS_MAX77705_CHARGE_H +#define HAKIOS_MAX77705_CHARGE_H + +#include +#include + +/* ---- the chip's registers (charger at 0x69, MUIC at 0x25) ------------------------------------------------------- */ + +#define CHG_REG_INT_OK 0xB2 /* bit 6 CHGIN_OK */ +#define CHG_REG_DTLS_00 0xB3 /* [6:5] CHGIN_DTLS: 3 = VBUS valid, 2 = over-voltage */ +#define CHG_REG_DTLS_01 0xB4 /* [3:0] CHG_DTLS, [6:4] BAT_DTLS */ +#define CHG_REG_DTLS_02 0xB5 /* [3:0] BYP_DTLS */ +#define CHG_REG_CNFG_00 0xB7 /* [3:0] mode (bit 0 CHG, bit 2 BUCK), bit 4 WDTEN */ +#define CHG_REG_CNFG_01 0xB8 /* [2:0] FCHGTIME, [5:4] CHG_RSTRT (read only here) */ +#define CHG_REG_CNFG_02 0xB9 /* [5:0] the charge current, 50 mA a step; [7:6] OTG_ILIM (kept) */ +#define CHG_REG_CNFG_04 0xBB /* [5:0] the float voltage (read only here) */ +#define CHG_REG_CNFG_06 0xBD /* [1:0] WDTCLR, [3:2] CHGPROT (11: unlocked) */ +#define CHG_REG_CNFG_09 0xC0 /* [6:0] the input limit, 25 mA a step; bit 7 CHG_EN (kept) */ + +#define CHG_CNFG00_CHG 0x01u +#define CHG_CNFG00_BUCK 0x04u +#define CHG_CNFG00_WDTEN 0x10u +#define CHG_CNFG02_CC_MASK 0x3Fu +#define CHG_CNFG09_LIM_MASK 0x7Fu +#define CHG_CNFG06_WDTCLR_MASK 0x03u +#define CHG_CNFG06_WDTCLR 0x01u +#define CHG_CNFG06_CHGPROT_MASK 0x0Cu + +#define MUIC_REG_USBC_STATUS1 0x06 /* [7:4] VBADC: VBUS in bands (below) */ +#define MUIC_REG_BC_STATUS 0x08 /* bit 7 VBUSDet, [5:3] PrChgTyp, bit 2 DCDTmo, [1:0] ChgTyp */ +#define MUIC_OP_CONTROL1_W 0x06 /* the switch: COM_OPEN 0x00, COM_USB 0x09 */ +#define MUIC_OP_AFC_RESULT 0x21 /* COMMAND_AFC_RESULT_READ: the AFC request with its byte; the answer at 0x51 */ +#define AFC_TX_9V 0x46 /* Samsung's byte for 9 V (max77705_muic_afc_hv_set) */ +#define AFC_TX_5V 0x08 /* ... and for 5 V */ + +/* VBADC (USBC_STATUS1 [7:4], and the AFC answer's second byte): 2 = 4.5-5.5 V, 5 = 7.5-8.5, 6 = 8.5-9.5, 7 = 9.5-10.5 */ +#define VBADC_5V_MAX 2u +#define VBADC_9V_MIN 5u +#define VBADC_9V_MAX 7u + +/* ---- the encodings (max77705_charger.c's set_/get_ functions) ---------------------------------------------------- */ + +/* CNFG_09: (code + 1) x 25 mA, 100 mA at codes 0-3, 3200 mA at 0x7F */ +static inline uint32_t +chg_input_ma_of(uint8_t code) +{ + code &= CHG_CNFG09_LIM_MASK; + return code <= 3 ? 100u : code >= 0x7F ? 3200u : (uint32_t)(code + 1u) * 25u; +} + +/* the code for at most ma (rounded down; never above ma, never under 100 mA's code) */ +static inline uint8_t +chg_input_code(uint32_t ma) +{ + if (ma < 100u) { + return 0; + } + if (ma > 3200u) { + ma = 3200u; + } + return (uint8_t)(ma / 25u - 1u); +} + +/* CNFG_02: code x 50 mA, 100 mA at codes 0-2 */ +static inline uint32_t +chg_charge_ma_of(uint8_t code) +{ + code &= CHG_CNFG02_CC_MASK; + return code <= 2 ? 100u : (uint32_t)code * 50u; +} + +static inline uint8_t +chg_charge_code(uint32_t ma) +{ + if (ma < 150u) { + return 0; /* (100 mA: the least the chip does) */ + } + if (ma > 3150u) { + ma = 3150u; + } + return (uint8_t)(ma / 50u); +} + +/* CNFG_04 [5:0]: 4000 + 50 mV a step to 0x04, then 4200 + 10 mV a step */ +static inline uint32_t +chg_float_mv_of(uint8_t code) +{ + code &= 0x3F; + return code <= 4 ? 4000u + code * 50u : 4200u + (code - 4u) * 10u; +} + +/* ---- the charger types and Samsung's limits for each ------------------------------------------------------------- */ + +enum chg_type { + CHG_NONE = 0, /* no VBUS */ + CHG_SDP, /* a computer's plain USB port (BC 1.2 SDP): Samsung's USB */ + CHG_CDP, /* a computer's charging port (BC 1.2 CDP) */ + CHG_DCP, /* a dedicated charger (DCP): Samsung's TA, at 5 V */ + CHG_AFC_9V, /* a DCP that answered the 9 V request: Samsung's 9V_TA */ + CHG_UNKNOWN, /* VBUS with anything else: DCD time-out, an Apple or other special charger, ChgTyp 0 */ + CHG_TYPES +}; + +struct chg_limit { + uint32_t input_ma; + uint32_t charge_ma; + uint32_t session_s; /* the charging time allowed in one session (Samsung's *_charging_total_time) */ + const char *name; +}; + +/* cable-info (current_group_12: USB; _3: CDP; default: TA; _4: 9V_TA; _1: TIMEOUT), the battery node's total times */ +static const struct chg_limit chg_limits[CHG_TYPES] = { + [CHG_NONE] = { 0, 0, 0, "no charger" }, + [CHG_SDP] = { 475, 550, 36000, "a computer's USB port (SDP)" }, + [CHG_CDP] = { 1500, 1500, 18000, "a computer's charging port (CDP)" }, + [CHG_DCP] = { 1800, 2100, 18000, "a wall charger at 5 V (DCP)" }, + [CHG_AFC_9V] = { 1650, 2150, 10800, "a fast charger at 9 V (AFC)" }, + [CHG_UNKNOWN] = { 500, 500, 18000, "an unknown charger" }, +}; + +#define CHG_FLOAT_MAX_MV 4350u /* chg_float_voltage */ +#define CHG_PRE_AFC_INPUT_MA 500u /* pre_afc_input_current: the input limit while the voltage is asked for */ +#define CHG_LOW_TEMP_CHARGE_MA 700u /* swelling_low_temp_current */ + +/* BC_STATUS -> the type. ChgTyp 1 with DCDTmo, or ChgTyp 1/2 with a special PrChgTyp, is not a plain port (Samsung's + * max77705_muic_check_chgtyp: DCD time-out, "unofficial TA"): unknown, the lowest limits. */ +static inline enum chg_type +chg_type_of_bc(uint8_t bc) +{ + unsigned chgtyp = bc & 3u, dcdtmo = (bc >> 2) & 1u, prchgtyp = (bc >> 3) & 7u; + + if (!(bc & 0x80u)) { + return CHG_NONE; + } + if (chgtyp == 1 && dcdtmo) { + return CHG_UNKNOWN; + } + if ((chgtyp == 1 || chgtyp == 2) && prchgtyp >= 1 && prchgtyp <= 5) { + return CHG_UNKNOWN; + } + switch (chgtyp) { + case 1: return CHG_SDP; + case 2: return CHG_CDP; + case 3: return CHG_DCP; + default: return CHG_UNKNOWN; + } +} + +/* ---- the temperature bands (tenths of a degree, as Samsung's device tree) --------------------------------------- */ + +#define T_STOP_HIGH_DC 410 /* swelling_high_temp_block */ +#define T_RESUME_HIGH_DC 390 /* swelling_high_temp_recov */ +#define T_STOP_LOW_DC 50 /* swelling_low_temp_block_2nd */ +#define T_RESUME_LOW_DC 100 /* swelling_low_temp_recov_2nd */ +#define T_REDUCE_DC 150 /* swelling_low_temp_block_1st: 700 mA at most */ +#define T_UNREDUCE_DC 200 /* swelling_low_temp_recov_1st */ +#define T_FAST_MIN_DC 150 /* 9 V only above the reduced band ... */ +#define T_FAST_MAX_DC 390 /* ... and under the swelling recovery point */ +#define T_CHG_FAST_MAX_DC 440 /* the charger's thermistor: chg_high_temp_recovery (46.0 C limits Samsung's 9 V) */ +#define T_ALARM_DC 450 /* the brief's own: above 45 C every change is given up */ +#define T_PLAUSIBLE_MIN_DC (-300) +#define T_PLAUSIBLE_MAX_DC 900 + +/* charging recharged after a full charge (recharge_condition_vcell, _soc) */ +#define RECHARGE_MV 4280u +#define RECHARGE_SOC 98u + +/* ---- the decision ------------------------------------------------------------------------------------------------ */ + +/* what the guard read this time */ +struct chg_in { + bool read_ok; /* every register below read */ + uint8_t bc; /* MUIC BC_STATUS */ + uint8_t vbadc; /* MUIC USBC_STATUS1 [7:4] */ + uint8_t dtls00, dtls01; /* charger DETAILS_00, _01 */ + uint8_t cnfg00, cnfg02, cnfg04, cnfg09; + bool temp_ok; /* the battery's thermistor read */ + int32_t temp_dc; /* the battery, tenths of a degree */ + bool chg_temp_ok; /* the charger's thermistor read */ + int32_t chg_temp_dc; + uint32_t soc; /* percent */ + uint32_t vcell_mv; + uint32_t now_s; /* seconds, any monotonic origin */ + bool afc_wanted; /* sweetafc=1 */ +}; + +/* what the guard keeps from one time to the next */ +struct chg_state { + enum chg_type type; /* the type in force: CHG_AFC_9V only after a good answer */ + bool stopped_hot, stopped_cold, reduced; /* the bands' hysteresis */ + bool full; /* the charger said done; charging again at the recharge condition */ + bool expired; /* the session's time ran out: nothing until the cable goes */ + bool afc_failed; /* the 9 V request went wrong once: not again until the cable goes */ + bool latched_off; /* a fault (a read-back that differed, the float above 4350 mV, an implausible + * temperature, 45 C): charging off, nothing written but that, until the cable goes */ + uint32_t session_start_s, charging_s, last_s; + uint32_t dcp_since_s; /* when the DCP was first seen (9 V asked 1 s after: Samsung waits 500 ms) */ + bool dcp_seen; +}; + +enum chg_why { + WHY_OK = 0, /* charging allowed at the type's limits */ + WHY_NO_VBUS, + WHY_READ_FAILED, + WHY_NO_TEMP, + WHY_HOT, + WHY_COLD, + WHY_FULL, + WHY_EXPIRED, + WHY_FAULT, + WHY_ALARM, + WHY_FLOAT_HIGH, +}; + +/* what to do now */ +struct chg_out { + bool enable; /* CNFG_00 bit 0 */ + uint32_t input_ma; /* CNFG_09: what it is to be set to (0: leave it) */ + uint32_t charge_ma; /* CNFG_02: ditto */ + bool ask_9v; /* send the 9 V request now */ + bool ask_5v; /* send the 5 V request now (back from 9 V) */ + bool rearm; /* the charger's watchdog expired (CHG_DTLS 0xB) with charging wanted: kick it, and charging + * off and on again, as Samsung's max77705_get_charging_health does */ + enum chg_why why; +}; + +static inline const char * +chg_why_name(enum chg_why why) +{ + static const char *const names[] = { "charging allowed", "no VBUS", "a read failed", "no battery temperature", + "too hot", "too cold", "full", "the session's time ran out", "a fault", + "45 C or more", "the float voltage reads above 4350 mV" }; + + return (unsigned)why < sizeof(names) / sizeof(names[0]) ? names[why] : "?"; +} + +static inline bool +chg_temp_plausible(int32_t dc) +{ + return dc >= T_PLAUSIBLE_MIN_DC && dc <= T_PLAUSIBLE_MAX_DC; +} + +/* CHG_DTLS: 0-2 charging (pre-qualification, fast CC, fast CV), 3 top-off, 4 done, 6 the fast-charge timer's fault, 8 off + * (no valid input, or charging off), 0xA off at the junction's thermal shutdown, 0xB off because the charger's watchdog + * expired (Samsung's driver counts 8, 0xA and 0xB as discharging, and re-arms the charger on 8 and 0xB) */ +#define CHG_DTLS_DONE 0x4u +#define CHG_DTLS_WDT_EXPIRED 0xBu + +/* the chip says something is wrong: VBUS over-voltage, the battery not OK, the timer's fault, thermal shutdown */ +static inline bool +chg_chip_fault(const struct chg_in *in) +{ + unsigned chgin = (in->dtls00 >> 5) & 3u, bat = (in->dtls01 >> 4) & 7u, chg = in->dtls01 & 0xFu; + + if (chgin == 2) { + return true; /* CHGIN > OVLO */ + } + if (bat == 0 || bat == 2 || bat == 5) { + return true; /* no battery, battery dead, battery over-voltage */ + } + return chg == 0x6 || chg == 0xA; +} + +/* the 9 V conditions, apart from the type */ +static inline bool +chg_fast_band(const struct chg_in *in) +{ + return in->temp_ok && in->chg_temp_ok && in->temp_dc > T_FAST_MIN_DC && in->temp_dc <= T_FAST_MAX_DC && + in->chg_temp_dc < T_CHG_FAST_MAX_DC && in->soc < RECHARGE_SOC; +} + +/* a new cable (or none): everything of the last one forgotten */ +static inline void +chg_state_reset(struct chg_state *s, uint32_t now_s) +{ + *s = (struct chg_state){ .type = CHG_NONE, .session_start_s = now_s, .last_s = now_s }; +} + +/* + * The guard's one step: from what was read and what it remembers, what the charger is to be told. Every limit given is at + * most Samsung's for the type in force; charging is off unless every condition holds. + */ +static inline struct chg_out +chg_step(struct chg_state *s, const struct chg_in *in) +{ + struct chg_out o = { .enable = false, .input_ma = 0, .charge_ma = 0, .why = WHY_OK }; + enum chg_type seen; + const struct chg_limit *lim; + uint32_t dt; + + if (!in->read_ok) { + /* nothing known: off is asked, nothing else (the caller writes only CNFG_00 when it could read it) */ + o.why = WHY_READ_FAILED; + return o; + } + seen = chg_type_of_bc(in->bc); + if (seen == CHG_NONE) { + chg_state_reset(s, in->now_s); + o.why = WHY_NO_VBUS; + return o; + } + /* the type in force: a 9 V session stays one while the MUIC still says DCP; anything else starts again */ + if (s->type == CHG_NONE || (s->type != seen && !(s->type == CHG_AFC_9V && seen == CHG_DCP))) { + bool was_9v = s->type == CHG_AFC_9V; + + chg_state_reset(s, in->now_s); + s->type = seen; + if (was_9v) { + s->afc_failed = true; /* (the MUIC changed its mind under 9 V: no new request on this cable) */ + } + } + dt = in->now_s >= s->last_s ? in->now_s - s->last_s : 0; + s->last_s = in->now_s; + + /* the faults: off and latched until the cable goes */ + if (s->latched_off) { + o.why = WHY_FAULT; + goto drop_9v; + } + if (chg_float_mv_of(in->cnfg04) > CHG_FLOAT_MAX_MV) { + s->latched_off = true; + o.why = WHY_FLOAT_HIGH; + goto drop_9v; + } + if (!in->temp_ok || !chg_temp_plausible(in->temp_dc)) { + o.why = WHY_NO_TEMP; + goto drop_9v; + } + if (in->temp_dc >= T_ALARM_DC) { + s->latched_off = true; + o.why = WHY_ALARM; + goto drop_9v; + } + if (chg_chip_fault(in)) { + s->latched_off = true; + o.why = WHY_FAULT; + goto drop_9v; + } + + /* the bands, with Samsung's hysteresis */ + if (in->temp_dc >= T_STOP_HIGH_DC) { + s->stopped_hot = true; + } else if (in->temp_dc <= T_RESUME_HIGH_DC) { + s->stopped_hot = false; + } + if (in->temp_dc <= T_STOP_LOW_DC) { + s->stopped_cold = true; + } else if (in->temp_dc >= T_RESUME_LOW_DC) { + s->stopped_cold = false; + } + if (in->temp_dc <= T_REDUCE_DC) { + s->reduced = true; + } else if (in->temp_dc >= T_UNREDUCE_DC) { + s->reduced = false; + } + + /* full, and charging again at Samsung's recharge condition */ + if ((in->dtls01 & 0xFu) == CHG_DTLS_DONE) { + s->full = true; + } else if (s->full && (in->vcell_mv < RECHARGE_MV || in->soc < RECHARGE_SOC)) { + s->full = false; + s->session_start_s = in->now_s; + s->charging_s = 0; + } + + /* the session's time: counted while charging is allowed and the chip charges */ + if ((in->cnfg00 & CHG_CNFG00_CHG) && (in->dtls01 & 0xFu) <= 0x3) { + s->charging_s += dt; + } + lim = &chg_limits[s->type]; + if (s->charging_s >= lim->session_s) { + s->expired = true; + } + + if (s->stopped_hot) { + o.why = WHY_HOT; + goto drop_9v; + } + if (s->stopped_cold) { + o.why = WHY_COLD; + goto drop_9v; + } + if (s->expired) { + o.why = WHY_EXPIRED; + goto drop_9v; + } + + /* 9 V: kept only inside its band; asked for once a DCP has been seen for a second, inside it */ + if (s->type == CHG_AFC_9V && (!chg_fast_band(in) || in->vbadc < VBADC_9V_MIN || in->vbadc > VBADC_9V_MAX || + s->reduced || s->full)) { + s->type = CHG_DCP; + s->afc_failed = true; + o.ask_5v = true; + } + if (s->type == CHG_DCP && !s->dcp_seen) { + s->dcp_seen = true; + s->dcp_since_s = in->now_s; + } + if (s->type == CHG_DCP && in->afc_wanted && !s->afc_failed && !s->full && !s->reduced && chg_fast_band(in) && + in->vbadc <= VBADC_5V_MAX && in->now_s - s->dcp_since_s >= 1) { + o.ask_9v = true; + } + + lim = &chg_limits[s->type]; + o.enable = !s->full; + o.why = s->full ? WHY_FULL : WHY_OK; + o.rearm = o.enable && (in->dtls01 & 0xFu) == CHG_DTLS_WDT_EXPIRED; + o.input_ma = lim->input_ma; + o.charge_ma = lim->charge_ma; + if (s->reduced && o.charge_ma > CHG_LOW_TEMP_CHARGE_MA) { + o.charge_ma = CHG_LOW_TEMP_CHARGE_MA; + } + /* VBUS above 5.5 V without a 9 V session in force (a request on its way, or a charger that went up by itself): + * the input held at the pre-AFC limit, which is under every type's */ + if (s->type != CHG_AFC_9V && in->vbadc > VBADC_5V_MAX) { + o.input_ma = CHG_PRE_AFC_INPUT_MA; + } + if (o.ask_9v) { + o.input_ma = CHG_PRE_AFC_INPUT_MA; + } + return o; + +drop_9v: + /* charging off; a 9 V session asked back to 5 V, the input held at the pre-AFC limit meanwhile */ + if (s->type == CHG_AFC_9V || in->vbadc > VBADC_5V_MAX) { + if (s->type == CHG_AFC_9V) { + s->type = CHG_DCP; + o.ask_5v = true; + } + s->afc_failed = true; + o.input_ma = CHG_PRE_AFC_INPUT_MA; + } + return o; +} + +/* The answer to the 9 V request (OPCODE_READ: the opcode, the result, VBADC): true only for result 0 with VBUS in the + * 7.5-10.5 V bands, read again from USBC_STATUS1 as well (Samsung: AFC_CHARGER_9V for those bands). */ +static inline bool +chg_afc_answer_9v(const uint8_t answer[3], uint8_t vbadc_now) +{ + return answer[0] == MUIC_OP_AFC_RESULT && answer[1] == 0 && answer[2] >= VBADC_9V_MIN && answer[2] <= VBADC_9V_MAX && + vbadc_now >= VBADC_9V_MIN && vbadc_now <= VBADC_9V_MAX; +} + +/* After the answer: the state's type moves to 9 V only with a good one; a bad one is remembered for the cable. */ +static inline void +chg_afc_result(struct chg_state *s, bool good) +{ + if (s->type != CHG_DCP) { + return; + } + if (good) { + s->type = CHG_AFC_9V; + } else { + s->afc_failed = true; + } +} + +/* A written register read back: the bits written must read as written (the guard's watchdog). */ +static inline bool +chg_readback_ok(uint8_t wrote, uint8_t read, uint8_t mask) +{ + return (wrote & mask) == (read & mask); +} + +#endif /* HAKIOS_MAX77705_CHARGE_H */ diff --git a/bsd/dev/starlte_charger.c b/bsd/dev/starlte_charger.c new file mode 100644 index 000000000..ea8c23105 --- /dev/null +++ b/bsd/dev/starlte_charger.c @@ -0,0 +1,555 @@ +/* SPDX-License-Identifier: MIT-0 */ +/* + * iOS 27 on STARLTE (24 Nov 2026): the Galaxy S9's charger, watched and guarded. The MAX77705's charger (0x69) and MUIC + * (0x25) on the bus of starlte_muic.c, and the battery's and the charger's thermistors on CMGP's ADC. The rules are + * scion-kernel's drivers/power/max77705/hakios.max77705_charge.h (copied here as bsd/dev/hakios.max77705_charge.h, + * tested on a computer by tools/max77705-charge-test.sh); docs/ios27/CHARGING.md has the facts. + * + * sweetchg=0 nothing here (SweetBattery as before: the gauge alone, 25 C) + * sweetchg=1 READ ONLY: every second the charger, the MUIC, the gauge and both thermistors read; the charger type, the + * battery's temperature and the charger's own state handed to SweetBattery for iOS; what the guard WOULD do + * logged ("would"); the charger's registers 0xB2-0xC5 in the log at start and every 5 minutes. + * sweetchg=2 the guard: as 1, and the charger told (volatile registers only, each write read back): + * CNFG_06 WDTCLR (the watchdog kicked every 10 s while it is on, as Samsung's driver does; without it the + * charger stopped about 70 s after S-Boot on phone 2, DETAILS_01 0x3b), + * CNFG_06 CHGPROT to 11 if it reads locked (Samsung's max77705_charger_unlock), + * CNFG_00 bit 0 (charging on or off: the temperature bands, the session's time, full and recharge), + * CNFG_09 [6:0] (the input limit) and CNFG_02 [5:0] (the charge current): Samsung's for the type, or less. + * A read-back that differs: charging off and nothing more written until the cable goes. + * sweetafc=1 (with sweetchg=2; OFF by default) the fast-charge path: on a DCP, inside the band, the MUIC's switch opened + * (Samsung's COM_OPEN for a TA) and Samsung's 9 V request sent (opcode 0x21 with 0x46); 9 V taken only when the + * answer is result 0 with VBUS in 7.5-10.5 V and USBC_STATUS1 says the same; then 1650/2150 mA. Checked every + * second: out of the band, VBUS out of 7.5-10.5 V, a fault or a differing read-back -> 500 mA, the 5 V request, + * the standard limits once VBUS reads 5 V; not asked again on that cable. + * sweetchg_drain=MIN (a test, with sweetchg=2; off by default) for the first MIN minutes (30 at most) the input held at + * 100 mA and charging off, so the phone runs from its battery and charging can then be seen from below + * full on a computer's port; given up at 50 % or 40 C. Lower limits only. + * Never written: the float voltage, the timers, CNFG_01/03/04/05/07/08/10-12, the gauge, the PMIC, anything non-volatile. + * The console: sysctl kern.hakios.chg_* (below). + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hakios.max77705_charge.h" + +#define CHARGER 0x69 +#define MUIC 0x25 +#define GAUGE 0x36 +#define OPCODE_WRITE 0x21 +#define OPCODE_WRITE_END 0x41 +#define OPCODE_READ 0x51 +#define COM_OPEN 0x00 + +/* bsd/dev/starlte_muic.c: the bus, brought up and locked (NULL if it could not be), and let go */ +extern struct hakios_hsi2c *starlte_muic_bus_take(void); +extern void starlte_muic_bus_give(void); + +/* ---- the thermistors: CMGP's ADC (0x14230000), channel 4 the battery's, 3 the charger's (Samsung's adc-temp and + * adc-chg-temp); five conversions, the highest and lowest dropped; the phone's table (battery,temp_table_adc/_data, + * the same for both). The clock gates and the reset as Scion's hakios.max77705.c does it. */ +#define ADC_PA 0x14230000UL +#define ADC_CON1 0x00 +#define ADC_CON2 0x04 +#define ADC_DAT 0x08 +#define ADC_INT_EN 0x10 +#define ADC_INT_ST 0x14 +#define ADC_CH_BATT 4 +#define ADC_CH_CHG 3 +static const uint16_t temp_adc[] = { 275, 327, 385, 451, 535, 626, 737, 864, 1013, 1210, 1361, 1554, 1769, 2007, 2239, + 2476, 2702, 2924, 3116, 3294, 3446, 3564, 3676 }; +static const int16_t temp_dc[] = { 900, 850, 800, 750, 700, 650, 600, 550, 500, 450, 400, 350, 300, 250, 200, 150, 100, + 50, 0, -50, -100, -150, -200 }; +static vm_offset_t adc; + +static void +adc_up(struct hakios_hsi2c *bus) +{ + static const uint32_t gates[] = { 0x2018, 0x201C }, qch[] = { 0x3008, 0x300C }; + + if (adc != 0 || bus->cmu == 0) { + return; + } + adc = ml_io_map(ADC_PA, 0x1000); + if (adc == 0) { + return; + } + for (unsigned i = 0; i < 2; i++) { + *(volatile uint32_t *)(bus->cmu + gates[i]) |= (1u << 20) | (1u << 21); + *(volatile uint32_t *)(bus->cmu + qch[i]) |= 3; + } + *(volatile uint32_t *)(adc + ADC_CON1) = 1u << 2; + *(volatile uint32_t *)(adc + ADC_CON1) = 1u << 1; + *(volatile uint32_t *)(adc + ADC_CON2) = 6u << 4; + *(volatile uint32_t *)(adc + ADC_INT_EN) = 1; +} + +static int +adc_convert(unsigned ch) +{ + volatile uint32_t *r = (volatile uint32_t *)adc; + + r[ADC_CON2 / 4] = (r[ADC_CON2 / 4] & ~0xfu) | ch; + r[ADC_CON1 / 4] |= 1; + for (int i = 0; i < 10000; i++) { + if (r[ADC_INT_ST / 4] & 1) { + int v = (int)(r[ADC_DAT / 4] & 0xfff); + + r[ADC_INT_ST / 4] = 1; + return v; + } + delay(1); + } + return -1; +} + +/* tenths of a degree; false if the ADC did not answer */ +static bool +thermistor(unsigned ch, int32_t *dc, int *raw_out) +{ + int s[5], lo = 0, hi = 0, sum = 0, raw; + const unsigned n = sizeof(temp_adc) / sizeof(temp_adc[0]); + + if (adc == 0) { + return false; + } + for (int i = 0; i < 5; i++) { + if ((s[i] = adc_convert(ch)) < 0) { + return false; + } + lo = s[i] < s[lo] ? i : lo; + hi = s[i] > s[hi] ? i : hi; + } + for (int i = 0; i < 5; i++) { + sum += (i == lo || i == hi) ? 0 : s[i]; + } + raw = sum / (lo == hi ? 4 : 3); + *raw_out = raw; + if (raw <= temp_adc[0]) { + *dc = temp_dc[0]; + } else if (raw >= temp_adc[n - 1]) { + *dc = temp_dc[n - 1]; + } else { + for (unsigned i = 1; i < n; i++) { + if (raw <= temp_adc[i]) { + *dc = temp_dc[i - 1] + (temp_dc[i] - temp_dc[i - 1]) * (raw - temp_adc[i - 1]) / + (temp_adc[i] - temp_adc[i - 1]); + break; + } + } + } + return true; +} + +/* ---- what the console and SweetBattery see -------------------------------------------------------------------------- */ + +static int chg_mode; /* sweetchg= */ +static int chg_afc; /* sweetafc= */ +static int chg_drain_min; /* sweetchg_drain= (a test): minutes on the battery first */ +static uint32_t drain_until_s; +static int k_type = -1, k_why = -1, k_temp_dc = -2730, k_chg_temp_dc = -2730, k_input_ma = -1, k_charge_ma = -1; +static int k_enable = -1, k_vbadc = -1, k_afc_asked, k_afc_good, k_afc_drops, k_writes, k_readback_bad, k_kicks; +static int k_bc = -1, k_dtls01 = -1, k_float_mv = -1, k_soc = -1, k_vcell = -1, k_current_ma; + +SYSCTL_DECL(_kern_hakios); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_mode, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &chg_mode, 0, "sweetchg=: 0 off, 1 read only, 2 the guard"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_afc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &chg_afc, 0, "sweetafc=: the 9 V path allowed"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_type, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_type, 0, + "the charger: 0 none, 1 SDP, 2 CDP, 3 DCP at 5 V, 4 AFC at 9 V, 5 unknown"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_why, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_why, 0, + "0 charging allowed, 1 no VBUS, 2 read failed, 3 no temperature, 4 hot, 5 cold, 6 full, 7 time, 8 fault, 9 45 C, 10 float"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_temp_dc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_temp_dc, 0, "the battery, tenths of a degree"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_chgtemp_dc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_chg_temp_dc, 0, "the charger's thermistor"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_input_ma, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_input_ma, 0, "CNFG_09 as read, mA"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_charge_ma, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_charge_ma, 0, "CNFG_02 as read, mA"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_enable, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_enable, 0, "CNFG_00 bit 0 as read"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_vbadc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_vbadc, 0, "VBUS band: 2 = 4.5-5.5 V, 5-7 = 7.5-10.5 V"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_afc_asked, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_afc_asked, 0, "9 V requests sent"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_afc_good, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_afc_good, 0, "9 V sessions begun"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_afc_drops, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_afc_drops, 0, "9 V given up (5 V asked)"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_writes, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_writes, 0, "charger register writes"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_readback_bad, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_readback_bad, 0, "read-backs that differed"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_kicks, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_kicks, 0, "watchdog kicks"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_bc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_bc, 0, "MUIC BC_STATUS"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_dtls01, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_dtls01, 0, "charger DETAILS_01"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_float_mv, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_float_mv, 0, "CNFG_04 as read, mV"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_soc, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_soc, 0, "the gauge's RepSOC, percent"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_current_ma, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_current_ma, 0, + "the gauge's Current, mA, above 0 while charging"); +SYSCTL_INT(_kern_hakios, OID_AUTO, chg_vcell_mv, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_KERN, &k_vcell, 0, "the gauge's VCELL, mV"); + +/* for SweetBattery.cpp (sweetchg >= 1) */ +struct starlte_chg_report { + bool valid; + int type; /* enum chg_type */ + bool external, charging, full; + int32_t temp_centi; /* the battery, hundredths of a degree (iOS's unit) */ + uint32_t input_ma, vbus_mv; + const char *type_name; +}; +int starlte_chg_report(struct starlte_chg_report *r); + +static struct starlte_chg_report report; + +int +starlte_chg_report(struct starlte_chg_report *r) +{ + if (chg_mode < 1 || !report.valid) { + return -1; + } + *r = report; + return 0; +} + +/* ---- the chip -------------------------------------------------------------------------------------------------------- */ + +static uint32_t +rd8(struct hakios_hsi2c *bus, uint8_t addr, uint8_t reg, uint8_t *v) +{ + return hakios_hsi2c_read_reg(bus, addr, reg, v, 1); +} + +static uint32_t +rd16(struct hakios_hsi2c *bus, uint8_t addr, uint8_t reg, uint16_t *v) +{ + uint8_t b[2] = { 0, 0 }; + uint32_t e = hakios_hsi2c_read_reg(bus, addr, reg, b, 2); + + *v = (uint16_t)(b[0] | (b[1] << 8)); + return e; +} + +/* a charger register: only the bits of mask changed, the rest as read; read back. true when it reads as written. */ +static bool +chg_write_bits(struct hakios_hsi2c *bus, uint8_t reg, uint8_t mask, uint8_t value, const char *what) +{ + uint8_t now = 0, back = 0, b[2]; + bool ok; + + if (rd8(bus, CHARGER, reg, &now) != 0) { + printf("STARLTE CHG: %s: %#x not read: not written\n", what, reg); + return false; + } + b[0] = reg; + b[1] = (uint8_t)((now & ~mask) | (value & mask)); + if (b[1] == now) { + return true; + } + ok = hakios_hsi2c_message(bus, CHARGER, false, b, 2, true) == 0 && rd8(bus, CHARGER, reg, &back) == 0 && + chg_readback_ok(b[1], back, mask); + k_writes++; + printf("STARLTE CHG: %s: %#x %#x -> %#x, read back %#x%s\n", what, reg, now, b[1], back, ok ? "" : " DIFFERS"); + if (!ok) { + k_readback_bad++; + } + return ok; +} + +/* a MUIC opcode with its data, through OPCODE_WRITE and OPCODE_WRITE_END (Samsung's max77705_usbc_opcode_write) */ +static uint32_t +muic_opcode(struct hakios_hsi2c *bus, uint8_t op, uint8_t data) +{ + uint8_t w1[3] = { OPCODE_WRITE, op, data }, w2[2] = { OPCODE_WRITE_END, 0 }; + uint32_t e = hakios_hsi2c_message(bus, MUIC, false, w1, 3, true); + + return e ? e : hakios_hsi2c_message(bus, MUIC, false, w2, 2, true); +} + +static void +regs_say(struct hakios_hsi2c *bus, const char *when) +{ + char line[3 * 20 + 1]; + size_t at = 0; + uint8_t v = 0, bc = 0, s1 = 0, s2 = 0; + + for (uint8_t reg = 0xB2; reg <= 0xC5; reg++) { + at += (size_t)snprintf(line + at, sizeof(line) - at, rd8(bus, CHARGER, reg, &v) == 0 ? " %02x" : " --", v); + } + (void)rd8(bus, MUIC, MUIC_REG_BC_STATUS, &bc); + (void)rd8(bus, MUIC, MUIC_REG_USBC_STATUS1, &s1); + (void)rd8(bus, MUIC, 0x07, &s2); + printf("STARLTE CHG: registers %s: charger 0xb2-0xc5:%s; MUIC BC_STATUS %#x USBC_STATUS1 %#x SYSMSG %#x\n", when, line, + bc, s1, s2); +} + +/* ---- the guard --------------------------------------------------------------------------------------------------------- */ + +static thread_call_t chg_call; +static struct chg_state st; + +static unsigned ticks; +static enum chg_why last_why = (enum chg_why)-1; +static enum chg_type last_type = (enum chg_type)-1; +static bool last_enable; + +static uint32_t +now_s(void) +{ + uint64_t ns; + + absolutetime_to_nanoseconds(mach_absolute_time(), &ns); + return (uint32_t)(ns / NSEC_PER_SEC); +} + +/* 9 V asked for: the switch opened, the request sent, the answer awaited (3 s); true for a good one */ +static bool +afc_ask(struct hakios_hsi2c *bus, uint8_t tx) +{ + uint8_t a[3] = { 0, 0, 0 }, s1 = 0; + uint32_t e; + + (void)muic_opcode(bus, MUIC_OP_CONTROL1_W, COM_OPEN); + delay(50000); + e = muic_opcode(bus, MUIC_OP_AFC_RESULT, tx); + printf("STARLTE CHG: AFC: %s request sent (%#x): %s\n", tx == AFC_TX_9V ? "9 V" : "5 V", tx, e ? "FAILED" : "ok"); + if (e != 0) { + return false; + } + for (int i = 0; i < 60; i++) { + /* (the bus let go meanwhile is not needed: the guard is its only user once the switch's two minutes are over, + * and the switch's tick takes the same lock) */ + delay(50000); + if (hakios_hsi2c_read_reg(bus, MUIC, OPCODE_READ, a, 3) == 0 && a[0] == MUIC_OP_AFC_RESULT) { + break; + } + } + (void)rd8(bus, MUIC, MUIC_REG_USBC_STATUS1, &s1); + printf("STARLTE CHG: AFC: answer opcode %#x result %u VBADC %u; USBC_STATUS1 VBADC %u\n", a[0], a[1], a[2], s1 >> 4); + return tx == AFC_TX_9V && chg_afc_answer_9v(a, (uint8_t)(s1 >> 4)); +} + +static void +chg_tick(__unused thread_call_param_t p0, __unused thread_call_param_t p1) +{ + struct hakios_hsi2c *bus = starlte_muic_bus_take(); + struct chg_in in = { .read_ok = false }; + struct chg_out o; + uint8_t cnfg06 = 0, dtls02 = 0, s1 = 0; + uint16_t soc = 0, vcell = 0, cur = 0; + int raw_b = -1, raw_c = -1; + bool guard = chg_mode >= 2; + uint64_t deadline; + + if (bus == NULL) { + goto again; + } + adc_up(bus); + in.read_ok = rd8(bus, MUIC, MUIC_REG_BC_STATUS, &in.bc) == 0 && rd8(bus, MUIC, MUIC_REG_USBC_STATUS1, &s1) == 0 && + rd8(bus, CHARGER, CHG_REG_DTLS_00, &in.dtls00) == 0 && rd8(bus, CHARGER, CHG_REG_DTLS_01, &in.dtls01) == 0 && + rd8(bus, CHARGER, CHG_REG_DTLS_02, &dtls02) == 0 && rd8(bus, CHARGER, CHG_REG_CNFG_00, &in.cnfg00) == 0 && + rd8(bus, CHARGER, CHG_REG_CNFG_02, &in.cnfg02) == 0 && rd8(bus, CHARGER, CHG_REG_CNFG_04, &in.cnfg04) == 0 && + rd8(bus, CHARGER, CHG_REG_CNFG_06, &cnfg06) == 0 && rd8(bus, CHARGER, CHG_REG_CNFG_09, &in.cnfg09) == 0 && + rd16(bus, GAUGE, 0x06, &soc) == 0 && rd16(bus, GAUGE, 0x09, &vcell) == 0; + in.vbadc = (uint8_t)(s1 >> 4); + in.temp_ok = thermistor(ADC_CH_BATT, &in.temp_dc, &raw_b); + in.chg_temp_ok = thermistor(ADC_CH_CHG, &in.chg_temp_dc, &raw_c); + (void)rd16(bus, GAUGE, 0x0A, &cur); /* Current: 312.5 uA a count, above 0 while charging (for the log) */ + k_current_ma = (int)((int64_t)(int16_t)cur * 3125 / 10000); + in.soc = soc / 256u; + in.vcell_mv = (uint32_t)((uint64_t)vcell * 78125u / 1000000u); + in.now_s = now_s(); + in.afc_wanted = chg_afc != 0 && guard; + if (ticks == 0) { + regs_say(bus, "at start"); + printf("STARLTE CHG: sweetchg=%d sweetafc=%d: %s; battery %d.%d C (ADC %d), charger %d.%d C (ADC %d)\n", chg_mode, + chg_afc, guard ? "the guard (volatile charger registers, read back)" : "read only", in.temp_dc / 10, + (in.temp_dc < 0 ? -in.temp_dc : in.temp_dc) % 10, raw_b, in.chg_temp_dc / 10, + (in.chg_temp_dc < 0 ? -in.chg_temp_dc : in.chg_temp_dc) % 10, raw_c); + } else if (ticks % 300 == 0) { + regs_say(bus, "every 5 minutes"); + } + + o = chg_step(&st, &in); + if (guard && drain_until_s != 0) { + if (in.now_s < drain_until_s && in.read_ok && in.soc > 50 && in.temp_ok && in.temp_dc < 400 && + o.why != WHY_FAULT && !st.latched_off) { + o.enable = false; + o.input_ma = 100; + o.ask_9v = false; + if (ticks % 60 == 0) { + printf("STARLTE CHG: drain (sweetchg_drain=%d): %u s left, %u %% %u mV\n", chg_drain_min, + drain_until_s - in.now_s, in.soc, in.vcell_mv); + } + } else { + printf("STARLTE CHG: drain over (%s): %u %% %u mV, battery %d.%d C; the guard's limits from now\n", + in.now_s >= drain_until_s ? "its time" : "50 %, 40 C or a fault", in.soc, in.vcell_mv, in.temp_dc / 10, + (in.temp_dc < 0 ? -in.temp_dc : in.temp_dc) % 10); + drain_until_s = 0; + } + } + + if (guard && in.read_ok) { + bool ok = true; + + /* the watchdog kicked while it is on (every 10 s, as Samsung's monitor does; it expired about 70 s after S-Boot + * on phone 2 without it), and at once when it has expired; CHGPROT unlocked if it reads locked */ + if ((in.cnfg00 & CHG_CNFG00_WDTEN) && (ticks % 10 == 0 || o.rearm)) { + uint8_t b[2] = { CHG_REG_CNFG_06, (uint8_t)((cnfg06 & ~CHG_CNFG06_WDTCLR_MASK) | CHG_CNFG06_WDTCLR) }; + + if (hakios_hsi2c_message(bus, CHARGER, false, b, 2, true) == 0) { + if (k_kicks++ == 0) { + printf("STARLTE CHG: watchdog: CNFG_00 %#x (WDTEN on): CNFG_06 %#x written %#x (kicked)\n", in.cnfg00, + cnfg06, b[1]); + } + } + } + if ((cnfg06 & CHG_CNFG06_CHGPROT_MASK) != CHG_CNFG06_CHGPROT_MASK) { + ok = chg_write_bits(bus, CHG_REG_CNFG_06, CHG_CNFG06_CHGPROT_MASK, CHG_CNFG06_CHGPROT_MASK, "CHGPROT unlocked"); + } + /* lower first, then on: the input before a request, 5 V asked after the input is down */ + if (ok && o.input_ma != 0) { + uint8_t code = chg_input_code(o.input_ma); + + if ((in.cnfg09 & CHG_CNFG09_LIM_MASK) != code) { + ok = chg_write_bits(bus, CHG_REG_CNFG_09, CHG_CNFG09_LIM_MASK, code, "input limit"); + } + } + if (ok && o.charge_ma != 0) { + uint8_t code = chg_charge_code(o.charge_ma); + + if ((in.cnfg02 & CHG_CNFG02_CC_MASK) != code) { + ok = chg_write_bits(bus, CHG_REG_CNFG_02, CHG_CNFG02_CC_MASK, code, "charge current"); + } + } + if (o.ask_5v) { + k_afc_drops++; + (void)afc_ask(bus, AFC_TX_5V); + } + if (!ok) { + /* a read-back that differs: off, latched until the cable goes */ + st.latched_off = true; + o.enable = false; + o.ask_9v = false; + if (st.type == CHG_AFC_9V) { + st.type = CHG_DCP; + st.afc_failed = true; + k_afc_drops++; + (void)afc_ask(bus, AFC_TX_5V); + } + } + /* the watchdog expired with charging wanted: off and on again (Samsung's max77705_get_charging_health) */ + if (o.rearm && o.enable && !st.latched_off && (in.cnfg00 & CHG_CNFG00_BUCK) && (in.cnfg00 & CHG_CNFG00_CHG)) { + static unsigned rearms; + + if (rearms++ < 5) { + printf("STARLTE CHG: the charger's watchdog had expired (DETAILS_01 %#x): kicked, charging off and on\n", + in.dtls01); + } + if (!chg_write_bits(bus, CHG_REG_CNFG_00, CHG_CNFG00_CHG, 0, "re-arm: charging off")) { + st.latched_off = true; + } + in.cnfg00 &= (uint8_t)~CHG_CNFG00_CHG; + } + /* charging on or off (CNFG_00 bit 0 only; the buck, which powers the phone from the cable, never touched) */ + if (((in.cnfg00 & CHG_CNFG00_CHG) != 0) != o.enable && (in.cnfg00 & CHG_CNFG00_BUCK) && !(o.enable && st.latched_off)) { + if (!chg_write_bits(bus, CHG_REG_CNFG_00, CHG_CNFG00_CHG, o.enable ? CHG_CNFG00_CHG : 0, + o.enable ? "charging on" : "charging off")) { + st.latched_off = true; + } + } + if (ok && o.ask_9v && !st.latched_off) { + bool good; + + k_afc_asked++; + good = afc_ask(bus, AFC_TX_9V); + chg_afc_result(&st, good); + if (good) { + k_afc_good++; + printf("STARLTE CHG: AFC: 9 V; the input and charge current go to %u/%u mA at the next second\n", + chg_limits[CHG_AFC_9V].input_ma, chg_limits[CHG_AFC_9V].charge_ma); + } else { + printf("STARLTE CHG: AFC: no 9 V; 5 V limits, not asked again on this cable\n"); + (void)afc_ask(bus, AFC_TX_5V); + } + } + } + + /* what was read, for the console and for iOS */ + k_type = st.type; + k_why = o.why; + k_temp_dc = in.temp_ok ? in.temp_dc : -2730; + k_chg_temp_dc = in.chg_temp_ok ? in.chg_temp_dc : -2730; + k_input_ma = (int)chg_input_ma_of(in.cnfg09); + k_charge_ma = (int)chg_charge_ma_of(in.cnfg02); + k_enable = in.cnfg00 & CHG_CNFG00_CHG; + k_vbadc = in.vbadc; + k_bc = in.bc; + k_dtls01 = in.dtls01; + k_float_mv = (int)chg_float_mv_of(in.cnfg04); + k_soc = (int)in.soc; + k_vcell = (int)in.vcell_mv; + if (in.read_ok) { + unsigned d = in.dtls01 & 0xFu; + + report.type = st.type; + report.type_name = chg_limits[st.type].name; + report.external = chg_type_of_bc(in.bc) != CHG_NONE; + report.charging = report.external && (in.cnfg00 & CHG_CNFG00_CHG) && d <= 0x2; + report.full = report.external && (d == 0x3 || d == 0x4 || st.full); + report.temp_centi = in.temp_ok ? in.temp_dc * 10 : 2500; + report.input_ma = chg_input_ma_of(in.cnfg09); + report.vbus_mv = in.vbadc >= VBADC_9V_MIN ? 9000u : 5000u; + report.valid = in.temp_ok; + } + + if (o.why != last_why || st.type != last_type || o.enable != last_enable || ticks % 60 == 0) { + printf("STARLTE CHG: %s%s; %s; charging %s; input %u mA charge %u mA (as read %u/%u, CNFG_00 %#x); " + "battery %d.%d C, charger %d.%d C; %u %% %u mV %d mA; DTLS %#x/%#x/%#x; BC %#x VBADC %u; float %u mV%s\n", + guard ? "" : "would: ", drain_until_s != 0 ? "the drain test" : chg_why_name(o.why), chg_limits[st.type].name, + o.enable ? "on" : "off", + o.input_ma, o.charge_ma, chg_input_ma_of(in.cnfg09), chg_charge_ma_of(in.cnfg02), in.cnfg00, + in.temp_dc / 10, (in.temp_dc < 0 ? -in.temp_dc : in.temp_dc) % 10, in.chg_temp_dc / 10, + (in.chg_temp_dc < 0 ? -in.chg_temp_dc : in.chg_temp_dc) % 10, in.soc, in.vcell_mv, k_current_ma, in.dtls00, in.dtls01, + dtls02, in.bc, in.vbadc, chg_float_mv_of(in.cnfg04), in.read_ok ? "" : " (A READ FAILED)"); + last_why = o.why; + last_type = st.type; + last_enable = o.enable; + } + starlte_muic_bus_give(); +again: + ticks++; + clock_interval_to_deadline(1, NSEC_PER_SEC, &deadline); + thread_call_enter_delayed(chg_call, deadline); +} + +/* the 9 V path on a DCP wants the switch open: starlte_muic.c's tick leaves it so */ +bool starlte_chg_afc_owns_switch(uint8_t bc); +bool +starlte_chg_afc_owns_switch(uint8_t bc) +{ + return chg_mode >= 2 && chg_afc != 0 && chg_type_of_bc(bc) == CHG_DCP; +} + +__startup_func +static void +starlte_chg_init(void) +{ + uint64_t deadline; + + (void)PE_parse_boot_argn("sweetchg", &chg_mode, sizeof(chg_mode)); + (void)PE_parse_boot_argn("sweetafc", &chg_afc, sizeof(chg_afc)); + if (chg_mode <= 0) { + return; + } + if (chg_mode > 2) { + chg_mode = 2; + } + (void)PE_parse_boot_argn("sweetchg_drain", &chg_drain_min, sizeof(chg_drain_min)); + if (chg_mode == 2 && chg_drain_min > 0) { + drain_until_s = now_s() + 60u * (uint32_t)(chg_drain_min > 30 ? 30 : chg_drain_min); + } + chg_state_reset(&st, 0); + + chg_call = thread_call_allocate_with_priority(chg_tick, NULL, THREAD_CALL_PRIORITY_KERNEL); + /* the first look 5 s after this (the switch's code brings the bus up first) */ + clock_interval_to_deadline(5, NSEC_PER_SEC, &deadline); + thread_call_enter_delayed(chg_call, deadline); +} +STARTUP(EARLY_BOOT, STARTUP_RANK_LAST, starlte_chg_init); diff --git a/bsd/dev/starlte_muic.c b/bsd/dev/starlte_muic.c index 738e49d8a..94777008b 100644 --- a/bsd/dev/starlte_muic.c +++ b/bsd/dev/starlte_muic.c @@ -38,6 +38,7 @@ static struct hakios_hsi2c bus = { .pins_pa = 0, .ipclk_mhz = 400, .bus_hz = 400000, }; static thread_call_t muic_call; +extern bool starlte_chg_afc_owns_switch(uint8_t bc); /* bsd/dev/starlte_charger.c */ static int muic_ticks; static bool muic_up; @@ -93,6 +94,27 @@ muic_bus_up(void) return true; } +/* bsd/dev/starlte_charger.c (sweetchg=): the same bus, brought up and held; NULL if it could not be (then nothing to give) */ +struct hakios_hsi2c *starlte_muic_bus_take(void); +void starlte_muic_bus_give(void); + +struct hakios_hsi2c * +starlte_muic_bus_take(void) +{ + lck_mtx_lock(&muic_bus_lock); + if (!muic_bus_up()) { + lck_mtx_unlock(&muic_bus_lock); + return NULL; + } + return &bus; +} + +void +starlte_muic_bus_give(void) +{ + lck_mtx_unlock(&muic_bus_lock); +} + static void muic_tick(__unused thread_call_param_t p0, __unused thread_call_param_t p1) { @@ -103,6 +125,12 @@ muic_tick(__unused thread_call_param_t p0, __unused thread_call_param_t p1) } uint8_t bc = 0; (void)hakios_hsi2c_read_reg(&bus, MUIC, MUIC_BC_STATUS, &bc, 1); + if (starlte_chg_afc_owns_switch(bc)) { + /* a wall charger with the fast-charge path on (starlte_charger.c, sweetafc=1): the switch is left open for it, + * as Samsung leaves it for a TA; there is no host on the other end for the console */ + lck_mtx_unlock(&muic_bus_lock); + goto next; + } int c = ctrl1_read(); if (c != COM_USB) { uint32_t e = ctrl1_write(COM_USB); @@ -114,6 +142,7 @@ muic_tick(__unused thread_call_param_t p0, __unused thread_call_param_t p1) printf("STARLTE MUIC: CONTROL1 %#x (USB to the AP); BC_STATUS %#x\n", c, bc); } lck_mtx_unlock(&muic_bus_lock); +next: if (++muic_ticks < 60) { uint64_t deadline; clock_interval_to_deadline(2, NSEC_PER_SEC, &deadline); diff --git a/iokit/Kernel/arm/SweetBattery.cpp b/iokit/Kernel/arm/SweetBattery.cpp index 1b64e4981..9e20a1b70 100644 --- a/iokit/Kernel/arm/SweetBattery.cpp +++ b/iokit/Kernel/arm/SweetBattery.cpp @@ -20,6 +20,16 @@ extern "C" int herolte_fg_read(unsigned *percent, unsigned *mv, int *ma, #if defined(ARM64_BOARD_CONFIG_STARLTE) /* bsd/dev/starlte_muic.c: the MAX77705's fuel gauge, read-only (boot-arg sweetfg=1) */ extern "C" int starlte_fg_read(unsigned *percent, unsigned *mv, int *ma, unsigned *rem_mah, unsigned *full_mah, bool *vbus); +/* bsd/dev/starlte_charger.c (sweetchg=1 or 2): the charger's own state, its type and the battery's thermistor */ +struct starlte_chg_report { + bool valid; + int type; /* 0 none, 1 SDP, 2 CDP, 3 DCP, 4 AFC 9 V, 5 unknown */ + bool external, charging, full; + int32_t temp_centi; + uint32_t input_ma, vbus_mv; + const char *type_name; +}; +extern "C" int starlte_chg_report(struct starlte_chg_report *r); #define BATTERY_DESIGN_MAH 3000u /* SM-G960F EB-BG960ABE */ #else #define BATTERY_DESIGN_MAH 3000u /* SM-G930F EB-BG930ABE */ @@ -43,11 +53,15 @@ class SweetBattery : public IOPMPowerSource { IOTimerEventSource *fTimer; bool fTimerAdded, fRunning, fReal; int fLastMode; + int32_t fTempCenti; /* the battery's thermistor (sweetchg=), else 2500, not measured */ + bool fTempMeasured; + int fLastType; void putNumber(const char *key, UInt32 value); void putBool(const char *key, bool value); void publish(unsigned percent, unsigned mv, int ma, bool external, bool capable, bool charging, bool full, bool measured, bool currentValid); void poll(void); + void publishAdapter(bool external, int type, uint32_t input_ma, uint32_t vbus_mv); static void timerFired(OSObject *owner, IOTimerEventSource *sender); static IOReturn stopPolling(OSObject *owner, void *, void *, void *, void *); static bool readWord(unsigned address, uint16_t *value); @@ -87,6 +101,9 @@ SweetBattery::init(OSDictionary *dictionary) } } fLastMode = -1; + fTempCenti = 2500; + fTempMeasured = false; + fLastType = -2; return true; } @@ -137,12 +154,12 @@ SweetBattery::publish(unsigned percent, unsigned mv, int ma, bool external, putNumber("AppleRawMaxCapacity", BATTERY_DESIGN_MAH); putNumber("DesignCapacity", BATTERY_DESIGN_MAH); putNumber("InstantAmperage", (UInt32)ma); - /* iOS battery convention: centidegrees C; fixed 25 C, NOT measured. */ - putNumber("Temperature", 2500); + /* iOS battery convention: centidegrees C; the battery's thermistor with sweetchg=, else a fixed 25 C, NOT measured. */ + putNumber("Temperature", (UInt32)fTempCenti); putBool("SweetBatteryHardwareSampleValid", measured); putBool("SweetBatteryCurrentValid", currentValid); putBool("SweetBatterySOCEstimated", measured); - putBool("SweetBatteryTemperatureEstimated", true); + putBool("SweetBatteryTemperatureEstimated", !fTempMeasured); putBool("SweetBatteryFallback", !measured); putNumber("SweetBatteryPercent", percent); @@ -224,6 +241,51 @@ SweetBattery::estimatePercent(unsigned mv) } #endif +/* + * The adapter's details as powerd reads them (kIOPMPSAdapterDetailsKey): the family from the charger type (the codes of + * IOPSKeysPrivate.h's kIOPSFamilyCode*, as Scion's hakios.battery.cpp uses them), the input limit, VBUS 5 or 9 V. + */ +void +SweetBattery::publishAdapter(bool external, int type, uint32_t input_ma, uint32_t vbus_mv) +{ + OSDictionary *adapter = OSDictionary::withCapacity(5); + UInt32 family; + + if (!adapter) { + return; + } + switch (external ? type : 0) { + case 0: family = 0; break; /* kIOPSFamilyCodeDisconnected */ + case 1: family = 0xe0004000; break; /* SDP: kIOPSFamilyCodeUSBHost */ + case 2: family = 0xe0004005; break; /* CDP: kIOPSFamilyCodeUSBChargingPortDownstream */ + case 3: case 4: family = 0xe0004004; break; /* DCP, AFC: kIOPSFamilyCodeUSBChargingPortDedicated */ + default: family = 0xe0004007; break; /* kIOPSFamilyCodeUSBUnknown */ + } + const UInt32 values[] = { family, external ? (vbus_mv * input_ma + 500000u) / 1000000u : 0, external ? input_ma : 0, + external ? vbus_mv : 0 }; + const char *keys[] = { kIOPMPSAdapterDetailsFamilyKey, kIOPMPSAdapterDetailsWattsKey, + kIOPMPSAdapterDetailsAmperageKey, kIOPMPSAdapterDetailsVoltage }; + for (unsigned i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { + if (!external && i > 0) { + break; + } + OSNumber *number = OSNumber::withNumber(values[i], 32); + if (number) { + adapter->setObject(keys[i], number); + number->release(); + } + } + if (external) { + adapter->setObject("IsWireless", kOSBooleanFalse); + } + const OSSymbol *symbol = OSSymbol::withCString(kIOPMPSAdapterDetailsKey); + if (symbol) { + setPSProperty(symbol, adapter); + symbol->release(); + } + adapter->release(); +} + #if defined(ARM64_BOARD_CONFIG_HEROLTE) void SweetBattery::poll(void) @@ -244,6 +306,22 @@ SweetBattery::poll(void) /* No charger driver: the gauge's charge current marks a cable. */ bool charging = ma > 20; #if defined(ARM64_BOARD_CONFIG_STARLTE) + /* sweetchg=1 or 2: the charger says whether it charges (its CHG_DTLS with charging on), whether it is done, what the + * cable is, and the battery's temperature (starlte_charger.c) */ + struct starlte_chg_report chg; + if (starlte_chg_report(&chg) == 0) { + fTempCenti = chg.temp_centi; + fTempMeasured = true; + publishAdapter(chg.external, chg.type, chg.input_ma, chg.vbus_mv); + if (chg.type != fLastType) { + IOLog("SWEET BATTERY: %s; %u%% %umV %dmA, battery %d.%02d C\n", chg.type_name, percent, mv, ma, + chg.temp_centi / 100, (chg.temp_centi < 0 ? -chg.temp_centi : chg.temp_centi) % 100); + fLastType = chg.type; + } + publish(percent, mv, ma, chg.external, chg.external, chg.charging, chg.external && (chg.full || percent >= 100), + true, true); + return; + } /* On the S9 the switch's VBUS bit says whether a cable is in, charging or not (full, or the charger's watchdog). */ if (vbus && !charging) { static unsigned vlogged; @@ -312,7 +390,7 @@ SweetBattery::timerFired(OSObject *owner, IOTimerEventSource *sender) SweetBattery *self = OSDynamicCast(SweetBattery, owner); if (self && self->fRunning) { self->poll(); - sender->setTimeoutMS(30000); + sender->setTimeoutMS(self->fTempMeasured ? 10000 : 30000); } } diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c index c18e93b65..2fa2ca21d 100644 --- a/osfmk/arm/arm_init.c +++ b/osfmk/arm/arm_init.c @@ -205,6 +205,9 @@ static const char starlte_default_bootargs[] = * pdp_ip0 (cp_if=1: no data without cp_apn=, which only a run gives). */ "tmu=3 shub=6 shub_hid=3 sweethalt=1 sweetfg=1 rtc_pmic=1 persona_lax=1 wifi_pcie=6 brcmfmac=8 " + /* On by default since 24 November 2026: the charger guard (bsd/dev/starlte_charger.c): the charger's watchdog fed, + * Samsung's temperature bands and limits for the charger type. Its fast-charge path (sweetafc=1) stays off. */ + "sweetchg=2 " "abox=8 max98512=3 cs47l93=6 abox_mic=1 abox_rmem=1 bt=7 " "cp=7 cp_nv=2 cp_delay=40 cp_rfs=1 cp_if=1 " /*