#!/bin/sh
# CPU performance profiles for the MU300 (Ubuntu and OpenWrt, POSIX sh). A profile is a governor and a per-cluster
# scaling_min/max; it moves only inside the hardware frequency table (cpuinfo_min_freq..cpuinfo_max_freq) and never
# touches voltage or the kernel thermal trips - thermal-guard keeps throttling in every profile.
#   mu300-cpu status [--json]        per-policy governor, cur/min/max, hw max, saved profile, throttling (--json: the
#                                    kernel's thermal zones too, read only)
#   mu300-cpu profile [NAME]         apply NAME and save it; no NAME shows the saved one
#   mu300-cpu apply                  apply the saved profile (the boot service)
#   mu300-cpu voltage ...            the CPU voltage offset, EXPERIMENTAL (it can damage the device for good):
#                                    see "the CPU voltage offset" below and docs/FINDINGS.md 133
#   mu300-cpu core N on|off          CPU N online or offline now, and saved (CPU0 always stays online); apply takes
#                                    the saved ones offline again at boot (FINDINGS 200, after kanoqwq's cpu-cores)
#   mu300-cpu lowlatency [on|off]    CPU0 without its cpuidle states, as ZTE's U30 Air firmware ("lowlatency"): far
#                                    shorter Wi-Fi delays in kanoqwq's measurements, more power drawn; off by default,
#                                    saved, applied at boot (FINDINGS 200). No argument: the saved setting
#   mu300-cpu services [little|all]  where the system's services run (OpenWrt: procd's /sys/fs/cgroup/services, and
#                                    every process they start): on the little cluster or on every CPU (the default);
#                                    saved, applied now and at boot (FINDINGS 235). No argument: the saved setting
#   mu300-cpu services apply         apply the saved setting (the boot service)
# Profiles: saving (cores capped at ~60 % of the maximum, schedutil - cooler, less power), balanced (schedutil over
# the full range, the stock behaviour), performance (every cluster pinned at its hardware maximum).
# Why it never fights the rest: mu300-power's idle "eco" drops the big core and caps policy4 to 1.5 GHz and brings
# it back by looking; it wins while the device is asleep and restores to whatever this profile set. thermal-guard
# caps a hot policy a step lower and lifts it on cool-down, but not above the ceiling this profile wrote
# (/run/mu300/cpu-ceiling), so "saving" stays capped. Configuration: /etc/mu300/cpu.conf (KEY=VALUE), kept across
# updates with the rest of etc/mu300; a missing key is its default.
set -u
export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin"
R=${MU300_SYSROOT:-}
RUNROOT=${MU300_RUN:-/run}
CPUFREQ=$R/sys/devices/system/cpu/cpufreq
CONF=${MU300_CPU_CONF:-/etc/mu300/cpu.conf}
CEIL=$RUNROOT/mu300/cpu-ceiling          # one "policyN=HZ" line per cluster: the max a profile set, for thermal-guard
PROFILES="saving balanced performance"
SAVING_PERCENT=${MU300_CPU_SAVING_PERCENT:-60}

say() { echo "mu300-cpu: $*" >&2; logger -t mu300-cpu -- "$*" 2>/dev/null || true; }

# --- configuration (as mu300-power reads power.conf)
default() { case $1 in PROFILE) echo balanced ;; CORES_OFF) echo ;; LOWLATENCY) echo 0 ;; SERVICES) echo all ;; *) return 1 ;; esac; }
valid() {
    case $1 in
        PROFILE) case $2 in saving|balanced|performance) return 0 ;; esac ;;
        # the CPUs kept offline: 1..63, comma-separated, never CPU0
        CORES_OFF) printf '%s\n' "$2" | grep -Eqx '([1-9]|[1-5][0-9]|6[0-3])(,([1-9]|[1-5][0-9]|6[0-3])){0,62}' && return 0 ;;
        LOWLATENCY) case $2 in 0|1) return 0 ;; esac ;;
        SERVICES) case $2 in little|all) return 0 ;; esac ;;
    esac
    return 1
}
conf_raw() { sed -n "s/^$1=\(.*\)\$/\1/p" "$CONF" 2>/dev/null | tail -n1; }
conf_get() {
    _v=$(conf_raw "$1")
    if [ -n "$_v" ] && valid "$1" "$_v"; then echo "$_v"; return 0; fi
    default "$1"
}
conf_del() {  # conf_del KEY: back to its default
    [ -f "$CONF" ] || return 0
    { grep -v "^$1=" "$CONF" || true; } > "$CONF.tmp" && mv "$CONF.tmp" "$CONF"   # (grep: 1 when nothing is left)
}
conf_set() {
    default "$1" >/dev/null || { echo "mu300-cpu: no such key: $1" >&2; return 2; }
    valid "$1" "$2" || { echo "mu300-cpu: bad value for $1: $2" >&2; return 2; }
    mkdir -p "${CONF%/*}" 2>/dev/null
    # (true, not ":": a failed redirection of a special builtin ends a POSIX shell, and the caller must get the failure)
    [ -f "$CONF" ] || true > "$CONF" || return 1
    if grep -q "^$1=" "$CONF"; then
        sed "s/^$1=.*\$/$1=$2/" "$CONF" > "$CONF.tmp" && mv "$CONF.tmp" "$CONF"
    else
        [ -z "$(tail -c1 "$CONF")" ] || echo >> "$CONF"
        echo "$1=$2" >> "$CONF"
    fi
}

