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
The phone's buttons: a driver that reads them; the system no longer sleeps
vcvkka0db6717f098
diff --git a/tools/buttons-session.sh b/tools/buttons-session.shnew file mode 100755index 0000000..5be07a3--- /dev/null+++ b/tools/buttons-session.sh@@ -0,0 +1,70 @@+#!/bin/bash+# A session for somebody with a hand on the phone's keys: one run of iOS with the buttons' driver+# on (boot-arg buttons=1), in which everything the driver sees and everything iOS makes of it is+# collected, and a summary at the end.+#+# tools/buttons-session.sh [SECONDS] (default 120)+#+# What it does: gets the phone into the loader (uploads the system image if it had to come from+# Android), starts the run, says when to start pressing, follows the log (tools/buttons-watch.sh:+# every press and release as the kernel's driver logs it, backboardd's own "[Button]" lines, a+# picture of the screen after each press), and afterwards fetches the screen recording the run+# made and prints what was seen. Everything goes to logs/buttons-HHMMSS/.+#+# The small image must be one that unlocks by itself (the keys are then tried at the home+# screen): REST=1 ZSTD=1 RC_JOBS=rc.jobs.unlock userland/build.sh+# Environment: XL_CMDLINE_MORE="..." more boot-args (gpu=1, -v, ...); RAMDISK=1 upload the system+# image even if the phone is already in the loader; RECORD=0 no screen recording.+cd "$(dirname "$(readlink -f "$0")")/.." || exit 1+PHONE=${XDG_RUNTIME_DIR:-/tmp}/darwin-redwood-phone+secs=${1:-120}+out=logs/buttons-$(date +%H%M%S)+mkdir -p "$out"++flock -n "$PHONE.run" true 2>/dev/null || { echo "buttons-session.sh: a run is in progress (started from $(cat "$PHONE.who" 2>/dev/null)): not now"; exit 1; }+grep -q swipe userland/root/etc/rc.jobs 2>/dev/null ||+ echo "buttons-session.sh: note: the small image was not built with RC_JOBS=rc.jobs.unlock: nothing will swipe the lock screen away"+before=$(./xl state)+echo "buttons-session.sh: the phone is in: $before"+./xl enter || exit 1+if [ "$before" != loader ] || [ -n "$RAMDISK" ]; then+ echo "buttons-session.sh: uploading the system image (about 70 s)"+ ./xl ramdisk || exit 1+fi++record="rec_start=30 rec_secs=$((secs - 45)) rec_mb=640"+[ "$RECORD" = 0 ] && record=+export XL_SECS=$secs+XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4 buttons=1 $record $XL_CMDLINE_MORE" ./xl run > "$out/run.out" 2>&1 &+echo+echo "=== $(date +%T): the run has started; it lasts $secs seconds."+echo "=== In about 20 s the lock screen appears, at about 35 s it is swiped away by a script."+echo "=== FROM THE MOMENT THE HOME SCREEN (the icons) IS THERE the keys can be pressed."+echo+sleep 2+tools/buttons-watch.sh "$out" | grep --line-buffered -v -E '^buttons: (step [1-4]|next:|channel|PMIC arbiter|the PMK8350|GPIO6 of)'+wait+cat "$out/run.out"+log=$(sed -n 's/.*\[\(logs\/[^]]*\)\].*/\1/p' "$out/run.out" | tail -1)+[ -f "$log" ] || { echo "buttons-session.sh: the run left no log"; exit 1; }+cp "$log" "$out/run.log"++if [ -n "$record" ] && ./xl recording "$out/recording.mp4" >/dev/null 2>&1; then+ echo "screen recording: $out/recording.mp4"+fi++echo+echo "=== what the driver saw (the kernel's log, $out/run.log) ==="+grep -a -E '^buttons: (power-on block|volume up.s pin|step 5|.*(PRESSED|released at)|so far|reading|a key reads|more than half)' "$out/run.log" | cut -c1-230+echo+echo "=== what iOS's event system made of it (backboardd) ==="+grep -a -E '\[Button\] [A-Za-z]+ page|Set Blanked' "$out/run.log" | sed -E 's/^[0-9-]+ //; s/\+0[0-9]+ backboardd\[[0-9:]+\]//' | cut -c1-120+echo+for key in power "volume up" "volume down"; do+ printf '%-12s %s presses, %s releases seen by the driver\n' "$key:" \+ "$(grep -a -c "^buttons: $key PRESSED" "$out/run.log")" "$(grep -a -c "^buttons: $key released at" "$out/run.log")"+done+printf 'backboardd: %s lock, %s volume-up, %s volume-down button events (a press and a release are two)\n' \+ "$(grep -a -c '\[Button\] Lock page' "$out/run.log")" "$(grep -a -c '\[Button\] VolumeIncrement page' "$out/run.log")" \+ "$(grep -a -c '\[Button\] VolumeDecrement page' "$out/run.log")"+echo "pictures taken after presses: $(ls "$out"/*.png 2>/dev/null | wc -l) in $out"diff --git a/tools/buttons-watch.sh b/tools/buttons-watch.shnew file mode 100755index 0000000..e1030e7--- /dev/null+++ b/tools/buttons-watch.sh@@ -0,0 +1,59 @@+#!/bin/bash+# While a run is in progress on the phone: follow what the kernel's log says about the buttons+# (the driver's "buttons:" lines, backboardd's "[Button]" lines, button presses a script makes+# with rwtouch), print each new line, and take pictures of the screen after every press -- one at+# once and one two seconds later -- so that a session in which somebody presses the phone's keys+# also shows what iOS made of them (a volume key: the volume indicator; the side button: the+# screen off, or back on).+#+# usage: XL_SECS=N tools/buttons-watch.sh [DIR] (N as for the run; pictures go to DIR, default+# logs/buttons-HHMMSS)+# Start the run first (./xl run in another terminal, or in the background); this ends with it.+# In the last seconds of the run it leaves the phone alone: what "xl log" and "xl screenshot" ask+# the loader for travels the same way as the run's own log, and must not be in its place when+# the run fetches that.+cd "$(dirname "$(readlink -f "$0")")/.." || exit 1+PHONE=${XDG_RUNTIME_DIR:-/tmp}/darwin-redwood-phone+out=${1:-logs/buttons-$(date +%H%M%S)}+mkdir -p "$out"+pattern='^buttons: |\[Button\] [A-Za-z]+ page|^\$ /redwood/bin/rwtouch .*button |Set Blanked'+press='PRESSED|rwtouch .*button '+shots=0 started= again=0 last=+running() { ! flock -n "$PHONE.run" true 2>/dev/null; }+picture() { # picture <suffix>+ local file+ file="$out/$(printf '%02d' $shots)-$name$1.png"+ ./xl screenshot "$file" >/dev/null 2>&1 && echo " (picture $(date +%T): $file)"+}+for ((i = 0; i < 20; i++)); do # wait for the run to start+ running && { started=$(stat -c %Y "$PHONE.run"); break; }+ sleep 0.5+done+[ -n "$started" ] || { echo "buttons-watch.sh: no run in progress"; exit 1; }+quiet=$((started + ${XL_SECS:-8} - 4))+while running; do+ if [ "$(date +%s)" -ge "$quiet" ]; then sleep 1; continue; fi+ ./xl log > "$out/log.now" 2>/dev/null || { sleep 1; continue; }+ # what is new: the lines after the last one already shown (the log is a ring: lines do not keep their numbers)+ new=$(grep -a -E "$pattern" "$out/log.now" | awk -v last="$last" '+ { line[NR] = $0; if ($0 == last) at = NR }+ END { if (last != "" && !at) at = NR - 1; # (it has left the ring: go on from the newest)+ for (i = at + 1; i <= NR; i++) print line[i] }')+ if [ -n "$new" ]; then+ last=$(printf '%s\n' "$new" | tail -1)+ printf '%s\n' "$new" | cut -c1-180+ if printf '%s\n' "$new" | grep -q -E "$press"; then+ shots=$((shots + 1))+ name=$(printf '%s\n' "$new" | grep -E "$press" | tail -1 |+ sed -E 's/^buttons: (.*) PRESSED.*/\1/; s/^.*button ([a-z]+).*/script-\1/; s/ /-/g')+ picture ""+ again=$(( $(date +%s) + 2 ))+ fi+ fi+ if [ "$again" != 0 ] && [ "$(date +%s)" -ge "$again" ]; then+ again=0+ picture "-later"+ fi+ sleep 0.2+done+echo "buttons-watch.sh: the run is over; pictures in $out, the whole log in logs/last.log"diff --git a/userland/rc.jobs.buttons b/userland/rc.jobs.buttonsnew file mode 100644index 0000000..accd4f8--- /dev/null+++ b/userland/rc.jobs.buttons@@ -0,0 +1,13 @@+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).+# The buttons, pressed by a script (RC_JOBS=rc.jobs.buttons): button records written to+# /dev/redwood-touch, which is where a driver's presses go too. Unlock, volume up, volume down,+# the side button to turn the screen off, the side button to wake it, unlock again.+# tools/buttons-watch.sh, run on the host meanwhile, takes a picture of the screen after each press.+/redwood/bin/rwtouch wait 32 swipe 0.5 0.985 0.5 0.3 250 wait 6+/redwood/bin/rwtouch button volup 80 wait 4+/redwood/bin/rwtouch button voldown 80 wait 4+/redwood/bin/rwtouch button lock 80 wait 8+/redwood/bin/rwtouch button lock 80 wait 6+/redwood/bin/rwtouch swipe 0.5 0.985 0.5 0.3 250 wait 4+/redwood/bin/rwtouch button lock 80 wait 20+/redwood/bin/rwtouch tap 0.5 0.5 wait 5diff --git a/xnu/files/bsd/dev/redwood_buttons.c b/xnu/files/bsd/dev/redwood_buttons.cnew file mode 100644index 0000000..b8ead23--- /dev/null+++ b/xnu/files/bsd/dev/redwood_buttons.c@@ -0,0 +1,551 @@+/*+ * The buttons of the POCO X5 Pro (redwood) -- power, volume up, volume down -- as a source of+ * button records for /dev/redwood-touch (sys/redwood_input.h). Only with boot-arg buttons=1:+ * every address below belongs to this phone.+ *+ * None of the three is a pin of the SoC. They are inputs of two of the power management chips:+ * power KPDPWR_N of the power-on block ("PON") of the PMK8350+ * volume down RESIN_N of the same block+ * volume up GPIO6 of the PM7325, pulled up; the key pulls it low+ * Both chips sit on the SPMI bus (slaves 0 and 1), and the way to that bus is the SoC's "PMIC+ * arbiter": it owns the bus and gives each of the systems on the chip (this one, the modem, the+ * always-on processor, TrustZone...) a set of registers per PMIC peripheral -- a "channel" -- to+ * ask for a transfer with. Reads go through the "observer" channels, which every system has for+ * every peripheral, whoever owns it.+ *+ * THIS DRIVER ONLY READS. Nothing is written to either chip, neither a register of a PMIC nor+ * the configuration of the pin: the PMICs make the phone's supplies, and a wrong write there+ * can switch one off. The firmware reads the same keys itself (volume down and volume up choose+ * between fastboot and recovery) and has left both inputs as they are needed; the driver checks+ * that before it believes them, and where it finds something else it says so and leaves that+ * key alone. The only thing written is the command word that asks the arbiter for a read.+ *+ * What a press is: the PON's "real time status" has a bit per key, set while the key is held+ * (after the block's own debouncing); the GPIO's has the level of the pin. A thread reads the+ * two registers 60 times a second, and a key has changed when two looks in a row say so. A key+ * that reads as held before it has ever been seen released is not believed (a pin that is not+ * what it was taken for must not become a volume key held down for the whole session).+ * No interrupt is used; what one would take is said at the end of this file.+ *+ * The mapping: the phone has what the iPhone X has, whose user space runs here -- a side button+ * and two volume keys, no home button. Power is the side button (REDWOOD_BUTTON_LOCK).+ *+ * The bring-up is made in steps, each said in the log before it is made. Boot-arg+ * buttons_steps=N stops after the first N:+ * 1 map the arbiter and read its version (the first access to that block)+ * 2 find the channels of the two peripherals (reads of the arbiter's tables)+ * 3 ask each peripheral what it is (the first transfers on the bus)+ * 4 read how the keys' inputs are set up, and what they say now+ * 5 watch them (the default)+ *+ * Register layouts: Linux drivers/spmi/spmi-pmic-arb.c (arbiter version 5),+ * drivers/input/misc/pm8941-pwrkey.c (the "pmk8350" kind), drivers/pinctrl/qcom/pinctrl-spmi-gpio.c,+ * and the phone's own device tree (qcom,spmi@c440000, pon_hlos@1300, gpio_keys).+ */+#include <kern/clock.h>+#include <kern/thread.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <pexpert/pexpert.h>+#include <sys/redwood_input.h>+#include <sys/systm.h>++extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);+extern kern_return_t thread_terminate(thread_t thread);++/*+ * Every line goes to the loader's log directly as well: without -v the kernel's own messages+ * reach that log only at the end of a run (with the kernel's message buffer), and "xl log"+ * during a run is to show a press when it happens.+ */+extern void loader_log_putc(char c);++static int say(const char *format, ...) __printflike(1, 2);++static int+say(const char *format, ...)+{+ char line[400];+ va_list list;++ va_start(list, format);+ vsnprintf(line, sizeof(line), format, list);+ va_end(list);+ for (const char *c = line; *c != 0; c++) {+ loader_log_putc(*c);+ }+ return printf("%s", line);+}+#define printf say++static inline uint32_t+rd(vm_offset_t address)+{+ return *(volatile uint32_t *)address;+}++static inline void+wr(vm_offset_t address, uint32_t value)+{+ *(volatile uint32_t *)address = value;+}++/* ---- the PMIC arbiter ---------------------------------------------------------------------------- */++#define ARB_CORE_PHYS 0x0c440000UL /* "core": the version, and which peripheral each channel is */+#define ARB_CORE_SIZE 0x1100UL+#define ARB_CNFG_PHYS 0x0c40a000UL /* "cnfg": which system owns each channel */+#define ARB_CNFG_SIZE 0x1000UL+#define ARB_OBSERVER_PHYS 0x0e600000UL /* "obsrvr": 0x10000 per system, 0x80 per channel in it */+#define ARB_OBSERVER_SIZE 0x10000UL /* ours is the first */+#define ARB_SYSTEM 0 /* who we are to the arbiter: the device tree's "qcom,ee" */++#define ARB_VERSION 0x000+#define ARB_VERSION_5 0x50000000u /* what follows is version 5's; 7 moved things again */+#define ARB_VERSION_7 0x70000000u+#define ARB_FEATURES 0x004 /* [10:0] the number of channels */+#define ARB_CHANNEL(n) (0x900 + 4 * (n)) /* core: [19:8] slave and peripheral, [24] interrupts go to the owner */+#define ARB_CHANNEL_INTERRUPTS (1u << 24)+#define ARB_OWNER(n) (0x700 + 4 * (n)) /* cnfg: [2:0] the system that may write through channel n */+#define ARB_MAX_CHANNELS 512++#define OBSERVER_COMMAND 0x00+#define OBSERVER_STATUS 0x08+#define OBSERVER_DATA0 0x18 /* the bytes read, the first in the lowest byte */+#define OBSERVER_DATA1 0x1c+#define STATUS_DONE 0x1+#define STATUS_FAILURE 0x2+#define STATUS_DENIED 0x4+#define STATUS_DROPPED 0x8+#define COMMAND_READ (1u << 27) /* "extended register read long"; [11:4] register, [2:0] bytes - 1 */+#define READ_TIMEOUT_US 2000 /* a read takes some tens of microseconds */++static vm_offset_t arb_core, arb_cnfg, arb_observer;++struct peripheral {+ const char * name;+ uint16_t id; /* slave << 8 | peripheral: the high byte of its register addresses */+ uint16_t channel;+ bool found;+};+static struct peripheral pon = { .name = "the PMK8350's power-on block", .id = 0x013 }; /* registers 0x1300 of slave 0 */+static struct peripheral pin = { .name = "GPIO6 of the PM7325", .id = 0x18d }; /* registers 0x8d00 of slave 1 */++/* How the reads have gone: said once a minute. */+static struct {+ uint64_t reads, failed, total_ns, longest_ns, last_ns;+} bus;++/*+ * Read `count` (1 to 8) registers of a peripheral, from register `reg` on. Returns NULL, or what+ * went wrong.+ */+static const char *+spmi_read(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t count)+{+ vm_offset_t channel = arb_observer + 0x10000UL * ARB_SYSTEM + 0x80UL * p->channel;+ uint64_t start = mach_absolute_time(), now, interval, taken;+ uint32_t status, data[2];+ const char *problem = NULL;++ nanoseconds_to_absolutetime(READ_TIMEOUT_US * (uint64_t)NSEC_PER_USEC, &interval);+ wr(channel + OBSERVER_COMMAND, COMMAND_READ | (uint32_t)reg << 4 | (count - 1));+ do {+ status = rd(channel + OBSERVER_STATUS);+ now = mach_absolute_time();+ } while (!(status & STATUS_DONE) && now - start < interval);++ if (!(status & STATUS_DONE)) {+ problem = "no answer from the arbiter";+ } else if (status & STATUS_DENIED) {+ problem = "the arbiter refuses";+ } else if (status & STATUS_FAILURE) {+ problem = "the transfer failed (nobody at that address?)";+ } else if (status & STATUS_DROPPED) {+ problem = "the transfer was dropped";+ } else {+ data[0] = rd(channel + OBSERVER_DATA0);+ data[1] = count > 4 ? rd(channel + OBSERVER_DATA1) : 0;+ for (uint32_t i = 0; i < count; i++) {+ bytes[i] = (uint8_t)(data[i / 4] >> (8 * (i % 4)));+ }+ }+ absolutetime_to_nanoseconds(now - start, &taken);+ bus.reads++;+ bus.total_ns += taken;+ bus.last_ns = taken;+ if (taken > bus.longest_ns) {+ bus.longest_ns = taken;+ }+ if (problem != NULL) {+ bus.failed++;+ }+ return problem;+}++/*+ * Which channel is that peripheral's. Several can be: one per system that may write to it. As+ * Linux chooses: the first, unless a later one is ours to write through.+ */+static void+find_channel(struct peripheral *p, uint32_t channels)+{+ for (uint32_t n = 0; n < channels; n++) {+ uint32_t map = rd(arb_core + ARB_CHANNEL(n)), owner;++ if (map == 0 || ((map >> 8) & 0xfff) != p->id) {+ continue;+ }+ owner = rd(arb_cnfg + ARB_OWNER(n)) & 7;+ printf("buttons: channel %u is %s (%#x); written by system %u%s\n", n, p->name, map, owner,+ (map & ARB_CHANNEL_INTERRUPTS) ? ", which also gets its interrupts" : "");+ if (!p->found || owner == ARB_SYSTEM) {+ p->found = true;+ p->channel = (uint16_t)n;+ }+ }+ if (!p->found) {+ printf("buttons: no channel of the arbiter is %s (slave %u, peripheral %#x)\n", p->name, p->id >> 8, p->id & 0xff);+ }+}++/* ---- the two peripherals ------------------------------------------------------------------------- */++/* every peripheral of these PMICs */+#define REG_TYPE 0x04+#define REG_SUBTYPE 0x05+#define REG_RT_STATUS 0x10 /* the inputs as they are now */+#define REG_INT_SET_TYPE 0x11 /* interrupts: a bit per input in each of these */+#define REG_INT_POLARITY_HIGH 0x12+#define REG_INT_POLARITY_LOW 0x13+#define REG_INT_ENABLED 0x15+#define REG_INT_LATCHED 0x18+#define REG_INT_PENDING 0x19++/* the power-on block, of the kind that is split in two ("generation 3"): this is its half for the operating system */+#define PON_TYPE 0x01+#define PON_SUBTYPE_HLOS 0x09+#define PON_KPDPWR 0x80 /* in the status and in the interrupt registers */+#define PON_RESIN 0x40++/* a GPIO of the low or medium voltage kind */+#define GPIO_TYPE 0x10+#define GPIO_SUBTYPE_LV 0x10+#define GPIO_SUBTYPE_MV_VIN3 0x13 /* 0x10 to 0x13: one layout */+#define GPIO_LEVEL 0x01 /* in the status */+#define GPIO_REG_MODE 0x40 /* [1:0]: 0 input, 1 output, 2 both, 3 analog */+#define GPIO_REG_SUPPLY 0x41+#define GPIO_REG_PULL 0x42 /* [2:0]: 0 to 3 up (30, 1.5, 31.5 uA, 1.5 with a boost), 4 down, 5 none */+#define GPIO_REG_ENABLE 0x46 /* [7] */++#define POLL_MS 16+#define MINUTE_TICKS (60 * 1000 / POLL_MS)++static struct button {+ const char * name;+ uint32_t record; /* REDWOOD_BUTTON_* */+ bool usable; /* its input is what it was taken for */+ bool live; /* it has been seen released */+ bool last; /* the look before this one */+ bool down; /* as reported */+ uint64_t since; /* when it went down */+ uint32_t presses;+} power = { .name = "power", .record = REDWOOD_BUTTON_LOCK },+ volume_up = { .name = "volume up", .record = REDWOOD_BUTTON_VOLUME_UP },+ volume_down = { .name = "volume down", .record = REDWOOD_BUTTON_VOLUME_DOWN };++/* "12.345 s (08:13:05.918 UTC)": since boot as in the log's own stamps, and as the daemons' lines have it */+static void+now_text(char *text, size_t size, uint64_t now)+{+ clock_sec_t seconds;+ clock_usec_t micro;+ uint64_t up;++ absolutetime_to_nanoseconds(now, &up);+ clock_get_calendar_microtime(&seconds, µ);+ snprintf(text, size, "%llu.%03llu s (%02u:%02u:%02u.%03u UTC)", up / NSEC_PER_SEC, up / NSEC_PER_MSEC % 1000,+ (unsigned)(seconds / 3600 % 24), (unsigned)(seconds / 60 % 60), (unsigned)(seconds % 60), (unsigned)(micro / 1000));+}++static void+button_look(struct button *b, bool pressed)+{+ uint64_t now = mach_absolute_time(), held;+ bool steady = pressed == b->last;+ char when[64];++ b->last = pressed;+ if (!b->usable || !steady) {+ return;+ }+ if (!b->live) {+ if (!pressed) {+ b->live = true;+ printf("buttons: %s is released now: believed from here on\n", b->name);+ }+ return;+ }+ if (pressed == b->down) {+ return;+ }+ b->down = pressed;+ now_text(when, sizeof(when), now);+ if (pressed) {+ b->since = now;+ b->presses++;+ printf("buttons: %s PRESSED at %s\n", b->name, when);+ } else {+ absolutetime_to_nanoseconds(now - b->since, &held);+ printf("buttons: %s released at %s, after %llu ms\n", b->name, when, held / NSEC_PER_MSEC);+ }+ redwood_touch_post(pressed ? REDWOOD_BUTTON_DOWN : REDWOOD_BUTTON_UP, b->record, 0, 0);+}++/* One look at both peripherals. */+static void+buttons_poll(void)+{+ static unsigned said;+ const char *problem;+ uint8_t status;++ if (power.usable || volume_down.usable) {+ problem = spmi_read(&pon, REG_RT_STATUS, &status, 1);+ if (problem == NULL) {+ button_look(&power, status & PON_KPDPWR);+ button_look(&volume_down, status & PON_RESIN);+ } else if (said < 8) {+ said++;+ printf("buttons: reading %s: %s\n", pon.name, problem);+ }+ }+ if (volume_up.usable) {+ problem = spmi_read(&pin, REG_RT_STATUS, &status, 1);+ if (problem == NULL) {+ button_look(&volume_up, !(status & GPIO_LEVEL));+ } else if (said < 8) {+ said++;+ printf("buttons: reading %s: %s\n", pin.name, problem);+ }+ }+}++/* Step 3: is each peripheral what the registers above are those of? */+static bool+identify(const struct peripheral *p, uint8_t type, uint8_t subtype_from, uint8_t subtype_to)+{+ const char *problem;+ uint8_t is[2];++ if (!p->found) {+ return false;+ }+ printf("buttons: next: read the type of %s through channel %u (2 registers, 0x%02x04)\n", p->name, p->channel, p->id & 0xff);+ problem = spmi_read(p, REG_TYPE, is, 2);+ if (problem != NULL) {+ printf("buttons: %s: %s\n", p->name, problem);+ return false;+ }+ printf("buttons: %s says type %#x, subtype %#x (the read took %llu us)\n", p->name, is[0], is[1], bus.last_ns / 1000);+ if (is[0] != type || is[1] < subtype_from || is[1] > subtype_to) {+ printf("buttons: ... which is not what this driver knows (type %#x, subtype %#x to %#x): left alone\n", type,+ subtype_from, subtype_to);+ return false;+ }+ return true;+}++/* Step 4 for the power-on block: nothing to check but what it says now; its interrupt setup goes to the log. */+static void+pon_inputs(void)+{+ const char *problem;+ uint8_t r[8], more[2];++ printf("buttons: next: read the status and the interrupt setup of %s (registers 0x1310 to 0x1319)\n", pon.name);+ problem = spmi_read(&pon, REG_RT_STATUS, r, 8);+ if (problem == NULL) {+ problem = spmi_read(&pon, REG_INT_LATCHED, more, 2);+ }+ if (problem != NULL) {+ printf("buttons: %s: %s\n", pon.name, problem);+ return;+ }+ printf("buttons: power-on block: status %#x (power %s, volume down %s); interrupts: edge %#x, high %#x, low %#x, "+ "enabled %#x, latched %#x, pending %#x\n", r[0], (r[0] & PON_KPDPWR) ? "HELD" : "released",+ (r[0] & PON_RESIN) ? "HELD" : "released", r[REG_INT_SET_TYPE - REG_RT_STATUS], r[REG_INT_POLARITY_HIGH - REG_RT_STATUS],+ r[REG_INT_POLARITY_LOW - REG_RT_STATUS], r[REG_INT_ENABLED - REG_RT_STATUS], more[0], more[1]);+ power.usable = volume_down.usable = true;+ power.last = r[0] & PON_KPDPWR;+ volume_down.last = r[0] & PON_RESIN;+}++/* Step 4 for the pin: it is volume up only if it is an input with a pull-up, and switched on. */+static void+pin_input(void)+{+ const char *problem;+ uint8_t c[8], status = 0;+ unsigned mode, pull;++ printf("buttons: next: read the setup and the level of %s (registers 0x8d40 to 0x8d47, 0x8d10)\n", pin.name);+ problem = spmi_read(&pin, GPIO_REG_MODE, c, 8);+ if (problem == NULL) {+ problem = spmi_read(&pin, REG_RT_STATUS, &status, 1);+ }+ if (problem != NULL) {+ printf("buttons: %s: %s\n", pin.name, problem);+ return;+ }+ mode = c[0] & 3;+ pull = c[GPIO_REG_PULL - GPIO_REG_MODE] & 7;+ printf("buttons: volume up's pin: mode %u (%s), supply %u, pull %u (%s), %s; registers 0x40.. = %02x %02x %02x %02x %02x %02x "+ "%02x %02x; level %s\n", mode, mode == 0 ? "input" : mode == 1 ? "output" : mode == 2 ? "input and output" : "analog",+ c[GPIO_REG_SUPPLY - GPIO_REG_MODE] & 7, pull, pull < 4 ? "up" : pull == 4 ? "down" : "none",+ (c[GPIO_REG_ENABLE - GPIO_REG_MODE] & 0x80) ? "enabled" : "DISABLED", c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7],+ (status & GPIO_LEVEL) ? "high (released)" : "LOW (held)");+ if (mode != 0 || pull >= 4 || !(c[GPIO_REG_ENABLE - GPIO_REG_MODE] & 0x80)) {+ printf("buttons: volume up's pin is not an enabled input with a pull-up. Making it one is a write to the PMIC, "+ "which this driver does not do: volume up is left alone\n");+ return;+ }+ volume_up.usable = true;+ volume_up.last = !(status & GPIO_LEVEL);+}++static void+say_summary(void)+{+ printf("buttons: so far %u presses of power, %u of volume up, %u of volume down; now%s%s%s%s; %llu reads of the bus, "+ "%llu us each (the longest %llu), %llu failed\n", power.presses, volume_up.presses, volume_down.presses,+ power.down ? " power" : "", volume_up.down ? " volume-up" : "", volume_down.down ? " volume-down" : "",+ (power.down || volume_up.down || volume_down.down) ? " held" : " none held", bus.reads,+ bus.reads ? bus.total_ns / bus.reads / 1000 : 0, bus.longest_ns / 1000, bus.failed);+}++static void+buttons_thread(void *parameter, __unused wait_result_t result)+{+ uint32_t steps = (uint32_t)(uintptr_t)parameter, version, channels;+ bool pon_known, pin_known;++ printf("buttons: step 1: map the PMIC arbiter (%#lx, %#lx, %#lx) and read its version\n", ARB_CORE_PHYS, ARB_CNFG_PHYS,+ ARB_OBSERVER_PHYS);+ arb_core = ml_io_map(ARB_CORE_PHYS, ARB_CORE_SIZE);+ arb_cnfg = ml_io_map(ARB_CNFG_PHYS, ARB_CNFG_SIZE);+ arb_observer = ml_io_map(ARB_OBSERVER_PHYS, ARB_OBSERVER_SIZE);+ version = rd(arb_core + ARB_VERSION);+ channels = rd(arb_core + ARB_FEATURES) & 0x7ff;+ printf("buttons: PMIC arbiter version %#x, %u channels\n", version, channels);+ if (version < ARB_VERSION_5 || version >= ARB_VERSION_7) {+ printf("buttons: this driver knows version 5 of the arbiter only: no buttons\n");+ goto out;+ }+ if (channels == 0 || channels > ARB_MAX_CHANNELS) {+ channels = ARB_MAX_CHANNELS;+ }+ if (steps < 2) {+ goto out;+ }++ printf("buttons: step 2: look through the arbiter's table for the channels of the two peripherals\n");+ find_channel(&pon, channels);+ find_channel(&pin, channels);+ if (steps < 3) {+ goto out;+ }++ printf("buttons: step 3: the first transfers on the SPMI bus\n");+ pon_known = identify(&pon, PON_TYPE, PON_SUBTYPE_HLOS, PON_SUBTYPE_HLOS);+ pin_known = identify(&pin, GPIO_TYPE, GPIO_SUBTYPE_LV, GPIO_SUBTYPE_MV_VIN3);+ if (steps < 4) {+ goto out;+ }++ printf("buttons: step 4: how the keys' inputs are set up\n");+ if (pon_known) {+ pon_inputs();+ }+ if (pin_known) {+ pin_input();+ }+ if (!power.usable && !volume_up.usable) {+ printf("buttons: nothing that can be read: no buttons\n");+ goto out;+ }+ if (power.last || volume_down.last || volume_up.last) {+ printf("buttons: a key reads as held before anything was watched:%s%s%s. It is not reported until it has been "+ "seen released\n", power.last ? " power" : "", volume_up.last ? " volume-up" : "",+ volume_down.last ? " volume-down" : "");+ }+ /* (a key that is released now is believed at once) */+ power.live = power.usable && !power.last;+ volume_down.live = volume_down.usable && !volume_down.last;+ volume_up.live = volume_up.usable && !volume_up.last;+ if (steps < 5) {+ goto out;+ }++ printf("buttons: step 5: watching%s%s%s, every %u ms: power is the side button\n", power.usable ? " power" : "",+ volume_up.usable ? " volume-up" : "", volume_down.usable ? " volume-down" : "", POLL_MS);+ for (unsigned tick = 1;; tick++) {+ buttons_poll();+ /* once early on as well: a short run is to say what the reads cost too */+ if (tick % MINUTE_TICKS == 0 || tick == 10 * 1000 / POLL_MS) {+ say_summary();+ }+ if (bus.failed >= 1000 && bus.failed * 2 > bus.reads) {+ printf("buttons: more than half of %llu reads have failed: giving up\n", bus.reads);+ break;+ }+ delay_for_interval(POLL_MS, NSEC_PER_MSEC);+ }+out:+ if (steps < 5) {+ printf("buttons: stopping here (buttons_steps=%u)\n", steps);+ }+ thread_terminate(current_thread());+}++void+redwood_buttons_init(void)+{+ uint32_t enabled = 0, steps = 5;+ thread_t thread;++ if (!PE_parse_boot_argn("buttons", &enabled, sizeof(enabled)) || !enabled) {+ return;+ }+ PE_parse_boot_argn("buttons_steps", &steps, sizeof(steps));+ if (steps == 0) {+ return;+ }+ if (kernel_thread_start(buttons_thread, (void *)(uintptr_t)steps, &thread) == KERN_SUCCESS) {+ thread_deallocate(thread);+ }+}++/*+ * What interrupts would take, instead of looking 60 times a second:+ *+ * - The arbiter has one interrupt line for all the PMICs' peripherals ("periph_irq": through the+ * power domain controller's pin 1 to the interrupt controller's SPI 481). This kernel has no+ * driver that takes a hardware interrupt other than the timer's so far; that is the first+ * thing to add (a handler registered for one more interrupt of the GICv3 the kernel already+ * drives, and that line unmasked and set to level, high).+ * - Per channel, the arbiter has an enable bit ("ACC_ENABLE"), a status and a clear register+ * (in the "chnls" region: 0x100, 0x104, 0x108 of 0x10000 per channel), and per system a+ * summary of which channels have something. Those are writes to the arbiter, not to a PMIC.+ * - But the peripheral must be told to raise them as well: for each key a bit in "interrupt+ * type" (edge), "polarity high" and "polarity low" (both edges), and "enable set". Those are+ * WRITES TO THE PMIC -- to the power-on block for power and volume down, to the GPIO for+ * volume up -- unless the firmware has left them set; step 4 prints what it finds there.+ * After an interrupt the peripheral's latched status is cleared by another write to it.+ * - Only the system that owns a peripheral's channel gets its interrupts (step 2 prints the+ * owners).+ * Looking costs two reads of some tens of microseconds each, 60 times a second (the minute's+ * summary line says what they really take), so the reason to want interrupts would not be+ * processor time; it would be a system that sleeps and is to be woken by a key, and this one+ * does not sleep.+ */diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.cindex 69d5f75..f496be6 100644--- a/xnu/files/bsd/dev/redwood_input.c+++ b/xnu/files/bsd/dev/redwood_input.c@@ -170,5 +170,6 @@ redwood_input_init(void)redwood_cpufreq_init();redwood_virtio_input_init();redwood_goodix_init();+ redwood_buttons_init();redwood_adreno_init();}diff --git a/xnu/files/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.hindex e1babac..01f7cef 100644--- a/xnu/files/bsd/sys/redwood_input.h+++ b/xnu/files/bsd/sys/redwood_input.h@@ -41,6 +41,7 @@ void redwood_touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y);void redwood_input_init(void);void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virtio pointer and keyboard */void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's touch screen */+void redwood_buttons_init(void); /* boot-arg buttons=1: the phone's power and volume keys */void redwood_cpufreq_init(void); /* boot-arg cpufreq=1: the phone's processor at full speed */void redwood_adreno_init(void); /* boot-arg adreno=N: the first N steps of waking the phone's GPU */void redwood_adreno_quiesce(void); /* on the way back to the loader: the GPU block stopped, out of our memory */diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex d6a8036..07893ee 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -46,22 +46,23 @@ index 222158a93918..68bb0f3e56bf 100755####################################################################### HISTORYdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..a4cebd7e7561 100644+index 44274016a4cf..6cf54551f728 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,11 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,12 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic+bsd/dev/redwood_input.c standard+bsd/dev/redwood_virtio_input.c standard+bsd/dev/redwood_goodix.c standard++bsd/dev/redwood_buttons.c standard+bsd/dev/redwood_cpufreq.c standard+bsd/dev/redwood_adreno.c standardbsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +160,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +161,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfsbsd/miscfs/mockfs/mockfs_fsnode.c optional mockfsbsd/miscfs/mockfs/mockfs_vfsops.c optional mockfsbsd/miscfs/mockfs/mockfs_vnops.c optional mockfs@@ -72,7 +73,7 @@ index 44274016a4cf..a4cebd7e7561 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +370,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +371,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -80,7 +81,7 @@ index 44274016a4cf..a4cebd7e7561 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +393,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +394,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standard@@ -1170,6 +1171,42 @@ index 1ed75eea2052..551cfb9d5126 100644# MACH_BASE = [ mach config_ecc_logging vc_progress_white importance_inheritance config_atm config_coalitions config_iosched config_library_validation config_sysdiagnose config_telemetry config_mach_bridge_recv_time config_quiesce_counter config_service_port_info ]# MACH_RELEASE = [ MACH_BASE config_skip_precise_user_kernel_time debugger_for_zone_info ]# MACH_DEV = [ MACH_BASE config_io_accounting importance_trace ]+diff --git a/iokit/Kernel/IOPMrootDomain.cpp b/iokit/Kernel/IOPMrootDomain.cpp+index 4a06407aea5f..69a4bcf1839d 100644+--- a/iokit/Kernel/IOPMrootDomain.cpp++++ b/iokit/Kernel/IOPMrootDomain.cpp+@@ -555,7 +555,16 @@ static uint32_t gDarkWakeFlags = kDarkWakeFlagPromotionEarly;+ #endif /* !defined(XNU_TARGET_OS_OSX) */++ static uint32_t gNoIdleFlag = 0;+-static uint32_t gSleepDisabledFlag = 0;++/*++ * redwood: the system does not sleep. There is nothing here to sleep into and nothing that would++ * wake it: with the screen locked, powerd asks for system sleep within seconds, and that request++ * ended in IOCPUSleepKernel() -- with one processor it came straight back out, again and again++ * (every time a round of sleep and wake notifications to all the system); with more than one it++ * stopped there for good, waiting for a processor to go that never goes. Refused instead, the++ * system stays awake with its display off, and the side button or a tap wakes the screen.++ * Boot-arg syssleep=1 gives the old behaviour back.++ */++static uint32_t gSleepDisabledFlag = 1;+ static uint32_t gSwdPanic = 1;+ static uint32_t gSwdSleepTimeout = 0;+ static uint32_t gSwdWakeTimeout = 0;+@@ -1587,6 +1596,13 @@ IOPMrootDomain::start( IOService * nub )+ #endif /* DEVELOPMENT || DEBUG */++ PE_parse_boot_argn("noidle", &gNoIdleFlag, sizeof(gNoIdleFlag));++ {++ uint32_t syssleep = 0;++++ if (PE_parse_boot_argn("syssleep", &syssleep, sizeof(syssleep)) && syssleep) {++ gSleepDisabledFlag = 0;++ }++ }+ PE_parse_boot_argn("swd_sleeptimeout", &gSwdSleepTimeout, sizeof(gSwdSleepTimeout));+ PE_parse_boot_argn("swd_waketimeout", &gSwdWakeTimeout, sizeof(gSwdWakeTimeout));+ PE_parse_boot_argn("swd_timeout", &gSwdSleepWakeTimeout, sizeof(gSwdSleepWakeTimeout));diff --git a/iokit/Kernel/IOPlatformExpert.cpp b/iokit/Kernel/IOPlatformExpert.cppindex 7a32a23e4bb1..35dc7b503846 100644--- a/iokit/Kernel/IOPlatformExpert.cpp