Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
configs: defconfigs, fragments and a .config for the kernel's boot-arguments, the way Linux has them
shimokub4fd0228ed4f
diff --git a/.gitignore b/.gitignoreindex 5480a8b..86be0f7 100644--- a/.gitignore+++ b/.gitignore@@ -8,6 +8,7 @@!/README.md!/CONTRIBUTING.md!/ci/+!/configs/!/README.uk.md!/README.zh.md!/Makefilediff --git a/Makefile b/Makefileindex 461f07b..336968b 100644--- a/Makefile+++ b/Makefile@@ -15,19 +15,35 @@# make clean build output of the kernel, loader and images# make doctor check this machine and a phone on adb for what HakiOS needs (tools/doctor.sh)#+# Configuration, the way Linux's make does it (configs/, tools/hakios-config.py; docs/configs.md):+# make redwood_defconfig .config from configs/defconfig + configs/redwood_defconfig (any NAME_defconfig)+# make virt.config lay a fragment (configs/virt.config) over the .config there is+# make config show the .config: its symbols, the kernel's arguments, the firmware it wants+# make savedefconfig the .config as a minimal defconfig+# make phone with a .config, its arguments are the kernel's; without, the phone line below+# FRAGMENTS="open trace" fragments for a NAME_defconfig: make redwood_defconfig FRAGMENTS=open+## DEVICE=poco-x5-pro the device directory under devices/ (default poco-x5-pro)-# ARGS="..." kernel arguments for make phone (default: everything the phone has)+# ARGS="..." kernel arguments for make phone (default: the .config's, else everything the phone has)# SECS=600 the session's length for make phone / make qemu# JOBS=8 parallel jobs for the kernel buildDEVICE ?= poco-x5-proJOBS ?= 8SECS ?= 600-ARGS_OPEN ?= cpus=1+# qemu-open runs the open configuration: configs/defconfig (nothing of a phone's own, one core)+ARGS_OPEN ?= $(shell tools/hakios-config.py args --defconfig defconfig)+ifneq ($(wildcard .config),)+# a .config is the kernel's arguments; the runner then does not add its own four (cores, clock, storage): they are in it+ARGS ?= $(shell tools/hakios-config.py args)+RUNNER_BASE = BASE_ARGS=+elseARGS ?= touchscreen=1 gpu=1 adsp=1 sound=4 wifi=1 haptic=5 modem=1 modem_again=1 modem_buffer=0xa8000000+RUNNER_BASE =+endifIMAGE_OPTS ?= REST=1-.PHONY: help fetch images kernel loader loader-open hello qemu qemu-open phone prebuilt clean all doctor+.PHONY: help fetch images kernel loader loader-open hello qemu qemu-open phone prebuilt clean all doctor defconfig config savedefconfighelp:@awk '{ if (!/^#/) exit; sub(/^# ?/, ""); print }' Makefile@@ -79,7 +95,24 @@ qemu-open: kernel loader-open helloqemu/run.sh $(SECS) | tee logs/qemu-open.logphone:- XL_SB_DELAY=8 tools/modem-cycle.sh "$(ARGS)" $(SECS)+ [ ! -f .config ] || tools/hakios-config.py check+ XL_SB_DELAY=8 $(RUNNER_BASE) tools/modem-cycle.sh "$(ARGS)" $(SECS)++# ---- configuration (configs/, tools/hakios-config.py) ---------------------------------------------------------+defconfig:+ tools/hakios-config.py defconfig defconfig $(FRAGMENTS)++%_defconfig:+ tools/hakios-config.py defconfig $* $(FRAGMENTS)++%.config:+ tools/hakios-config.py merge $*++config:+ tools/hakios-config.py show++savedefconfig:+ tools/hakios-config.py savedefconfigprebuilt:tools/update-prebuilt.shdiff --git a/ci/github-check.yml b/ci/github-check.ymlindex a393d31..65f71bd 100644--- a/ci/github-check.yml+++ b/ci/github-check.yml@@ -27,6 +27,8 @@ jobs:run: python3 tools/provenance-test.py- name: A run sends only the soc_* values that differ from the kernel's defaultsrun: bash tools/soc-only-changes-test.sh+ - name: Configurations - defconfigs, fragments, the arguments made from them+ run: python3 tools/hakios-config-test.py- name: The kernel's version string is made as it should berun: python3 tools/kernel-version-test.py- name: The kernel patch applies to Apple's treediff --git a/configs/defconfig b/configs/defconfignew file mode 100644index 0000000..17f8853--- /dev/null+++ b/configs/defconfig@@ -0,0 +1,4 @@+# HakiOS defconfig: what every configuration starts from. It is the open one: nothing of a phone's own, one core.+# (`make qemu-open` runs this; a device's defconfig is laid over it: make redwood_defconfig.)+CONFIG_FIRMWARE="none"+CONFIG_CPUS=1diff --git a/configs/open.config b/configs/open.confignew file mode 100644index 0000000..f21cc33--- /dev/null+++ b/configs/open.config@@ -0,0 +1,13 @@+# Fragment: the open profile. Nothing of the phone's own is loaded: no GPU, Wi-Fi, audio, haptic, camera or modem firmware.+# Laid over a device's defconfig it gives that phone's configuration without a single file pulled from the device.+CONFIG_FIRMWARE="none"+# CONFIG_GPU is not set+# CONFIG_ADSP is not set+# CONFIG_SOUND is not set+# CONFIG_MIC is not set+# CONFIG_WIFI is not set+# CONFIG_HAPTIC is not set+# CONFIG_CAM is not set+# CONFIG_MODEM is not set+# CONFIG_MODEM_AGAIN is not set+# CONFIG_MODEM_BUFFER is not setdiff --git a/configs/persist.config b/configs/persist.confignew file mode 100644index 0000000..243d323--- /dev/null+++ b/configs/persist.config@@ -0,0 +1,7 @@+# Fragment: keep /private/var across reboots. THIS WRITES TO THE PHONE'S STORAGE, to the partition `darwin` only.+# The kernel and the loader refuse any other write. The partition has to exist: it is cut off the end of Android's+# userdata once, by hand (tools/userdata-carve.py prints the commands and says what they do to Android's data).+# Without that partition, leave this fragment out.+CONFIG_UFS=2+CONFIG_UFS_WRITE=y+CONFIG_VAR_STORE=ydiff --git a/configs/redwood_defconfig b/configs/redwood_defconfignew file mode 100644index 0000000..1893659--- /dev/null+++ b/configs/redwood_defconfig@@ -0,0 +1,19 @@+# HakiOS defconfig for the POCO X5 Pro 5G (redwood, SM7325, devices/poco-x5-pro): the arguments the project's own phone line uses.+# It is exactly what `make phone` and tools/modem-cycle.sh passed before there were configurations, so choosing it changes nothing.+# Needs the phone's own firmware pulled from your phone (devices/poco-x5-pro/pull-firmware.sh): `tools/hakios-config.py needs`.+CONFIG_DEVICE="poco-x5-pro"+CONFIG_SOC="sc7280"+CONFIG_FIRMWARE="device"+CONFIG_CPUS=8+CONFIG_BOOTCPU=7+CONFIG_CPUFREQ=y+CONFIG_UFS=2+CONFIG_TOUCHSCREEN=y+CONFIG_GPU=y+CONFIG_ADSP=y+CONFIG_SOUND=4+CONFIG_WIFI=y+CONFIG_HAPTIC=5+CONFIG_MODEM=y+CONFIG_MODEM_AGAIN=y+CONFIG_MODEM_BUFFER=0xa8000000diff --git a/configs/trace.config b/configs/trace.confignew file mode 100644index 0000000..a8f02bb--- /dev/null+++ b/configs/trace.config@@ -0,0 +1,3 @@+# Fragment: tracing, a log line for each of the first 20 frames on the network interfaces.+# (CONFIG_NET_NAMES, which logs the names asked of DNS, is not here on purpose: it writes what you browse into the log.)+CONFIG_NET_TRACE=20diff --git a/configs/virt.config b/configs/virt.confignew file mode 100644index 0000000..e6ff7d1--- /dev/null+++ b/configs/virt.config@@ -0,0 +1,3 @@+# Fragment: QEMU's virt machine. QEMU's virtio network device as en0 (its bus address means nothing on a phone).+CONFIG_FIRMWARE="none"+CONFIG_VIRTIO_NET=ydiff --git a/tools/hakios-config-test.py b/tools/hakios-config-test.pynew file mode 100644index 0000000..8e0b008--- /dev/null+++ b/tools/hakios-config-test.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""tools/hakios-config.py: what the configurations of configs/ give, and what the tool refuses.++ the real configs/ redwood gives exactly the arguments the project's phone line used before there were configurations+ (so choosing it changes nothing); redwood + open loads nothing of the phone's own; persist adds the+ writes to `darwin`; virt and trace do what they say; kernel.ver carries -sc7280+ refusals an unknown symbol (with a suggestion), a firmware option in the open profile, a dependency that is+ missing, a number out of range, a bad hex or string, a command line that cannot fit+ workflow merge over an existing .config; `is not set` in a fragment switches off; savedefconfig round-trips;+ --config and --root work after the command as well as before it+"""+import os+import shutil+import subprocess+import sys+import tempfile+import importlib.util++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(HERE)+TOOL = os.path.join(HERE, "hakios-config.py")+failures = []++# what `make phone` passed before there were configurations: the runner's four, then the Makefile's ARGS+OLD_PHONE_LINE = ("bootcpu=7 cpus=8 cpufreq=1 ufs=2 touchscreen=1 gpu=1 adsp=1 sound=4 wifi=1 haptic=5 modem=1 modem_again=1 "+ "modem_buffer=0xa8000000").split()+++def check(label, ok, detail=""):+ print("%s %s" % ("ok " if ok else "FAIL", label))+ if not ok:+ failures.append(label)+ if detail:+ print(" " + str(detail).strip().replace("\n", "\n ")[:500])+++def run(*args, root=ROOT):+ return subprocess.run([sys.executable, TOOL, "--root", root, *args], capture_output=True, text=True)+++def args_of(out):+ return out.stdout.split()+++work = tempfile.mkdtemp(prefix="hakios-config-test-")+try:+ cfg = os.path.join(work, "cfg")++ r = run("defconfig", "redwood", "-o", cfg)+ check("defconfig redwood: makes the .config", r.returncode == 0 and os.path.isfile(cfg), r.stdout + r.stderr)+ a = args_of(run("args", "--config", cfg))+ check("redwood: the same arguments as the project's phone line before configurations", sorted(a) == sorted(OLD_PHONE_LINE),+ "got %s\nwant %s" % (sorted(a), sorted(OLD_PHONE_LINE)))+ check("redwood: kernel.ver carries the SoC", "-sc7280-" in r.stdout, r.stdout)+ check("redwood: the .config is in Linux's form",+ "CONFIG_GPU=y" in open(cfg).read() and "# CONFIG_CAM is not set" in open(cfg).read() and 'CONFIG_FIRMWARE="device"' in open(cfg).read())+ check("redwood: check passes", run("check", "--config", cfg).returncode == 0)++ r = run("needs", "--config", cfg)+ check("redwood: needs says which firmware, and that it is missing here (none is pulled in a clean checkout)",+ "fw-gpu/" in r.stdout and "fw-modem/" in r.stdout, r.stdout)++ # the open profile over redwood+ o = os.path.join(work, "open")+ r = run("defconfig", "redwood", "open", "-o", o)+ check("redwood + open: passes", r.returncode == 0, r.stdout + r.stderr)+ check("redwood + open: nothing of the phone's own is loaded",+ sorted(args_of(run("args", "--config", o))) == sorted("cpus=8 bootcpu=7 cpufreq=1 ufs=2 touchscreen=1".split()),+ run("args", "--config", o).stdout)+ r = run("needs", "--config", o)+ check("redwood + open: needs nothing", r.returncode == 0 and "nothing of the phone's own" in r.stdout, r.stdout)++ # fragments+ p = os.path.join(work, "persist")+ shutil.copyfile(cfg, p)+ r = run("merge", "persist", "--config", p)+ check("merge persist: ufs_write and var_store appear", r.returncode == 0 and {"ufs_write=1", "var_store=1"} <= set(args_of(run("args", "--config", p))), r.stdout + r.stderr)+ check("merge persist: UFS stays 2, not duplicated", args_of(run("args", "--config", p)).count("ufs=2") == 1)+ v = os.path.join(work, "virt")+ run("defconfig", "defconfig", "virt", "-o", v)+ check("defconfig + virt: virtio_net, one core, no firmware", sorted(args_of(run("args", "--config", v))) == ["cpus=1", "virtio_net=1"],+ run("args", "--config", v).stdout)+ d = os.path.join(work, "base")+ run("defconfig", "defconfig", "-o", d)+ check("defconfig alone is the open one: cpus=1", args_of(run("args", "--config", d)) == ["cpus=1"], run("args", "--config", d).stdout)+ t = os.path.join(work, "trace")+ run("defconfig", "redwood", "trace", "-o", t)+ check("trace: net_trace=20", "net_trace=20" in args_of(run("args", "--config", t)))++ # the arguments straight from a defconfig, with no .config made (what `make qemu-open` asks for)+ check("args --defconfig defconfig: cpus=1", args_of(run("args", "--defconfig", "defconfig")) == ["cpus=1"], run("args", "--defconfig", "defconfig").stdout)+ check("args --defconfig redwood --fragment open: the open phone",+ sorted(args_of(run("args", "--defconfig", "redwood", "--fragment", "open"))) == sorted("cpus=8 bootcpu=7 cpufreq=1 ufs=2 touchscreen=1".split()))+ check("args --defconfig redwood: the same as the .config's", sorted(args_of(run("args", "--defconfig", "redwood"))) == sorted(a))++ # the order of the arguments is the table's: cpus first, as in the README's lines+ check("the arguments come in the order of the symbol table", args_of(run("args", "--config", cfg))[:3] == ["cpus=8", "bootcpu=7", "cpufreq=1"])++ # savedefconfig round trip: the minimal defconfig, made a defconfig of its own, gives the same arguments+ sd = run("savedefconfig", "--config", cfg)+ check("savedefconfig: drops what defconfig already has", "CONFIG_FIRMWARE=\"none\"" not in sd.stdout and "CONFIG_GPU=y" in sd.stdout, sd.stdout)+ fake = os.path.join(work, "root")+ shutil.copytree(os.path.join(ROOT, "configs"), os.path.join(fake, "configs"))+ open(os.path.join(fake, "configs", "mine_defconfig"), "w").write(sd.stdout)+ shutil.copyfile(os.path.join(ROOT, "VERSION"), os.path.join(fake, "VERSION"))+ r = run("defconfig", "mine", "-o", os.path.join(work, "mine"), root=fake)+ check("savedefconfig round trip: same arguments", sorted(args_of(run("args", "--config", os.path.join(work, "mine"), root=fake))) == sorted(a), r.stdout + r.stderr)++ # `--config` and `--root` after the command too (checked above for --config); before it:+ check("--config before the command works too", run("--config", cfg, "check").returncode == 0)++ # refusals, one configuration each in a temporary configs/+ def refusal(label, text, want, base_text=None):+ d = os.path.join(work, "r%d" % len(os.listdir(work)))+ os.makedirs(os.path.join(d, "configs"))+ open(os.path.join(d, "configs", "defconfig"), "w").write(base_text if base_text is not None else 'CONFIG_FIRMWARE="device"\nCONFIG_CPUS=1\n')+ open(os.path.join(d, "configs", "bad_defconfig"), "w").write(text)+ shutil.copyfile(os.path.join(ROOT, "VERSION"), os.path.join(d, "VERSION"))+ r = run("defconfig", "bad", "-o", os.path.join(d, "out"), root=d)+ out = r.stdout + r.stderr+ check(label, r.returncode != 0 and want in out, "exit %d, want %r in:\n%s" % (r.returncode, want, out))++ refusal("an unknown symbol is refused, with a suggestion", "CONFIG_WIFFI=y\n", "did you mean CONFIG_WIFI")+ refusal("a line that is no setting is refused, with its number", "this is not a setting\n", "bad_defconfig:1")+ refusal("a firmware option in the open profile is refused", 'CONFIG_FIRMWARE="none"\nCONFIG_GPU=y\n', "needs the phone's own firmware")+ refusal("a missing dependency is refused (modem without ufs=2)", "CONFIG_MODEM=y\nCONFIG_UFS=1\n", "requires CONFIG_UFS=2")+ refusal("var_store without ufs_write is refused", "CONFIG_VAR_STORE=y\n", "requires CONFIG_UFS_WRITE")+ refusal("cpus out of range", "CONFIG_CPUS=9\n", "CONFIG_CPUS is 1 to 8")+ refusal("a hex that is not hex", "CONFIG_UFS=2\nCONFIG_MODEM=y\nCONFIG_MODEM_BUFFER=a8000000\n", "starts with 0x")+ refusal("a bool that is not y", "CONFIG_GPU=1\n", "is a bool: y, or not set")+ refusal("a string without quotes", "CONFIG_DEVICE=redwood\n", "string in quotes")+ refusal("a FIRMWARE that is neither", 'CONFIG_FIRMWARE="maybe"\n', '"device" or "none"')++ r = run("defconfig", "nosuchphone", "-o", os.path.join(work, "x"))+ check("an unknown defconfig lists what there is", r.returncode != 0 and "redwood_defconfig" in (r.stdout + r.stderr), r.stdout + r.stderr)+ r = run("args", "--config", os.path.join(work, "nothing"))+ check("no .config: says how to make one", r.returncode != 0 and "defconfig NAME" in (r.stdout + r.stderr), r.stdout + r.stderr)++ # `=n` for a bool is `is not set`; a later `is not set` removes what an earlier file set+ fake2 = os.path.join(work, "root2")+ os.makedirs(os.path.join(fake2, "configs"))+ shutil.copyfile(os.path.join(ROOT, "VERSION"), os.path.join(fake2, "VERSION"))+ open(os.path.join(fake2, "configs", "defconfig"), "w").write("CONFIG_CPUS=2\nCONFIG_CPUFREQ=y\n")+ open(os.path.join(fake2, "configs", "x_defconfig"), "w").write("CONFIG_CPUFREQ=n\nCONFIG_TOUCHSCREEN=y\n")+ open(os.path.join(fake2, "configs", "y.config"), "w").write("# CONFIG_TOUCHSCREEN is not set\n")+ out2 = os.path.join(work, "o2")+ run("defconfig", "x", "y", "-o", out2, root=fake2)+ check("=n and `is not set` switch a symbol off", args_of(run("args", "--config", out2, root=fake2)) == ["cpus=2"], run("args", "--config", out2, root=fake2).stdout)++ # the command line that cannot fit: the table is short, so shrink the limit and ask the checker+ spec = importlib.util.spec_from_file_location("hc", TOOL)+ hc = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(hc)+ hc.KERNEL_LINE = 300+ problems, _ = hc.check({"CPUS": "8", "BOOTCPU": "7", "UFS": "2", "MODEM": "y", "MODEM_BUFFER": "0xa8000000", "FIRMWARE": '"device"'})+ check("a command line that cannot fit is a problem", any("the end of it would be lost" in p for p in problems), problems)++ # help, show, list+ r = run("help", "gpu")+ check("help GPU: the argument, the firmware", "gpu=1" in r.stdout and "fw-gpu/" in r.stdout, r.stdout)+ r = run("help", "CONFIG_MODEM_BUFFER")+ check("help takes CONFIG_ and says what it requires", r.returncode == 0 and "requires: CONFIG_MODEM" in r.stdout, r.stdout)+ r = run("help", "gpuu")+ check("help on an unknown symbol suggests", r.returncode != 0 and "did you mean CONFIG_GPU" in r.stdout, r.stdout)+ r = run("list")+ check("list: defconfigs and fragments", all(x in r.stdout for x in ("redwood", "open", "virt", "persist", "trace")), r.stdout)+finally:+ shutil.rmtree(work, ignore_errors=True)++if failures:+ sys.exit("hakios-config-test: %d FAILED" % len(failures))+print("hakios-config-test: all passed")diff --git a/tools/hakios-config.py b/tools/hakios-config.pynew file mode 100644index 0000000..474594f--- /dev/null+++ b/tools/hakios-config.py@@ -0,0 +1,442 @@+#!/usr/bin/env python3+"""HakiOS configuration: defconfigs, fragments, a .config and the kernel's boot-arguments made from it.++The way Linux does it (arch/arm64/configs/<device>_defconfig, scripts/kconfig/merge_config.sh, `make+savedefconfig`), for a kernel whose options are not compiled in but given on its command line:++ tools/hakios-config.py defconfig redwood .config = configs/defconfig + configs/redwood_defconfig+ tools/hakios-config.py defconfig redwood open ... and the fragment configs/open.config on top+ tools/hakios-config.py merge virt put a fragment over the .config there is+ tools/hakios-config.py args the kernel's boot-arguments for the .config+ tools/hakios-config.py check | show | needs validate it; say what it is; which firmware it wants+ tools/hakios-config.py savedefconfig the .config as a minimal defconfig (its differences from configs/defconfig)+ tools/hakios-config.py list | help SYMBOL what configs/ holds; what a symbol means++`make redwood_defconfig` and `make config` call it.++A symbol CONFIG_GPU=y is the boot-argument gpu=1; CONFIG_CPUS=8 is cpus=8; CONFIG_MODEM_BUFFER=0xa8000000 is+modem_buffer=0xa8000000. A symbol that is "not set" is left out of the command line (the kernel's own default+applies). A few symbols are not arguments but facts about the build (CONFIG_DEVICE, CONFIG_SOC, CONFIG_FIRMWARE).++Where this differs from Linux's, on purpose:+ - CONFIG_FIRMWARE="none" is a profile that loads NOTHING of the phone's own (no GPU, Wi-Fi, audio or modem+ firmware pulled from the device): the open configuration. The check refuses an option that needs firmware in it.+ - the kernel's command line holds 607 characters; the check says how much of them the configuration takes, and+ refuses what cannot fit, because a command line that is too long loses its tail without an error.+"""+import argparse+import difflib+import os+import re+import subprocess+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(HERE)+KERNEL_LINE = 607 # BOOT_LINE_LENGTH 608 less the terminator: what the kernel's boot_args can hold+RUN_OVERHEAD = 260 # what a run adds itself: the loader's own arguments, xl's, the runner's (measured: ~190-250)++# name, kind, boot-arg, one-line help, firmware directory it needs, what it requires+# kinds: bool (y/n, becomes arg=1), int, hex, str, and meta (a fact about the build, not an argument)+SYMBOLS = [+ ("DEVICE", "meta", None, "the directory of the phone under devices/ this configuration is for", None, None),+ ("SOC", "meta", None, "the SoC family (sc7280: SM7325, QCM6490); it is part of the kernel's version string", None, None),+ ("FIRMWARE", "meta", None, "\"device\": options may use firmware pulled from your own phone (fw-*/); \"none\": the open "+ "configuration, nothing of the phone's own is loaded", None, None),+ ("CPUS", "int", "cpus", "CPU cores the kernel uses, 1 to 8; one if not set", None, None),+ ("BOOTCPU", "int", "bootcpu", "the core the kernel runs on, 0 to 7; 7 is the biggest core (the loader keeps core 0)", None, None),+ ("CPUFREQ", "bool", "cpufreq", "set the boot core to its top speed", None, None),+ ("UFS", "int", "ufs", "the phone's storage: 1 a survey, read only; 2 the loader's block service, through which the kernel "+ "reads it (the modem's file systems, /private/var)", None, None),+ ("UFS_WRITE", "bool", "ufs_write", "let the kernel write, to the partition `darwin` and nowhere else (writes to the phone's "+ "storage: it is the one switch for it)", None, "UFS=2"),+ ("VAR_STORE", "bool", "var_store", "keep /private/var across reboots, in the partition `darwin`", None, "UFS_WRITE"),+ ("TOUCHSCREEN", "bool", "touchscreen", "the touch screen, and the power and volume buttons", None, None),+ ("GPU", "bool", "gpu", "rendering on Adreno (an image built with GL=1; the GPU's firmware from your phone)", "fw-gpu", None),+ ("ADSP", "bool", "adsp", "the audio DSP; the battery level in the UI and charging state come through it", "fw-audio", None),+ ("SOUND", "int", "sound", "the speakers (4 is what the README's phone line uses)", "fw-audio", "ADSP"),+ ("MIC", "int", "mic", "the microphone (4 is what the README's phone line uses)", "fw-audio", "ADSP"),+ ("WIFI", "bool", "wifi", "Wi-Fi: the radio, its driver, a connection (also fw-wifi/mac and fw-wifi/network)", "fw-wifi", None),+ ("HAPTIC", "int", "haptic", "the vibration motor (5 is what the README's phone line uses)", "fw-haptic", None),+ ("CAM", "int", "cam", "the cameras (5 is what the README uses)", "fw-camera", None),+ ("MODEM", "bool", "modem", "the modem beside the system: its firmware, file systems, IPA, SIM, NAS", "fw-modem", "UFS=2"),+ ("MODEM_AGAIN", "bool", "modem_again", "start the modem although a kernel before this one left it shut down", None, "MODEM"),+ ("MODEM_BUFFER", "hex", "modem_buffer", "the modem's RMTFS buffer, an address below 4 GB (0xa8000000 on the reference phone)", None, "MODEM"),+ ("NET_TRACE", "int", "net_trace", "a log line for each of the first N frames on the network interfaces", None, None),+ ("NET_NAMES", "bool", "net_names", "a log line for every name asked of a DNS server and every TCP connection begun "+ "(the names go to the log: for debugging only)", None, None),+ ("VIRTIO_NET", "bool", "virtio_net", "QEMU's virtio network device as en0 (QEMU only; its bus address means nothing on a phone)", None, None),+]+BY_NAME = {s[0]: s for s in SYMBOLS}+FIRMWARE_VALUES = ("device", "none")+RANGES = {"CPUS": (1, 8), "BOOTCPU": (0, 7), "UFS": (1, 2)}+++class ConfigError(Exception):+ pass+++# ---- reading and writing --------------------------------------------------------------------------------------++def parse(path):+ """A defconfig, a fragment or a .config as (set, unset): {NAME: value} and a set of NAMEs `# CONFIG_X is not set`.+ Linux's rules: CONFIG_NAME=value, strings in quotes, no comment after a value, `# CONFIG_NAME is not set` is the+ way to say a symbol is off (so that a fragment can switch off what an earlier file switched on). `=n` is accepted+ for a bool as the same thing."""+ values, unset = {}, set()+ for n, raw in enumerate(open(path, encoding="utf-8"), 1):+ line = raw.strip()+ m = re.fullmatch(r"#\s*CONFIG_([A-Z0-9_]+) is not set", line)+ if m:+ unset.add(m.group(1))+ values.pop(m.group(1), None)+ continue+ if not line or line.startswith("#"):+ continue+ m = re.fullmatch(r"CONFIG_([A-Z0-9_]+)=(.*)", line)+ if not m:+ raise ConfigError("%s:%d: want CONFIG_NAME=value or # CONFIG_NAME is not set, got %r" % (path, n, line))+ name, value = m.group(1), m.group(2)+ if name not in BY_NAME:+ close = difflib.get_close_matches(name, BY_NAME, n=1)+ raise ConfigError("%s:%d: no symbol CONFIG_%s%s" % (path, n, name, " (did you mean CONFIG_%s?)" % close[0] if close else ""))+ if value == "n" and BY_NAME[name][1] == "bool":+ unset.add(name)+ values.pop(name, None)+ continue+ values[name] = value+ unset.discard(name)+ return values, unset+++def typed(name, value):+ """The value of a symbol as Python has it, or a ConfigError that says what is wrong."""+ kind = BY_NAME[name][1]+ if kind == "bool":+ if value != "y":+ raise ConfigError("CONFIG_%s is a bool: y, or not set (got %s)" % (name, value))+ return True+ if kind in ("int", "hex"):+ if kind == "hex" and not value.lower().startswith("0x"):+ raise ConfigError("CONFIG_%s is a hex number and starts with 0x (got %s)" % (name, value))+ try:+ number = int(value, 16 if value.lower().startswith("0x") else 10)+ except ValueError:+ raise ConfigError("CONFIG_%s wants a %s, got %s" % (name, "hex number (0x...)" if kind == "hex" else "number", value))+ low, high = RANGES.get(name, (0, None))+ if number < low or (high is not None and number > high):+ raise ConfigError("CONFIG_%s is %s to %s, got %s" % (name, low, high if high is not None else "any", value))+ return number+ if not (len(value) >= 2 and value[0] == '"' and value[-1] == '"'):+ raise ConfigError("CONFIG_%s is a string in quotes (got %s)" % (name, value))+ text = value[1:-1]+ if name == "FIRMWARE" and text not in FIRMWARE_VALUES:+ raise ConfigError('CONFIG_FIRMWARE is "device" or "none" (got "%s")' % text)+ if not re.fullmatch(r"[A-Za-z0-9._-]*", text):+ raise ConfigError("CONFIG_%s holds letters, digits, dots, dashes and underscores (got %s)" % (name, value))+ return text+++def config_dir(root):+ return os.path.join(root, "configs")+++def find_config(root, name):+ """configs/<name>, configs/<name>_defconfig or configs/<name>.config: the file for NAME."""+ base = os.path.basename(name)+ for candidate in (base, base + "_defconfig", base + ".config"):+ path = os.path.join(config_dir(root), candidate)+ if os.path.isfile(path):+ return path+ available = sorted(os.listdir(config_dir(root))) if os.path.isdir(config_dir(root)) else []+ raise ConfigError("no configs/%s, configs/%s_defconfig or configs/%s.config (there is: %s)" %+ (base, base, base, ", ".join(available) or "nothing"))+++def overlay(config, files):+ """`config` with the files laid over it, later ones winning; `is not set` in a file removes a symbol.+ The same for the first file on an empty config (defconfig) and for a fragment over an existing one (merge)."""+ result = dict(config)+ for path in files:+ values, unset = parse(path)+ for name in unset:+ result.pop(name, None)+ result.update(values)+ return result+++def resolve(root, names):+ """The files for `defconfig NAME FRAGMENT...`: the base, the device's defconfig, then the fragments."""+ files = [find_config(root, "defconfig")]+ device = names[0] if names else "defconfig"+ if device not in ("defconfig", ""):+ files.append(find_config(root, device if device.endswith("_defconfig") else device + "_defconfig"))+ files += [find_config(root, f) for f in names[1:]]+ return files+++def rel(base, path):+ """`path` relative to `base` for the messages; as it is when it cannot be (another drive on Windows)."""+ try:+ return os.path.relpath(path, base).replace(os.sep, "/")+ except ValueError:+ return path.replace(os.sep, "/")+++def write_config(config, path, sources):+ """The .config, in the form Linux's has: every symbol, set or `is not set`, in the order of the table."""+ lines = ["#",+ "# Made by tools/hakios-config.py from %s." % ", ".join(sources),+ "# Do not edit it: change a defconfig or a fragment in configs/, and make the .config again.",+ "#"]+ for name, kind, _arg, _help, _needs, _requires in SYMBOLS:+ if name in config:+ lines.append("CONFIG_%s=%s" % (name, config[name]))+ elif kind != "meta":+ lines.append("# CONFIG_%s is not set" % name)+ open(path, "w", encoding="utf-8", newline="\n").write("\n".join(lines) + "\n")+++def kernel_ver(root, config_path):+ """The kernel.ver string this .config gives (tools/kernel-version.py reads CONFIG_SOC from it)."""+ out = subprocess.run([sys.executable, os.path.join(HERE, "kernel-version.py"), "--config", config_path, "--root", root],+ capture_output=True, text=True)+ return out.stdout.strip() or "unknown"+++# ---- what a configuration means -------------------------------------------------------------------------------++def check(config):+ """(problems, boot-arguments) of a merged configuration: the problems are strings, empty if it is fine."""+ problems = []+ parsed = {}+ for name, value in config.items():+ try:+ parsed[name] = typed(name, value)+ except ConfigError as e:+ problems.append(str(e))+ firmware = parsed.get("FIRMWARE", "device")+ for name in parsed:+ _n, _kind, _arg, _help, needs, requires = BY_NAME[name]+ if needs and firmware == "none":+ problems.append('CONFIG_%s needs the phone\'s own firmware (%s/), and this configuration says CONFIG_FIRMWARE="none": '+ "it loads nothing from the device" % (name, needs))+ if requires:+ wanted, _, value = requires.partition("=")+ have = parsed.get(wanted)+ if have is None or (value and str(have) != value):+ problems.append("CONFIG_%s requires CONFIG_%s%s" % (name, wanted, "=" + value if value else ""))+ args = boot_args(parsed)+ length = len(" ".join(args))+ if length > KERNEL_LINE - RUN_OVERHEAD:+ problems.append("the boot-arguments take %d characters; a run adds about %d of its own and the kernel's command line holds %d: "+ "the end of it would be lost" % (length, RUN_OVERHEAD, KERNEL_LINE))+ return problems, args+++def boot_args(parsed):+ """['cpus=8', 'gpu=1', ...] in the order of the symbol table."""+ args = []+ for name, kind, arg, _help, _needs, _requires in SYMBOLS:+ if name not in parsed or arg is None:+ continue+ value = parsed[name]+ if kind == "bool":+ args.append("%s=1" % arg)+ elif kind == "hex":+ args.append("%s=0x%x" % (arg, value))+ else:+ args.append("%s=%s" % (arg, value))+ return args+++def load(path):+ if not os.path.isfile(path):+ raise ConfigError("no %s: make one with `tools/hakios-config.py defconfig NAME` (or `make NAME_defconfig`)" % path)+ return parse(path)[0]+++def report(problems):+ for p in problems:+ print("hakios-config: PROBLEM: " + p)+++# ---- commands ---------------------------------------------------------------------------------------------------++def cmd_defconfig(a):+ files = resolve(a.root, [a.name] + a.fragments)+ config = overlay({}, files)+ problems, args = check(config)+ write_config(config, a.output, [rel(a.root, f) for f in files])+ print("hakios-config: %s made from %s" % (rel(os.getcwd(), a.output), ", ".join(os.path.basename(f) for f in files)))+ print("hakios-config: %d characters of boot-arguments; kernel.ver=%s" % (len(" ".join(args)), kernel_ver(a.root, a.output)))+ report(problems)+ return 1 if problems else 0+++def cmd_merge(a):+ files = [find_config(a.root, f) for f in a.fragments]+ config = overlay(load(a.config), files)+ problems, args = check(config)+ write_config(config, a.config, [".config"] + [rel(a.root, f) for f in files])+ print("hakios-config: %s merged into %s; %d characters of boot-arguments" %+ (", ".join(os.path.basename(f) for f in files), rel(os.getcwd(), a.config), len(" ".join(args))))+ report(problems)+ return 1 if problems else 0+++def cmd_args(a):+ if a.defconfig:+ # the arguments of a defconfig and fragments, without making a .config (what `make qemu-open` asks for)+ config = overlay({}, resolve(a.root, [a.defconfig] + a.fragment))+ else:+ config = load(a.config)+ problems, args = check(config)+ if problems and not a.force:+ for p in problems:+ print("hakios-config: PROBLEM: " + p, file=sys.stderr)+ return 1+ print(" ".join(args))+ return 0+++def cmd_check(a):+ config = load(a.config)+ problems, args = check(config)+ for p in problems:+ print("PROBLEM: " + p)+ print("%s: %d symbols set, %d characters of boot-arguments (the kernel holds %d; a run adds about %d)%s" % (+ rel(os.getcwd(), a.config), len(config), len(" ".join(args)), KERNEL_LINE, RUN_OVERHEAD,+ "" if not problems else ", %d problem(s)" % len(problems)))+ return 1 if problems else 0+++def cmd_show(a):+ config = load(a.config)+ problems, args = check(config)+ given = {x.split("=", 1)[0]: x for x in args}+ print("HakiOS configuration %s, kernel.ver=%s" % (rel(os.getcwd(), a.config), kernel_ver(a.root, a.config)))+ for name, _kind, arg, _help, _needs, _requires in SYMBOLS:+ if name in config:+ print(" CONFIG_%-13s = %-14s %s" % (name, config[name], "-> " + given[arg] if arg in given else "(a fact about the build)"))+ print("boot-arguments: %s" % " ".join(args))+ print("firmware wanted from the phone: %s" % (", ".join(sorted({BY_NAME[n][4] for n in config if BY_NAME[n][4]})) or "none"))+ for p in problems:+ print("PROBLEM: " + p)+ return 1 if problems else 0+++def cmd_needs(a):+ config = load(a.config)+ needed = sorted({BY_NAME[n][4] for n in config if BY_NAME[n][4]})+ firmware = typed("FIRMWARE", config["FIRMWARE"]) if "FIRMWARE" in config else "device"+ if firmware == "none" and needed:+ print('this configuration says CONFIG_FIRMWARE="none" and still sets options that need firmware: %s' % ", ".join(needed))+ return 1+ missing = 0+ for d in needed:+ path = os.path.join(a.root, d)+ have = os.path.isdir(path) and any(os.scandir(path))+ missing += not have+ print("%-12s %s" % (d + "/", "pulled" if have else "MISSING: devices/<name>/pull-firmware.sh (or pull-firmware-root.sh)"))+ if not needed:+ print("nothing of the phone's own is needed")+ return 1 if missing else 0+++def cmd_savedefconfig(a):+ config = load(a.config)+ base = parse(find_config(a.root, "defconfig"))[0]+ lines = ["# A minimal defconfig: what this configuration sets that configs/defconfig does not, or sets differently."]+ for name, *_ in SYMBOLS:+ if name in config and base.get(name) != config[name]:+ lines.append("CONFIG_%s=%s" % (name, config[name]))+ elif name not in config and name in base:+ lines.append("# CONFIG_%s is not set" % name)+ print("\n".join(lines))+ return 0+++def first_comment(path):+ """The first comment of a file, which says what it is (`# CONFIG_X is not set` is not a comment, it is a setting)."""+ for line in open(path, encoding="utf-8"):+ if line.startswith("#") and not re.fullmatch(r"#\s*CONFIG_[A-Z0-9_]+ is not set\s*", line):+ return line.lstrip("# ").strip()+ return ""+++def cmd_list(a):+ d = config_dir(a.root)+ names = sorted(os.listdir(d)) if os.path.isdir(d) else []+ print("defconfigs (tools/hakios-config.py defconfig NAME, or make NAME_defconfig):")+ for n in names:+ if n == "defconfig" or n.endswith("_defconfig"):+ print(" %-16s %s" % (n[:-len("_defconfig")] if n.endswith("_defconfig") else n, first_comment(os.path.join(d, n))))+ print("fragments (put over a configuration: tools/hakios-config.py merge NAME, or defconfig NAME FRAGMENT):")+ for n in names:+ if n.endswith(".config"):+ print(" %-16s %s" % (n[:-len(".config")], first_comment(os.path.join(d, n))))+ return 0+++def cmd_help(a):+ name = a.symbol.upper()+ name = name[len("CONFIG_"):] if name.startswith("CONFIG_") else name+ if name not in BY_NAME:+ close = difflib.get_close_matches(name, BY_NAME, n=3)+ print("no symbol CONFIG_%s%s" % (name, " (did you mean %s?)" % ", ".join("CONFIG_" + c for c in close) if close else ""))+ return 1+ _n, kind, arg, help_, needs, requires = BY_NAME[name]+ print("CONFIG_%s (%s)" % (name, kind))+ print(" " + help_)+ if arg:+ print(" boot-argument: %s=%s" % (arg, {"bool": "1", "hex": "0x...", "int": "N", "str": "..."}[kind]))+ if needs:+ print(" needs firmware pulled from your phone: %s/" % needs)+ if requires:+ print(" requires: CONFIG_%s" % requires)+ return 0+++def main():+ # --root and --config are accepted before the command and after it+ common = argparse.ArgumentParser(add_help=False)+ common.add_argument("--root", default=argparse.SUPPRESS, help="the top of the repository (tests use another)")+ common.add_argument("--config", default=argparse.SUPPRESS, help="the .config to use (default: .config at the top)")+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[common])+ sub = ap.add_subparsers(dest="command", required=True)+ p = sub.add_parser("defconfig", parents=[common], help="make .config from a defconfig and fragments")+ p.add_argument("name")+ p.add_argument("fragments", nargs="*")+ p.add_argument("-o", "--output")+ p.set_defaults(fn=cmd_defconfig)+ p = sub.add_parser("merge", parents=[common], help="put fragments over the .config")+ p.add_argument("fragments", nargs="+")+ p.set_defaults(fn=cmd_merge)+ p = sub.add_parser("args", parents=[common], help="the kernel's boot-arguments")+ p.add_argument("--force", action="store_true", help="print them even if the check finds a problem")+ p.add_argument("--defconfig", help="the arguments of this defconfig (and --fragment) instead of the .config's")+ p.add_argument("--fragment", action="append", default=[], help="a fragment over it; more than one is allowed")+ p.set_defaults(fn=cmd_args)+ for name, fn, text in (("check", cmd_check, "validate the .config"), ("show", cmd_show, "say what the .config is"),+ ("needs", cmd_needs, "which firmware the .config wants, and whether it is there"),+ ("savedefconfig", cmd_savedefconfig, "the .config as a minimal defconfig"),+ ("list", cmd_list, "the defconfigs and fragments in configs/")):+ sub.add_parser(name, parents=[common], help=text).set_defaults(fn=fn)+ p = sub.add_parser("help", parents=[common], help="what a symbol means")+ p.add_argument("symbol")+ p.set_defaults(fn=cmd_help)+ a = ap.parse_args()+ a.root = os.path.abspath(getattr(a, "root", ROOT))+ a.config = os.path.abspath(getattr(a, "config", os.path.join(a.root, ".config")))+ if getattr(a, "output", None) is None:+ a.output = a.config+ try:+ sys.exit(a.fn(a))+ except ConfigError as e:+ print("hakios-config: %s" % e, file=sys.stderr)+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/tools/modem-cycle-win.sh b/tools/modem-cycle-win.shindex e6d1aa4..60bd280 100644--- a/tools/modem-cycle-win.sh+++ b/tools/modem-cycle-win.sh@@ -9,6 +9,8 @@cd "$(dirname "$0")/.." || exit 1PATH=$PWD/tools/win-bin:/c/platform-tools:$PATHARGS=$1; SECS=${2:-300}+# BASE_ARGS: the arguments the runner puts first (default: the reference phone's cores, clock and storage).+# Empty, as `make phone` sets it when there is a .config, they come from the configuration instead and are not doubled.# A port's SoC addresses (devices/<name>/soc.args, made by devices/<name>/pull-soc.sh): added to the# kernel command line so hakios.mpss.c / hakios.ipa.c map that phone's blocks. SOC_ARGS names the file;# default is the one device there is. The POCO's values equal the kernel defaults, so this is a no-op there.@@ -20,7 +22,7 @@ for i in $(seq 1 2160); do s=$(./xl state); [ "$s" != absent ] && break; sleep 1echo "$(date +%T) phone: $s"; [ "$s" = absent ] && { echo "NO PHONE"; exit 1; }./xl enter 2>&1 | tail -1./xl ramdisk userland/system.apfs 2>&1 | tail -1-XL_SB_DELAY=${XL_SB_DELAY:-600} XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 ufs=2 $ARGS $SOC" XL_SECS=$SECS XL_FOLLOW=1 XL_FOLLOW_KEEP=1 ./xl run 2>&1 | tail -2+XL_SB_DELAY=${XL_SB_DELAY:-600} XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 ${BASE_ARGS-bootcpu=7 cpus=8 cpufreq=1 ufs=2} $ARGS $SOC" XL_SECS=$SECS XL_FOLLOW=1 XL_FOLLOW_KEEP=1 ./xl run 2>&1 | tail -2echo "$(date +%T) state after run: $(./xl state)"L=$(ls -t logs/*-run.log.live | head -1); F=${L%.live}; echo "LOG=$F"cat $L $F 2>/dev/null | grep -a "mpss: \(7: \(THE\|the watch\)\|11\|rmtfs\|tftp\|servreg\|dms\|nas\|ipa: \(THE\|from node\|the modem\|a probe\)\|link: \(THE\|tftp\)\|LAST WORDS\|step 1[01]\)\|serving system\|panic(\|ipa: \|cell: \|net: en1\|wda: \|wds: \(THE\|the client\|about\)" | grep -v "about to ask\|about to tell" | sed 's/^\[ *[0-9.]*\]: //' | awk '!seen[$0]++' | cut -c1-230 | head -80diff --git a/tools/modem-cycle.sh b/tools/modem-cycle.shindex 8e817a0..4bbd5af 100755--- a/tools/modem-cycle.sh+++ b/tools/modem-cycle.sh@@ -6,6 +6,8 @@cd "$(dirname "$0")/.." || exit 1PATH=$PWD/tools/macos-bin/platform-tools:$PWD/tools/macos-bin:$PATHARGS=$1; SECS=${2:-300}+# BASE_ARGS: the arguments the runner puts first (default: the reference phone's cores, clock and storage).+# Empty, as `make phone` sets it when there is a .config, they come from the configuration instead and are not doubled.# A port's SoC addresses (devices/<name>/soc.args, made by devices/<name>/pull-soc.sh): added to the# kernel command line so hakios.mpss.c / hakios.ipa.c map that phone's blocks. SOC_ARGS names the file;# default is the one device there is. The POCO's values equal the kernel defaults, so this is a no-op there.@@ -17,7 +19,7 @@ for i in $(seq 1 2160); do s=$(./xl state); [ "$s" != absent ] && break; sleep 1echo "$(date +%T) phone: $s"; [ "$s" = absent ] && { echo "NO PHONE"; exit 1; }./xl enter 2>&1 | tail -1./xl ramdisk userland/system.apfs 2>&1 | tail -1-XL_SB_DELAY=${XL_SB_DELAY:-600} XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 bootcpu=7 cpus=8 cpufreq=1 ufs=2 $ARGS $SOC" XL_SECS=$SECS XL_FOLLOW=1 XL_FOLLOW_KEEP=1 ./xl run 2>&1 | tail -2+XL_SB_DELAY=${XL_SB_DELAY:-600} XL_CMDLINE="debug=0x8 rd=md0 hv_wdt_pet=1 ${BASE_ARGS-bootcpu=7 cpus=8 cpufreq=1 ufs=2} $ARGS $SOC" XL_SECS=$SECS XL_FOLLOW=1 XL_FOLLOW_KEEP=1 ./xl run 2>&1 | tail -2echo "$(date +%T) state after run: $(./xl state)"L=$(ls -t logs/*-run.log.live | head -1); F=${L%.live}; echo "LOG=$F"cat $L $F 2>/dev/null | grep -a "mpss: \(7: \(THE\|the watch\)\|11\|rmtfs\|tftp\|servreg\|dms\|nas\|ipa: \(THE\|from node\|the modem\|a probe\)\|link: \(THE\|tftp\)\|LAST WORDS\|step 1[01]\)\|serving system\|panic(\|ipa: \|cell: \|net: en1\|wda: \|wds: \(THE\|the client\|about\)" | grep -v "about to ask\|about to tell" | sed 's/^\[ *[0-9.]*\]: //' | awk '!seen[$0]++' | cut -c1-230 | head -80