num() { case ${1#-} in ''|*[!0-9]*) echo 0 ;; *) echo "${1#-}" ;; esac; }
rd() { cat "$1" 2>/dev/null; }
policies() { for p in "$CPUFREQ"/policy*; do [ -d "$p" ] && echo "$p"; done; }

# a governor the policy has, else its first available one (schedutil is the mainline default; the 5.4 vendor kernel
# may not have it; powersave is only a fallback we never choose on purpose)
pick_gov() {  # pick_gov POLICY WANT
    if grep -qw "$2" "$1/scaling_available_governors" 2>/dev/null; then echo "$2"; else cut -d' ' -f1 "$1/scaling_available_governors" 2>/dev/null; fi
}

# ceil_write / ceil_get: the per-policy ceiling a profile set, so thermal-guard does not lift a capped policy past it
ceil_write() {  # ceil_write POLICYNAME HZ
    mkdir -p "${CEIL%/*}" 2>/dev/null
    { grep -v "^$1=" "$CEIL" 2>/dev/null; echo "$1=$2"; } > "$CEIL.tmp" 2>/dev/null && mv "$CEIL.tmp" "$CEIL" 2>/dev/null
}

apply() {  # apply PROFILE
    _p=$1
    case " $PROFILES " in *" $_p "*) ;; *) echo "mu300-cpu: unknown profile '$_p' ($PROFILES)" >&2; return 1 ;; esac
    _any=
    for pol in $(policies); do
        _any=1
        _name=${pol##*/}
        read -r _hwmin < "$pol/cpuinfo_min_freq" 2>/dev/null || _hwmin=
        read -r _hwmax < "$pol/cpuinfo_max_freq" 2>/dev/null || _hwmax=
        [ -n "$_hwmin" ] && [ -n "$_hwmax" ] || { say "$_name: no hardware frequency range, left alone"; continue; }
        case $_p in
            saving)
                # highest table step at or below SAVING_PERCENT % of the maximum (never below the hardware minimum)
                _cap=$(tr ' ' '\n' < "$pol/scaling_available_frequencies" 2>/dev/null | \
                    awk -v lim=$(( _hwmax * SAVING_PERCENT / 100 )) -v lo="$_hwmin" '$1 != "" && $1 <= lim && $1 >= lo && $1 > c {c = $1} END {print c}')
                [ -n "$_cap" ] && [ "$_cap" -gt 0 ] 2>/dev/null || _cap=$_hwmax
                _gov=$(pick_gov "$pol" schedutil); _min=$_hwmin; _max=$_cap ;;
            balanced)    _gov=$(pick_gov "$pol" schedutil);  _min=$_hwmin; _max=$_hwmax ;;
            performance) _gov=$(pick_gov "$pol" performance); _min=$_hwmin; _max=$_hwmax ;;
        esac
        # order matters: never set min above the current max, nor max below the current min
        echo "$_min" > "$pol/scaling_min_freq" 2>/dev/null || true
        echo "$_max" > "$pol/scaling_max_freq" 2>/dev/null || true
        [ -n "$_gov" ] && echo "$_gov" > "$pol/scaling_governor" 2>/dev/null || true
        ceil_write "$_name" "$_max"
    done
    [ -n "$_any" ] || { say "no cpufreq policies (this kernel has no CPU scaling): nothing to apply"; return 0; }
    return 0
}

# --- the cores (CPU hotplug; mainline has CONFIG_HOTPLUG_CPU, FINDINGS 200). CPU0 is never taken offline: the
# kernel's timekeeping and the vendor drivers' interrupts start there. mu300-power's idle takes CPU7 offline and
# brings it back, but not one kept offline here (it reads CORES_OFF too).
CPUDIR=$R/sys/devices/system/cpu
cpus() { for c in "$CPUDIR"/cpu[0-9]*; do [ -d "$c" ] && echo "${c##*/cpu}"; done | sort -n; }
in_list() { case ",$2," in *",$1,"*) return 0 ;; esac; return 1; }
core_set() {  # core_set N on|off: now and saved
    case $1 in ''|*[!0-9]*) echo "mu300-cpu: no such CPU: $1" >&2; return 2 ;; esac
    case $2 in on|off) ;; *) echo "usage: mu300-cpu core N on|off" >&2; return 2 ;; esac
    [ "$1" != 0 ] || { echo "mu300-cpu: CPU0 always stays online" >&2; return 2; }
    [ -e "$CPUDIR/cpu$1/online" ] || { echo "mu300-cpu: CPU$1 cannot be switched (no such CPU, or no CPU hotplug in this kernel)" >&2; return 1; }
    _off=$(conf_get CORES_OFF); _new=
    for _c in $(printf '%s' "$_off" | tr ',' ' '); do [ "$_c" = "$1" ] || _new="${_new:+$_new,}$_c"; done
    if [ "$2" = off ]; then
        # the last online core but CPU0 may go too; CPU0 always keeps the system running
        echo 0 > "$CPUDIR/cpu$1/online" 2>/dev/null || [ "$(rd "$CPUDIR/cpu$1/online")" = 0 ] ||
            { echo "mu300-cpu: the kernel refused to take CPU$1 offline" >&2; return 1; }
        _new="${_new:+$_new,}$1"
    else
        echo 1 > "$CPUDIR/cpu$1/online" 2>/dev/null || [ "$(rd "$CPUDIR/cpu$1/online")" = 1 ] ||
            { echo "mu300-cpu: the kernel refused to bring CPU$1 online" >&2; return 1; }
    fi
    if [ -n "$_new" ]; then conf_set CORES_OFF "$_new"; else conf_del CORES_OFF; fi
    say "CPU$1 $2 (saved)"
    # the profile's limits for a cluster that came back: its policy was gone while all its cores were off
    [ "$2" = off ] || apply "$(conf_get PROFILE)" >/dev/null 2>&1 || true
}
cores_apply() {  # the saved offline cores, at boot; one that cannot go offline is left as it is
    for _c in $(conf_get CORES_OFF | tr ',' ' '); do
        [ "$_c" != 0 ] && [ -e "$CPUDIR/cpu$_c/online" ] || continue
        [ "$(rd "$CPUDIR/cpu$_c/online")" = 0 ] && continue
        echo 0 > "$CPUDIR/cpu$_c/online" 2>/dev/null && say "CPU$_c offline (saved)" || say "CPU$_c could not be taken offline"
    done
}
cores_json() {
    printf '['
    _sep=
    for _c in $(cpus); do
        _on=1
        [ "$(rd "$CPUDIR/cpu$_c/online")" = 0 ] && _on=0
        _hp=0
        [ "$_c" != 0 ] && [ -e "$CPUDIR/cpu$_c/online" ] && _hp=1
        printf '%s{"cpu":%s,"online":%s,"switchable":%s}' "$_sep" "$_c" "$_on" "$_hp"
        _sep=,
    done
    printf ']'
}

# --- CPU0's idle states (ZTE's U30 Air: init.md.rc "zte add for feimao lowlatency" disables all three after boot).
# kanoqwq measured the Wi-Fi receive delay on a U30 Air: with CPU0 allowed into its deeper states, events waited 34 ms
# on average (100 ms at worst); with them off, 0.6 ms (2 ms); the stock firmware the other way round. The power cost
# was not measured, so it stays off unless the owner switches it on.
lowlat_nodes() { for n in "$CPUDIR"/cpu0/cpuidle/state*/disable; do [ -f "$n" ] && echo "$n"; done; }
# All or nothing (kanoqwq's cpu-idle, cc0ecce7): when a state does not take the value (written, then read back), every
# state gets back what it had, so a failed switch never leaves CPU0 half in one setting and half in the other; and a
# setting that cannot be saved is undone the same way (what runs is what the next boot applies).
lowlat_snapshot() { _lw_was=; for n in $(lowlat_nodes); do _lw_was="$_lw_was $n=$(rd "$n")"; done; }
lowlat_restore() {  # back to the last lowlat_snapshot
    for _nv in $_lw_was; do
        [ "$(rd "${_nv%=*}")" = "${_nv##*=}" ] || { echo "${_nv##*=}" > "${_nv%=*}"; } 2>/dev/null
    done
    return 0
}
lowlat_write() {  # lowlat_write 0|1: 1 disables every state of CPU0
    lowlat_snapshot
    for n in $(lowlat_nodes); do
        [ "$(rd "$n")" = "$1" ] && continue
        { echo "$1" > "$n"; } 2>/dev/null && [ "$(rd "$n")" = "$1" ] && continue
        lowlat_restore
        return 1
    done
    return 0
}
lowlat_supported() { [ -n "$(lowlat_nodes)" ]; }
lowlat_active() {  # every state of CPU0 disabled
    _any=
    for n in $(lowlat_nodes); do _any=1; [ "$(rd "$n")" = 1 ] || return 1; done
    [ -n "$_any" ]
}
lowlat_mixed() {  # some of CPU0's states disabled and some not (by hand, or by something else)
    _on= _off=
    for n in $(lowlat_nodes); do if [ "$(rd "$n")" = 1 ]; then _off=1; else _on=1; fi; done
    [ -n "$_on" ] && [ -n "$_off" ]
}
lowlat_set() {
    case ${1:-} in on) _v=1 ;; off) _v=0 ;; *) echo "usage: mu300-cpu lowlatency [on|off]" >&2; return 2 ;; esac
    lowlat_supported || { echo "mu300-cpu: this kernel has no cpuidle states for CPU0" >&2; return 1; }
    lowlat_write "$_v" || { echo "mu300-cpu: CPU0's idle states could not be written; they are as they were, nothing saved" >&2; return 1; }
    if [ "$_v" = 1 ]; then conf_set LOWLATENCY 1; else conf_del LOWLATENCY; fi ||
        { lowlat_restore; echo "mu300-cpu: the setting could not be saved; CPU0's idle states are as they were" >&2; return 1; }
    say "low latency $1 (CPU0 idle states $([ "$_v" = 1 ] && echo off || echo on)), saved"
}
lowlat_apply() {  # at boot: only an "on" is applied; off leaves the kernel's own settings alone
    [ "$(conf_get LOWLATENCY)" = 1 ] || return 0
    lowlat_supported || return 0
    lowlat_write 1 && say "low latency on (saved): CPU0 idle states off" || say "low latency: CPU0's idle states could not be written"
}

# --- the services' CPUs (FINDINGS 235). The panel, the collectors and the daemons are shell scripts and ucode: short
# bursts of process starts that the scheduler spread over idle big cores (each burst woke an A76 and its cluster, and
# raised its clock), for work a little core does in the same milliseconds. procd puts every service in a cgroup of its
# own under /sys/fs/cgroup/services, so with "little" one cpuset there holds them all, and every process they start, on
# the little cluster; the kernel's own work (network, interrupts) is not touched. "all", the default, leaves them on
# every CPU: a userspace VPN engine (xray, sing-box, OpenVPN) is a procd service too, and on these boards all traffic,
# the router's own included, goes through it. A no-op where there is no procd service tree (Ubuntu) or no cpuset.
CGROUP=$R/sys/fs/cgroup
little_cpus() {  # the CPUs of the lowest capacity, comma-separated (every CPU on a SoC of one kind)
    _lc_min= _lc_list=
    for _c in "$CPUDIR"/cpu[0-9]*; do
        read -r _cap < "$_c/cpu_capacity" 2>/dev/null || continue
        case $_cap in ''|*[!0-9]*) continue ;; esac
        if [ -z "$_lc_min" ] || [ "$_cap" -lt "$_lc_min" ]; then _lc_min=$_cap; _lc_list=${_c##*/cpu}
        elif [ "$_cap" = "$_lc_min" ]; then _lc_list="$_lc_list,${_c##*/cpu}"; fi
    done
    printf '%s\n' "$_lc_list"
}
services_apply() {
    [ -d "$CGROUP/services" ] || return 0
    _sv_cpus=
    [ "$(conf_get SERVICES)" = little ] && _sv_cpus=$(little_cpus)
    if [ -n "$_sv_cpus" ]; then
        grep -qw cpuset "$CGROUP/cgroup.controllers" 2>/dev/null || { say "no cpuset controller: the services stay on every CPU"; return 0; }
        grep -qw cpuset "$CGROUP/cgroup.subtree_control" 2>/dev/null || echo +cpuset > "$CGROUP/cgroup.subtree_control" 2>/dev/null ||
            { say "the cpuset controller could not be enabled: the services stay on every CPU"; return 0; }
        echo "$_sv_cpus" > "$CGROUP/services/cpuset.cpus" 2>/dev/null || { say "services: CPUs $_sv_cpus could not be set"; return 0; }
        say "services on CPUs $_sv_cpus"
    elif [ -f "$CGROUP/services/cpuset.cpus" ] && [ -n "$(rd "$CGROUP/services/cpuset.cpus")" ]; then
        # empty: every CPU the parent has
        echo > "$CGROUP/services/cpuset.cpus" 2>/dev/null && say "services on every CPU"
    fi
    return 0
}
services_set() {
    case ${1:-} in
        apply) services_apply ;;
        little|all) conf_set SERVICES "$1" && services_apply ;;
        *) echo "usage: mu300-cpu services [little|all|apply]" >&2; return 2 ;;
    esac
}

khz() { case $1 in ''|*[!0-9]*) echo null ;; *) echo $(( $1 / 1000 )) ;; esac; }
jstr() { printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"; }

# cooling devices currently capping a cpufreq policy ("cpufreq ..."), for the throttling line
throttling() {
    for c in "$R"/sys/class/thermal/cooling_device*; do
        [ -r "$c/type" ] || continue
        case $(rd "$c/type") in *cpufreq*|*thermal-cpufreq*) [ "$(num "$(rd "$c/cur_state")")" -gt 0 ] && { echo 1; return; } ;; esac
    done
    [ -e "$RUNROOT/mu300/thermal-alarm" ] && echo 1 || echo 0
}

# thermal_json: the kernel's thermal zones for the panel's read-only Thermal section - type, temperature (mC), mode,
# trip points and the cooling devices bound to the zone (cdevK links) with their states. Read only, every kernel: on
# mainline the stock soc-thmzone (mu300_thermal, docs/FINDINGS.md 48) is the one with trips and cooling devices.
thermal_json() {
    printf '['
    _sep=
    for z in "$R"/sys/class/thermal/thermal_zone*; do
        [ -r "$z/type" ] || continue
        printf '%s{"zone":%s,"temp":%s,"mode":%s,"trips":[' "$_sep" "$(jstr "$(rd "$z/type")")" \
            "$(num "$(rd "$z/temp")")" "$(jstr "$(rd "$z/mode")")"
        _s2=; _i=0
        while [ -r "$z/trip_point_${_i}_temp" ]; do
            printf '%s{"type":%s,"temp":%s}' "$_s2" "$(jstr "$(rd "$z/trip_point_${_i}_type")")" "$(num "$(rd "$z/trip_point_${_i}_temp")")"
            _s2=,; _i=$((_i + 1))
        done
        printf '],"cooling":['
        _s2=
        for c in "$z"/cdev[0-9]*; do
            [ -r "$c/type" ] || continue
            printf '%s{"type":%s,"state":%s,"max":%s}' "$_s2" "$(jstr "$(rd "$c/type")")" "$(num "$(rd "$c/cur_state")")" "$(num "$(rd "$c/max_state")")"
            _s2=,
        done
        printf ']}'
        _sep=,
    done
    printf ']'
}

status_json() {
    _saved=$(conf_get PROFILE)
    printf '{"ok":1,"profile":%s,"profiles":["saving","balanced","performance"],"throttling":%s,"thermal":%s,' \
        "$(jstr "$_saved")" "$(throttling)" "$(thermal_json)"
    printf '"cores":%s,"cores_off":%s,"lowlatency":{"saved":%s,"active":%s,"mixed":%s,"supported":%s},"policies":[' \
        "$(cores_json)" "$(jstr "$(conf_get CORES_OFF)")" "$(conf_get LOWLATENCY)" \
        "$(lowlat_active && echo 1 || echo 0)" "$(lowlat_mixed && echo 1 || echo 0)" "$(lowlat_supported && echo 1 || echo 0)"
    _sep=
    for pol in $(policies); do
        _rel=$(rd "$pol/related_cpus")
        _lo=${_rel%% *}; _hi=${_rel##* }
        printf '%s{"name":%s,"cpus":%s,"governor":%s,"cur":%s,"min":%s,"max":%s,"hwmin":%s,"hwmax":%s}' \
            "$_sep" "$(jstr "${pol##*/}")" "$(jstr "$_lo-$_hi")" "$(jstr "$(rd "$pol/scaling_governor")")" \
            "$(khz "$(rd "$pol/scaling_cur_freq")")" "$(khz "$(rd "$pol/scaling_min_freq")")" \
            "$(khz "$(rd "$pol/scaling_max_freq")")" "$(khz "$(rd "$pol/cpuinfo_min_freq")")" "$(khz "$(rd "$pol/cpuinfo_max_freq")")"
        _sep=,
    done
    printf ']}\n'
}

status_human() {
    echo "saved profile: $(conf_get PROFILE)"
    printf '  %-10s %-12s %10s %10s %10s %10s\n' policy governor cur min max hw-max
    for pol in $(policies); do
        _rel=$(rd "$pol/related_cpus"); _lo=${_rel%% *}; _hi=${_rel##* }
        printf '  %-10s %-12s %10s %10s %10s %10s\n' "cpu$_lo-$_hi" "$(rd "$pol/scaling_governor")" \
            "$(khz "$(rd "$pol/scaling_cur_freq")")" "$(khz "$(rd "$pol/scaling_min_freq")")" \
            "$(khz "$(rd "$pol/scaling_max_freq")")" "$(khz "$(rd "$pol/cpuinfo_max_freq")")"
    done
    echo "  (MHz)"
    [ "$(throttling)" = 1 ] && echo "thermal throttling: active" || echo "thermal throttling: none"
    _offl=; for _c in $(cpus); do [ "$(rd "$CPUDIR/cpu$_c/online")" = 0 ] && _offl="$_offl cpu$_c"; done
    echo "offline cores:${_offl:- none} (kept offline: $(conf_get CORES_OFF | sed 's/^$/none/'))"
    if lowlat_supported; then
        echo "low latency: $([ "$(conf_get LOWLATENCY)" = 1 ] && echo on || echo off) (CPU0 idle states $(lowlat_active && echo off || { lowlat_mixed && echo 'partly off' || echo on; }))"
    fi
}

# --- the CPU voltage offset (EXPERIMENTAL: it can damage the device for good; docs/FINDINGS.md 133)
#   mu300-cpu voltage status [--json]   what DVFS runs with, what is asked for, the trial/good/armed marks, the limits,
#                                       the firmware check and each domain's frequency/voltage table
#   mu300-cpu voltage set A,B,C --confirm EXPERIMENTAL
#                                       offsets in uV for domains 0, 1, 2 (CPUs 0-3, 4-6, 7), from the next boot on
#   mu300-cpu voltage off               back to 0,0,0 from the next boot on
#   mu300-cpu voltage keep-good [on|off]  a good value survives a power cut after 10 minutes up (off by default)
#   mu300-cpu voltage stress [MINUTES] [--background]   mu300-toolkit's CPU stress test (10 minutes)
#   mu300-cpu voltage warning           the warning (English, Turkish, Chinese)
#   (services) voltage mark-good: 10 minutes after boot; voltage shutdown: a clean shutdown or reboot
# The firmware applies an offset once per boot, inside DVFS_INIT; the initramfs (boot/init, cpu-voltage) decides at
# every boot whether the value asked for may run and writes it to the kernel. A new value gets one trial boot; it is
# kept ("good") once that boot has been up 10 minutes, and dropped - back to 0,0,0, the request cleared - when a boot
# with an offset ends without a clean shutdown (a crash, a watchdog reset, a power cut) or the trial boot ended before
# its good mark. The kernel refuses anything outside -25..+12.5 mV or not a whole 3.125 mV step whatever this says.
CPUV_SYS=$R/sys/module/sprd_cpufreq_v2_driver/parameters
CPUV_WORD=EXPERIMENTAL
CPUV_GOOD_MIN=10
CPUV_WARN=${MU300_CPUV_WARNING:-/opt/mu300/lib/cpu-voltage-warning.txt}
# the SML (ATF) builds whose DVFS_INIT encoding is known (the same list as boot/init's; a test keeps them equal): the
# F50's, the V50's and the U30 Air's (their payload is the F50's byte for byte, FINDINGS 201)
CPUV_SML_KNOWN=${MU300_CPUV_SML_KNOWN:-ff4782690fd805ff54fe34853ef8ee5c7e51c3259e20077c55373b50a4b259c2 5b3183f17af9b416e71dea61e578c61824e4e1df43737a1179032f4b20466b2b f27ac16f44e6cdc87a8ee00a9b53c499c8dde0c3b92c771388e256e84ef12e70}

cpuv_dir() {  # .mu300 on the Linux disk (the same rule as mu300-next-boot)
    for _d in "${MU300_DISK:-/mnt/mu300-disk}" "$R"; do [ -d "$_d/.mu300" ] && { printf '%s/.mu300' "$_d"; return 0; }; done
    return 1
}
cpuv_is_root() { [ "$(id -u)" = 0 ] || [ -n "${MU300_SYSROOT:-}" ]; }
cpuv_norm() { printf '%s' "$1" | tr -s ' \t' ',' | sed 's/^,//; s/,$//'; }
cpuv_valid() {  # the same check as boot/init's: three whole 3.125 mV steps within -25000..12500 uV, written plainly
    case $1 in *[!0-9,-]*|'') return 1 ;; esac
    _o=$IFS; IFS=,; set -- $1; IFS=$_o
    [ $# = 3 ] || return 1
    for _cv; do   # digits only, no leading zero, 6 at most
        case ${_cv#-} in ''|*[!0-9]*|0?*|???????*) return 1 ;; esac
        [ "$_cv" != -0 ] || return 1
        [ "$_cv" -ge -25000 ] && [ "$_cv" -le 12500 ] && [ $((_cv % 3125)) = 0 ] || return 1
    done
}
cpuv_kernel() { [ -r "$CPUV_SYS/voltage_offset_uv" ] && [ -r "$CPUV_SYS/voltage_state" ]; }
cpuv_limit() {  # cpuv_limit KEY: a value of the kernel's voltage_limits (min max step dcdc_max wait)
    # braces: a failed "<" is reported before a 2>/dev/null after it takes effect (a kernel without the offset)
    { tr ' ' '\n' < "$CPUV_SYS/voltage_limits"; } 2>/dev/null | sed -n "s/^$1=\(-\{0,1\}[0-9]*\)\$/\1/p"
}
cpuv_head() { head -n1 "$1" 2>/dev/null | tr -d '\r'; }
snum() { case ${1#-} in ''|*[!0-9]*) echo 0 ;; *) echo "$1" ;; esac; }   # a signed integer, else 0

# the internal disk's sml_a and sml_b (only its own: a card can carry the same names; lib/storage.sh), checked against
# the known builds; known, unknown or unreadable (not root). Cached for the boot: the partitions do not change under a
# running system.
cpuv_firmware() {
    _c=$RUNROOT/mu300/cpu-voltage-firmware
    [ -s "$_c" ] && { cat "$_c"; return; }
    _r=unknown _n=0
    for _p in $(MU300_SYS=$R/sys; . "${MU300_STORAGE_LIB:-/opt/mu300/lib/storage.sh}" &&
                _d=$(mu300_storage_disk) && mu300_storage_part sml_a "$_d" && mu300_storage_part sml_b "$_d"); do
        _p=$R/dev/$_p
        if ! _h=$(sha256sum < "$_p" 2>/dev/null); then _r=unreadable; break; fi
        case " $CPUV_SML_KNOWN " in *" ${_h%% *} "*) _n=$((_n + 1)) ;; *) _r=unknown; break ;; esac
    done
    [ "$_r" = unknown ] && [ "$_n" = 2 ] && _r=known
    [ "$_r" = unreadable ] || { mkdir -p "${_c%/*}" 2>/dev/null; echo "$_r" > "$_c" 2>/dev/null; }
    echo "$_r"
}

cpuv_arr() {  # "A,B,C" -> [A,B,C]; anything else -> null
    if cpuv_valid "$1"; then printf '[%s]' "$1"; else printf null; fi
}
cpuv_phase() {  # off, pending (the next boot changes it), trial, good, or unsupported
    _app=$1 _req=$2 _good=$3
    cpuv_kernel || { echo unsupported; return; }
    if [ "$_req" != "$_app" ]; then echo pending
    elif [ "$_app" = 0,0,0 ]; then echo off
    elif [ "$_good" = "$_app" ]; then echo good
    else echo trial; fi
}
cpuv_stress_running() {
    _pf=$RUNROOT/mu300/cpu-voltage-stress.pid
    [ -s "$_pf" ] && kill -0 "$(cat "$_pf")" 2>/dev/null
}

voltage_status_json() {
    _d=$(cpuv_dir) || _d=
    _app=$(cpuv_head "$CPUV_SYS/voltage_offset_uv"); cpuv_valid "$_app" || _app=0,0,0
    _req=$(cpuv_head "$_d/cpu-voltage"); cpuv_valid "$_req" || _req=0,0,0
    _good=$(cpuv_head "$_d/cpu-voltage-good"); _trial=$(cpuv_head "$_d/cpu-voltage-trial")
    _rej=$(cpuv_head "$_d/cpu-voltage-rejected")
    _kst=$(cpuv_head "$CPUV_SYS/voltage_state")
    printf '{"ok":1,"kernel":%s,"state":%s,"phase":%s,"applied":%s,"requested":%s,"good":%s,"trial":%s,"armed":%s,"keep_good":%s,' \
        "$(cpuv_kernel && echo 1 || echo 0)" "$(jstr "${_kst:-none}")" "$(jstr "$(cpuv_phase "$_app" "$_req" "$_good")")" \
        "$(cpuv_arr "$_app")" "$(cpuv_arr "$_req")" "$(cpuv_arr "$_good")" "$(cpuv_arr "$_trial")" \
        "$([ -n "$_d" ] && [ -e "$_d/cpu-voltage-armed" ] && echo 1 || echo 0)" \
        "$([ -n "$_d" ] && cpuv_keep_good "$_d" && echo 1 || echo 0)"
    if [ -n "$_rej" ]; then
        printf '"rejected":{"offsets":%s,"reason":%s},' "$(cpuv_arr "${_rej%% *}")" "$(jstr "${_rej#* }")"
    else
        printf '"rejected":null,'
    fi
    printf '"limits":{"min":%s,"max":%s,"step":%s,"dcdc_max":%s},"firmware":%s,"disk":%s,"confirm":%s,"good_after_min":%s,' \
        "$(snum "$(cpuv_limit min)")" "$(snum "$(cpuv_limit max)")" "$(snum "$(cpuv_limit step)")" \
        "$(snum "$(cpuv_limit dcdc_max)")" "$(jstr "$(cpuv_firmware)")" "$([ -n "$_d" ] && echo 1 || echo 0)" \
        "$(jstr "$CPUV_WORD")" "$CPUV_GOOD_MIN"
    _last=$(ls -t /var/log/mu300-stress-*.txt 2>/dev/null | head -n1)
    printf '"stress":{"running":%s,"last":%s},"domains":[' "$(cpuv_stress_running && echo 1 || echo 0)" \
        "$(jstr "$( [ -n "$_last" ] && head -n 12 "$_last" | cut -c1-160)")"
    _sep=
    for pol in $(policies); do
        [ -r "$pol/scaling_voltage_domain" ] || continue
        _rel=$(rd "$pol/related_cpus"); _lo=${_rel%% *}; _hi=${_rel##* }
        printf '%s{"domain":%s,"cpus":%s,"offset":%s,"table":[' "$_sep" "$(num "$(rd "$pol/scaling_voltage_domain")")" \
            "$(jstr "$_lo-$_hi")" "$(snum "$(rd "$pol/scaling_voltage_offset")")"
        awk 'NF == 2 && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ { printf "%s[%d,%d]", s, $1, $2; s = "," }' "$pol/scaling_voltage_table" 2>/dev/null
        printf ']}'
        _sep=,
    done
    printf ']}\n'
}

voltage_status_human() {
    if ! cpuv_kernel; then echo "This kernel has no CPU voltage offset (a mainline kernel of this release or later has it)."; return 0; fi
    _d=$(cpuv_dir) || _d=
    _app=$(cpuv_head "$CPUV_SYS/voltage_offset_uv"); _req=$(cpuv_head "$_d/cpu-voltage"); [ -n "$_req" ] || _req=0,0,0
    _good=$(cpuv_head "$_d/cpu-voltage-good")
    echo "CPU voltage offset (EXPERIMENTAL), uV for domains 0,1,2 (CPUs 0-3, 4-6, 7)"
    echo "  running now:  $_app ($(cpuv_head "$CPUV_SYS/voltage_state"))"
    echo "  asked for:    $_req   phase: $(cpuv_phase "$_app" "$_req" "$_good")"
    [ -n "$_good" ] && echo "  good mark:    $_good"
    if [ -n "$_d" ] && [ -e "$_d/cpu-voltage-armed" ]; then
        if cpuv_keep_good "$_d" && [ "$(sed -n 2p "$_d/cpu-voltage-armed" 2>/dev/null)" = up ]; then
            echo "  armed:        $(cpuv_head "$_d/cpu-voltage-armed") (good, and this boot was up $CPUV_GOOD_MIN minutes: keep-good keeps it after a power cut)"
        else
            echo "  armed:        $(cpuv_head "$_d/cpu-voltage-armed") (a boot that ends without a clean shutdown drops it)"
        fi
    fi
    [ -n "$_d" ] && echo "  keep-good:    $(cpuv_keep_good "$_d" && echo on || echo off)"
    [ -n "$_d" ] && [ -s "$_d/cpu-voltage-rejected" ] && echo "  taken back:   $(cpuv_head "$_d/cpu-voltage-rejected")"
    echo "  limits:       $(cpuv_head "$CPUV_SYS/voltage_limits")"
    echo "  firmware:     $(cpuv_firmware)"
    for pol in $(policies); do
        [ -r "$pol/scaling_voltage_domain" ] || continue
        echo "  domain $(rd "$pol/scaling_voltage_domain") (CPUs $(rd "$pol/related_cpus")): offset $(rd "$pol/scaling_voltage_offset") uV"
        awk 'NF == 2 { printf "    %5d MHz  %7.3f mV\n", $1 / 1000, $2 / 1000 }' "$pol/scaling_voltage_table" 2>/dev/null
    done
}

voltage_warning() { cat "$CPUV_WARN" 2>/dev/null || echo "!! EXPERIMENTAL: changing the CPU voltage can PERMANENTLY DAMAGE your device. At your own risk. !!"; }

voltage_write() {  # voltage_write DIR VALUE: the request, atomically; a new value starts without trial or good mark
    printf '%s\n' "$2" > "$1/cpu-voltage.tmp" && mv "$1/cpu-voltage.tmp" "$1/cpu-voltage" || return 1
    rm -f "$1/cpu-voltage-trial" "$1/cpu-voltage-good" "$1/cpu-voltage-rejected"
    sync
}

voltage_set() {  # voltage_set VALUE [--confirm WORD]
    cpuv_is_root || { echo "mu300-cpu: the CPU voltage offset is root only" >&2; return 1; }
    _v=$(cpuv_norm "$1"); _w=
    [ "${2:-}" = --confirm ] && _w=${3:-}
    cpuv_valid "$_v" || {
        echo "mu300-cpu: offsets are three whole 3125 uV steps within -25000..12500 uV, e.g. -6250,-6250,0" >&2; return 2; }
    [ "$_v" = 0,0,0 ] && { voltage_off; return; }
    cpuv_kernel || { echo "mu300-cpu: this kernel has no CPU voltage offset" >&2; return 1; }
    case $(cpuv_head "$CPUV_SYS/voltage_state") in disabled|failed|probing)
        echo "mu300-cpu: CPU frequency scaling is not running normally on this boot ($(cpuv_head "$CPUV_SYS/voltage_state")); refused" >&2; return 1 ;; esac
    case $_v in *[1-9]*)
        _lo=$(cpuv_limit min); _hi=$(cpuv_limit max)
        _o=$IFS; IFS=,; set -- $_v; IFS=$_o
        for _x; do
            { [ -n "$_lo" ] && [ "$_x" -lt "$(snum "$_lo")" ]; } || { [ -n "$_hi" ] && [ "$_x" -gt "$(snum "$_hi")" ]; } && {
                echo "mu300-cpu: $_x is outside this kernel's limits ($(cpuv_head "$CPUV_SYS/voltage_limits"))" >&2; return 2; }
            [ "$_x" -gt 0 ] && [ "$(snum "$(cpuv_limit dcdc_max)")" = 0 ] && {
                echo "mu300-cpu: raising the voltage needs the CPU DCDC maximum from the device tree, and this device's has none; refused" >&2; return 2; }
        done ;;
    esac
    _fw=$(cpuv_firmware)
    [ "$_fw" = known ] || { echo "mu300-cpu: the SoC firmware (SML) is $_fw: its voltage encoding is not known, refused" >&2; return 1; }
    if [ "$_w" != "$CPUV_WORD" ]; then
        voltage_warning >&2
        echo >&2
        echo "mu300-cpu: to go ahead, type the confirmation word: mu300-cpu voltage set $_v --confirm $CPUV_WORD" >&2
        return 2
    fi
    _d=$(cpuv_dir) || { echo "mu300-cpu: the Linux disk (.mu300) was not found" >&2; return 1; }
    voltage_write "$_d" "$_v" || { echo "mu300-cpu: could not write $_d/cpu-voltage" >&2; return 1; }
    say "CPU voltage offset $_v asked for (EXPERIMENTAL), from the next boot"
    voltage_warning
    cat <<EOF

Asked for $_v uV (domains 0,1,2). Nothing changes until the next reboot; then:
  - that boot is the trial: the offset is kept once it has been up $CPUV_GOOD_MIN minutes;
  - a boot with the offset that ends in a crash, a watchdog reset or a power cut drops it (back to 0,0,0), and so
    does a trial boot that ends before its $CPUV_GOOD_MIN minutes;
  - test it under load during the trial: mu300-cpu voltage stress 10
Back to the stock voltages at any time: mu300-cpu voltage off (and reboot).
EOF
}

voltage_off() {
    cpuv_is_root || { echo "mu300-cpu: the CPU voltage offset is root only" >&2; return 1; }
    _d=$(cpuv_dir) || { echo "mu300-cpu: the Linux disk (.mu300) was not found" >&2; return 1; }
    voltage_write "$_d" 0,0,0 || { echo "mu300-cpu: could not write $_d/cpu-voltage" >&2; return 1; }
    say "CPU voltage offset off from the next boot"
    _app=$(cpuv_head "$CPUV_SYS/voltage_offset_uv")
    if [ -n "$_app" ] && [ "$_app" != 0,0,0 ]; then
        echo "Off from the next boot. This boot keeps running with $_app until you reboot."
    else
        echo "Off: the stock voltages."
    fi
}

voltage_mark_good() {  # 10 minutes after boot (mu300-cpu-voltage.timer, the OpenWrt service)
    _d=$(cpuv_dir) || return 0
    _a=$(cpuv_head "$_d/cpu-voltage-armed")
    [ -n "$_a" ] || return 0
    _k=$(cpuv_head "$CPUV_SYS/voltage_offset_uv")
    [ "$_a" = "$_k" ] || { say "armed $_a but the kernel runs ${_k:-nothing}: no good mark"; return 0; }
    _up=$(cut -d. -f1 "$R/proc/uptime" 2>/dev/null)
    [ "${_up:-0}" -ge $((CPUV_GOOD_MIN * 60)) ] 2>/dev/null || { say "up ${_up:-?} s, the good mark needs $CPUV_GOOD_MIN minutes"; return 1; }
    if [ "$(cpuv_head "$_d/cpu-voltage-good")" != "$_a" ]; then
        echo "$_a" > "$_d/cpu-voltage-good" && rm -f "$_d/cpu-voltage-trial" && sync
        say "CPU voltage offset $_a: good mark after ${_up} s up"
    fi
    # this boot, too, was up its 10 minutes with the good value: "up" under the armed value (what keep-good asks of a
    # boot that then ends without a clean shutdown; every boot earns it again, the initramfs arms without it)
    [ "$(sed -n 2p "$_d/cpu-voltage-armed" 2>/dev/null)" = up ] && return 0
    printf '%s\nup\n' "$_a" > "$_d/cpu-voltage-armed.tmp" && mv "$_d/cpu-voltage-armed.tmp" "$_d/cpu-voltage-armed" && sync
    return 0
}

# keep-good (kanoqwq's fb0b28e7, "preserve confirmed CPU settings"; off by default, not tried on a device by him or
# here): a good value is not dropped when a boot that was up its 10 minutes with it ends without a clean shutdown. A
# board without a battery (the F50, the V50) is switched off by pulling its cable, and each time that dropped the
# value. A boot that ends before its 10 minutes still drops it, so a value that crashes early cannot loop the boots.
cpuv_keep_good() { [ "$(cpuv_head "$1/cpu-voltage-keep-good")" = 1 ]; }
voltage_keep_good() {  # voltage_keep_good [on|off]
    _d=$(cpuv_dir) || { echo "mu300-cpu: the Linux disk (.mu300) was not found" >&2; return 1; }
    case ${1:-} in
        '') cpuv_keep_good "$_d" && echo on || echo off; return 0 ;;
        on|off) ;;
        *) echo "usage: mu300-cpu voltage keep-good [on|off]" >&2; return 2 ;;
    esac
    cpuv_is_root || { echo "mu300-cpu: the CPU voltage offset is root only" >&2; return 1; }
    if [ "$1" = on ]; then
        echo 1 > "$_d/cpu-voltage-keep-good" || return 1
        echo "keep-good on: a good offset stays after a power cut, once its boot was up $CPUV_GOOD_MIN minutes (a crash then counts the same: mu300-cpu voltage off takes it back)"
    else
        rm -f "$_d/cpu-voltage-keep-good" || return 1
        echo "keep-good off: any boot that ends without a clean shutdown drops the offset"
    fi
    sync
    say "voltage keep-good $1"
}

voltage_shutdown() {  # a clean shutdown or reboot only: the armed mark goes; a stopped service is not a shutdown
    if [ -z "${MU300_SYSROOT:-}" ] && command -v systemctl >/dev/null 2>&1; then
        case $(systemctl is-system-running 2>/dev/null) in stopping) ;; *) say "not a shutdown: the armed mark stays"; return 0 ;; esac
    fi
    _d=$(cpuv_dir) || return 0
    [ -e "$_d/cpu-voltage-armed" ] || return 0
    rm -f "$_d/cpu-voltage-armed" && sync
    say "clean shutdown: the CPU voltage offset stays for the next boot"
}

voltage_stress() {  # voltage_stress [MINUTES] [--background]
    _m=10 _bg=
    for _a; do case $_a in --background) _bg=1 ;; *) _m=$_a ;; esac; done
    case $_m in ''|*[!0-9]*) echo "mu300-cpu: minutes: 1 to 120" >&2; return 2 ;; esac
    [ "$_m" -ge 1 ] && [ "$_m" -le 120 ] || { echo "mu300-cpu: minutes: 1 to 120" >&2; return 2; }
    cpuv_is_root || { echo "mu300-cpu: the stress test needs root" >&2; return 1; }
    _tk=${MU300_TOOLKIT:-/opt/mu300/bin/mu300-toolkit}
    if [ -z "$_bg" ]; then exec "$_tk" stress cpu "$_m"; fi
    cpuv_stress_running && { echo "mu300-cpu: a stress test is already running" >&2; return 1; }
    mkdir -p "$RUNROOT/mu300"
    # its own session, no terminal: mu300-toolkit then runs for the time and writes /var/log/mu300-stress-*.txt
    setsid "$_tk" stress cpu "$_m" </dev/null >/dev/null 2>&1 &
    echo $! > "$RUNROOT/mu300/cpu-voltage-stress.pid"
    echo "CPU stress test started for $_m minutes; the summary goes to /var/log/mu300-stress-*.txt"
}

voltage_main() {
    case ${1:-status} in
        status) if [ "${2:-}" = --json ]; then voltage_status_json; else voltage_status_human; fi ;;
        set) shift; [ $# -ge 1 ] || { echo "usage: mu300-cpu voltage set A,B,C --confirm $CPUV_WORD" >&2; return 2; }
             voltage_set "$@" ;;
        off) voltage_off ;;
        mark-good) voltage_mark_good ;;
        keep-good) voltage_keep_good "${2:-}" ;;
        shutdown) voltage_shutdown ;;
        stress) shift; voltage_stress "$@" ;;
        warning) voltage_warning ;;
        *) echo "usage: mu300-cpu voltage [status [--json]|set A,B,C --confirm $CPUV_WORD|off|keep-good [on|off]|stress [MINUTES] [--background]|warning]" >&2; return 2 ;;
    esac
}


case ${1:-status} in
    status) if [ "${2:-}" = --json ]; then status_json; else status_human; fi ;;
    profile)
        if [ -z "${2:-}" ]; then echo "$(conf_get PROFILE)"; exit 0; fi
        apply "$2" && conf_set PROFILE "$2" && { [ "${3:-}" = --json ] && status_json || status_human; } ;;
    apply) apply "$(conf_get PROFILE)"; cores_apply; lowlat_apply; services_apply ;;
    core) core_set "${2:-}" "${3:-}" ;;
    lowlatency)
        if [ -z "${2:-}" ]; then [ "$(conf_get LOWLATENCY)" = 1 ] && echo on || echo off; exit 0; fi
        lowlat_set "$2" ;;
    services)
        if [ -z "${2:-}" ]; then conf_get SERVICES; exit 0; fi
        services_set "$2" ;;
    voltage) shift; voltage_main "$@" ;;
    -h|--help|help) sed -n '2,20s/^# \{0,1\}//p' "$0" ;;
    *) echo "usage: mu300-cpu [status [--json]|profile [saving|balanced|performance]|apply|core N on|off|lowlatency [on|off]|services [little|all|apply]|voltage ...]" >&2; exit 2 ;;
esac
