diff --git a/.github/workflows/gpu-patch-check.yml b/.github/workflows/gpu-patch-check.yml new file mode 100644 index 00000000..fbbfe8c0 --- /dev/null +++ b/.github/workflows/gpu-patch-check.yml @@ -0,0 +1,47 @@ +# Do the Adreno-generic metal2vulkan patches of userland/metal/patches/metal2vulkan apply to the pin of +# scripts/setup/get-references.sh, and does the crate still type-check with them? Public sources only, no Apple files. +# Manual run; on a failure the log is the artifact (send it back). +name: gpu-patch-check +on: + workflow_dispatch: + pull_request: + paths: ["userland/metal/patches/**"] +permissions: + contents: read +jobs: + check: + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Pin + id: pin + run: | + set -euo pipefail + pin=$(awk '$1=="metal2vulkan" {print $3}' scripts/setup/get-references.sh) + echo "pin=$pin" >> "$GITHUB_OUTPUT" + - name: Restore executable bits (an upload drops them) + run: git ls-files -z | xargs -0 grep -lZI '^#!' 2>/dev/null | xargs -0 -r chmod +x + - name: metal2vulkan at the pin + run: | + set -euo pipefail + git clone --filter=blob:none --no-checkout https://github.com/steelbrain/metal2vulkan.git m2v + git -C m2v checkout -q ${{ steps.pin.outputs.pin }} + - name: Apply + run: | + set -euo pipefail + cd m2v + git config user.email ci@example.invalid; git config user.name ci + for p in ../userland/metal/patches/metal2vulkan/*.patch; do echo "== $p"; git apply --check "$p"; git apply "$p"; done 2>&1 | tee ../apply.log + - name: cargo check (host) + run: | + set -euo pipefail + cd m2v + cargo check -p metal2vulkan -p metal2vulkan-runtime 2>&1 | tee ../cargo.log + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: gpu-patch-check-logs + path: | + apply.log + cargo.log diff --git a/docs/gpu.md b/docs/gpu.md index ae94ad9c..3cb76127 100644 --- a/docs/gpu.md +++ b/docs/gpu.md @@ -1017,7 +1017,7 @@ scripts/bg.sh metal userland/metal/build.sh # stage, turnip, plugin, finish | Piece | Source | Notes | |---|---|---| | `libvulkan_freedreno.dylib` | `external/mesa-droidvm` cecc0e9 (Droid-VM/mesa, `droidvm`) + the 30 patches listed in Droid-VM-UniXNU `scripts/data/adreno-compiler-inputs.json` (`patches/mesa/`: `turnip-darwin-kmd`, `turnip-darwin-virtgpu`, ...) | meson cross build, `-Dvulkan-drivers=freedreno -Dfreedreno-kmds=darwin`, release. Its 5633 weak flat-namespace imports are bound to the image itself (`macho-weak-self-binds.py`) | -| `libadreno_metal_bridge.a` | `external/metal2vulkan` 624bab3 + NativeMetal `bridge/patches` 0001-0024 (without 0020) + Droid-VM-UniXNU `patches/metal2vulkan` 0011-0038, behind `bridge/NativeMetalBridge.rs` | Rust 1.98.0, target `arm64e-apple-ios`, std built from `rust-src`, fat LTO. No `Cargo.lock` is pinned upstream: the crates are the newest that fit at build time | +| `libadreno_metal_bridge.a` | `external/metal2vulkan` 624bab3 + NativeMetal `bridge/patches` 0001-0024 (without 0020) + Droid-VM-UniXNU `patches/metal2vulkan` 0011-0038 + this project's `userland/metal/patches/metal2vulkan/` 0101-0103 (staged as 9xxx so they sort last: the Adreno-generic shader-translation fixes of hakios-arm64e-dada; `0104…NEEDS-REBASE` stays out, and the Mesa/nativemetal sets stay out as the wrong tree), behind `bridge/NativeMetalBridge.rs` | Rust 1.98.0, target `arm64e-apple-ios`, std built from `rust-src`, fat LTO. No `Cargo.lock` is pinned upstream: the crates are the newest that fit at build time | | `NativeAdrenoMetal` | `external/NativeMetal` b0d6a07 (`NativeAdrenoMetalPlugin.mm`, `NativeBridgeMetalFrontend.mm`), `external/AdrenoPM4`, the bridge | The Rust objects' callback imports go through `RustPacBoundary.c`; their indirect branches through its trampolines (`rust-pac-rewrite.py`) | The steps are the kernel base's own scripts (`build-turnip-darwin.py`, `build-adreno-metal-bridge.py`, @@ -1048,6 +1048,12 @@ framebuffer is `RGhA` half floats and the display path keeps them whole half-float framebuffer asked (...)`. The headroom, threshold and virtualized overrides below stay as they are. Not built or compiled yet (the plug-in builds on the Mac). +**Lasting debug tooling, off by default** (`stage`): `userland/metal/trace-turnip-init.patch` (into +`patches/mesa/` and the staged mesa-work tree, and appended to `adreno-compiler-inputs.json`), +`trace-metal-vulkan-init.patch` (into `patches/metal2vulkan/`), and `trace-metal-surfaces.patch` (into `patches/`, +applied to the staged frontend after the upstream replacements). Each only logs when its environment variable is +set (`ONEIOS_VK_INIT`, `ONEIOS_SURFACE_TRACE`), so a normal build is unchanged. + **The shared cache addresses.** Upstream's plug-in writes QuartzCore's options at fixed addresses of the iPad17,3 24A446 cache, relative to `CARenderServerStart`. They were re-found in this guest's cache (`out/image/24A446/systemos.img`, cache UUID `77BC8C63-93DA-3E9B-BB9C-0BE2AF0C0E17`) and are recorded in diff --git a/docs/hardware.md b/docs/hardware.md index 384f1bca..c9777ffe 100644 --- a/docs/hardware.md +++ b/docs/hardware.md @@ -1287,7 +1287,10 @@ addresses are the binary's, unslid): thread (overdrive, minimum on-time, duty limit, watchdog). Those protected an ERM on a bare LDO; here the chip's DSP brakes and protects the LRA. New: each write's loud span is sent with its peak as the intensity and its zero-crossing rate as the frequency. -- Messages: `OB_HAPTIC_VIB {on_ms, intensity 0..1000, frequency_hz}`, `OB_HAPTIC_STOP`. +- Messages: `OB_HAPTIC_VIB {on_ms, intensity 0..1000, frequency_hz}`, `OB_HAPTIC_STOP`, + `OB_HAPTIC_IMPACT {kind 1..3}` (an explicit one-shot, never a short VIB segment; only when the host + advertised `OB_FEAT_HAPTIC_IMPACT` in a length-extended v1 `OB_CTL_HELLO`, else the guest sends none and an + old host's 8-byte hello reads as features=0). ### UI haptics: the Actuator audio device (media, 2026-11-12; built, not run on the phone) @@ -1314,12 +1317,20 @@ What is built: latency one period (not the speaker's 6480 frames: the haptic synth keeps haptics in step with a device's latency). Each period goes to `oneios_haptic_actuator_play()`, not to virtio-snd. Published only when `drivers/haptics` has the host's actuator and UI haptics are on; `oneios-actuator=0` leaves it out. -- **The requests** (`drivers/haptics/oneios_actuator.h`, host-tested by `drivers/haptics/test_actuator.c`, 16 checks): +- **The requests** (`drivers/haptics/oneios_actuator.h`, host-tested by `drivers/haptics/test_actuator.c`, 19 checks): a period is loud above 256 of 32768; the first loud period asks 20 ms (a tap), the run renews when less than 12 ms is left (50 ms segments after 20 ms) or the level moves by more than 100 of 1000; a run of 30 ms or more is stopped after 10 ms of silence, a tap runs out. Intensity = the period's peak; frequency = the run's zero crossings with hysteresis, after 10 ms. A tap is one request; a long vibration about 20 a second (each is an effect upload on the CS40L26's I2C). +- **Native impacts** (off by default, both sides opt in): with the guest boot argument `oneios_native_impacts=1` + and the host started with `ONEIOS_HAPTIC_NATIVE_IMPACTS=1` on a HAL whose `getSupportedEffects` advertises + TICK, CLICK and HEAVY_CLICK, a short isolated run (under 30 ms, confirmed by 10 ms of silence) becomes one + `OB_HAPTIC_IMPACT` instead of 20 ms motor starts; the intensity maps to LIGHT (<=250), MEDIUM (<=800), HEAVY. + The host plays the matching `IVibrator.perform()` preset through the same serialized worker; a later STOP never + cancels an already-finished preset (its HAL-reported duration bounds `off()`), so One UI's own vibration is not + interrupted. Longer runs keep VIB/STOP semantics, malformed or unsupported impacts are dropped, never mapped to + VIB. Host-tested (`test_bridges` native-impacts case, `test_hal_binder` preset case); not run on the phone. - **The closed-loop node**: `oneios_haptic.c` waits (5 s at most) for the audio archive's decision (`oneios_haptic_actuator_published`), then publishes `/product/haptics {closed-loop 1, supports-3rd-party-haptics 1}` when the device exists (the old rule, an Actuator HAL plug-in in the root, stays as the second way in). Not copied diff --git a/drivers/bridge/OneiOSBridge.c b/drivers/bridge/OneiOSBridge.c index 2597edf8..959b2ca5 100644 --- a/drivers/bridge/OneiOSBridge.c +++ b/drivers/bridge/OneiOSBridge.c @@ -51,6 +51,7 @@ static struct { uint16_t tx_head, rx_used; bool up, interrupt; volatile uint32_t channels; // from the host's hello + volatile uint32_t features; // optional extended HELLO; zero on old hosts struct { oneios_bridge_handler fn; void *context; } listener[OB_CH_COUNT]; } ob; @@ -185,6 +186,7 @@ void oneios_bridge_listen(uint16_t channel, oneios_bridge_handler fn, void *cont bool oneios_bridge_ready(void) { return ob.up && ob.channels != 0; } uint32_t oneios_bridge_channels(void) { return ob.channels; } +uint32_t oneios_bridge_features(void) { return ob.features; } static void ob_dispatch(const uint8_t *message, uint32_t written) { struct ob_header header; @@ -197,6 +199,12 @@ static void ob_dispatch(const uint8_t *message, uint32_t written) { struct ob_ctl_hello hello; memcpy(&hello, payload, sizeof(hello)); ob.channels = hello.channels; + ob.features = 0; + if (header.length >= sizeof(struct ob_ctl_hello_ext)) { + struct ob_ctl_hello_ext ext; + memcpy(&ext, payload, sizeof(ext)); + if (ext.version == OB_PROTO_VERSION) ob.features = ext.features; + } oneios_bridge_stage = 5; snprintf(oneios_bridge_status, sizeof(oneios_bridge_status), "up, host channels %#x", hello.channels); printf("ONEIOS BRIDGE: on: host protocol %u, channels %#x (1 control, 2 haptics, 4 Bluetooth)\n", hello.version, hello.channels); diff --git a/drivers/bridge/oneios_bridge.h b/drivers/bridge/oneios_bridge.h index 0484f210..40bfc032 100644 --- a/drivers/bridge/oneios_bridge.h +++ b/drivers/bridge/oneios_bridge.h @@ -22,6 +22,8 @@ void oneios_bridge_start(void); bool oneios_bridge_ready(void); // Bit n: the host serves channel n. 0 until ready. uint32_t oneios_bridge_channels(void); +// Optional host features announced in a length-extended v1 HELLO. Older hosts: 0. +uint32_t oneios_bridge_features(void); // Sends one message. Any thread context that may take a mutex. 0, or -1 (not up, too long, queue full). int oneios_bridge_send(uint16_t channel, uint16_t type, const void *payload, uint32_t length); // Messages from the host for `channel` are handed to fn on the bridge's worker thread. @@ -32,6 +34,9 @@ void oneios_bridge_listen(uint16_t channel, oneios_bridge_handler fn, void *cont int oneios_haptic_start(void); // Vibrate from now for ms (0 = stop) at intensity 0..1000 and frequency_hz (0 = resonance). int oneios_haptic_vib(uint32_t ms, uint32_t intensity, uint32_t frequency_hz); +// A semantically discrete impact. Only when the host advertised OB_FEAT_HAPTIC_IMPACT; +// not interchangeable with on_ms and never auto-falls back to a continuous buzz. +int oneios_haptic_impact(uint32_t kind); void oneios_haptic_make_node(void); int oneios_haptic_publish_closed_loop(void); // The Actuator IOAudio2Device of the audio archive (DroidVMAudio.cpp as staged): ready = may publish it; diff --git a/drivers/bridge/oneios_bridge_proto.h b/drivers/bridge/oneios_bridge_proto.h index 9a03ddc7..abd65a5b 100644 --- a/drivers/bridge/oneios_bridge_proto.h +++ b/drivers/bridge/oneios_bridge_proto.h @@ -35,12 +35,19 @@ enum { OB_CH_CONTROL = 0, OB_CH_HAPTIC = 1, OB_CH_HCI = 2, OB_CH_CAMERA = 3, OB_ // before, so the way back is never at risk. enum { OB_CTL_HELLO = 1, OB_CTL_SHUTDOWN = 2 }; struct ob_ctl_hello { uint32_t version, channels; }; +/* Optional v1 hello extension (12 bytes). An older guest ignores the extra + * word; a newer guest treats an 8-byte reply as features=0. */ +#define OB_FEAT_HAPTIC_IMPACT (1u << 0) +struct ob_ctl_hello_ext { uint32_t version, channels, features; }; // ---- haptics (guest -> host only) ------------------------------------------------------------- enum { OB_HAPTIC_VIB = 1, // struct ob_haptic_vib: vibrate from now; on_ms 0 stops OB_HAPTIC_STOP = 2, // no payload + OB_HAPTIC_IMPACT = 3, // explicit one-shot impact; not a short VIB segment }; +enum { OB_IMPACT_LIGHT = 1, OB_IMPACT_MEDIUM = 2, OB_IMPACT_HEAVY = 3 }; +struct ob_haptic_impact { uint32_t kind; }; struct ob_haptic_vib { uint32_t on_ms; // 0 = stop uint16_t intensity; // 0..1000 (iOS's 0.0..1.0) diff --git a/drivers/haptics/oneios_actuator.h b/drivers/haptics/oneios_actuator.h index 1f7e3969..ec6874f5 100644 --- a/drivers/haptics/oneios_actuator.h +++ b/drivers/haptics/oneios_actuator.h @@ -35,10 +35,12 @@ #define OA_QUIET_MS 10u #define OA_LEVEL_STEP 100u -enum { OA_NONE = 0, OA_VIB = 1, OA_STOP = 2 }; +enum { OA_NONE = 0, OA_VIB = 1, OA_STOP = 2, OA_IMPACT = 3 }; struct oa_state { bool on; /* a request is in flight */ + bool native_taps; /* opt-in; only if the host advertised native impacts */ + uint32_t short_peak; /* strongest PCM sample in a not-yet-classified tap */ uint32_t now_us; /* the periods given so far, in microseconds */ uint32_t until_us; /* when the request in flight ends */ uint32_t level, hz; /* what it asked */ @@ -82,6 +84,7 @@ oa_period(struct oa_state *s, const int16_t *frames, uint32_t count, uint32_t ch s->on = false; /* the request ran out by itself */ } if (peak > OA_SILENT) { + if (peak > s->short_peak) s->short_peak = peak; s->run_us += period_us; s->run_crossings += crossings; s->quiet_us = 0; @@ -90,6 +93,12 @@ oa_period(struct oa_state *s, const int16_t *frames, uint32_t count, uint32_t ch uint32_t hz = s->run_us >= 10000u ? (uint32_t)((uint64_t)s->run_crossings * 1000000u / (2u * s->run_us)) : 0u; uint32_t moved = intensity > s->level ? intensity - s->level : s->level - intensity; bool renew = s->on && s->until_us - s->now_us < OA_RENEW_MS * 1000u; + /* When opted in, hold a newly started run for at most 30 ms. A + * short run confirmed by silence becomes ONE impact rather than + * several 20 ms motor starts; longer runs keep VIB/STOP semantics. */ + if (s->native_taps && !s->on && s->run_us < OA_LONG_MS * 1000u) { + return r; + } if (!s->on || renew || moved > OA_LEVEL_STEP) { r.action = OA_VIB; r.ms = s->run_us > OA_TAP_MS * 1000u ? OA_SEGMENT_MS : OA_TAP_MS; @@ -102,6 +111,16 @@ oa_period(struct oa_state *s, const int16_t *frames, uint32_t count, uint32_t ch } } else { s->quiet_us += period_us; + if (s->native_taps && !s->on && s->run_us > 0 && + s->run_us < OA_LONG_MS * 1000u && + s->quiet_us >= OA_QUIET_MS * 1000u) { + r.action = OA_IMPACT; + r.intensity = s->short_peak * 1000u / 32768u; + if (r.intensity == 0) r.intensity = 1; + if (r.intensity > 1000) r.intensity = 1000; + s->short_peak = 0; + s->sign = 0; + } if (s->quiet_us >= OA_QUIET_MS * 1000u) { if (s->on && s->run_us >= OA_LONG_MS * 1000u) { r.action = OA_STOP; @@ -109,6 +128,7 @@ oa_period(struct oa_state *s, const int16_t *frames, uint32_t count, uint32_t ch } s->run_us = 0; s->run_crossings = 0; + if (s->native_taps) { s->short_peak = 0; s->sign = 0; } } } /* a session of hours: keep the clock away from the 32-bit wrap */ diff --git a/drivers/haptics/oneios_haptic.c b/drivers/haptics/oneios_haptic.c index cc97405e..735d4bd3 100644 --- a/drivers/haptics/oneios_haptic.c +++ b/drivers/haptics/oneios_haptic.c @@ -37,6 +37,8 @@ * "haptics: counters:" line is the host's side: what came over the bridge and what the device played). * Kill switches: oneios_haptic=0 (all), oneios_haptic_ui=0 (no closed-loop node, no Actuator device); * the audio archive's oneios-actuator=0 (no Actuator device); oneios_haptic_report=0 (no counter line). + * oneios_native_impacts=1: short isolated taps become one OB_HAPTIC_IMPACT each instead of 20 ms motor + * starts, but only when the host advertised OB_FEAT_HAPTIC_IMPACT (else off, and VIB/STOP as before). */ #include #include @@ -71,6 +73,7 @@ static LCK_MTX_DECLARE(oh_wlock, &oh_grp); /* the stream state */ static bool oh_ready; /* the host serves the haptic channel */ static uint32_t oh_ui = 1; +static bool oh_native_impacts; /* user opt-in AND host advertised the feature */ static uint32_t oh_part, oh_part_peak; /* the open 2 ms block */ static int16_t oh_last; /* the previous sample, for zero crossings */ static uint64_t oh_frames, oh_loud_blocks; @@ -78,7 +81,8 @@ static uint32_t oh_said, oh_vibs; static bool oh_node_made, oh_opened, oh_wrote; /* The counter line's figures for the bridge (every layer has its own: see oh_report_thread). */ -static volatile uint64_t oh_sent_vib, oh_sent_stop, oh_send_failed, oh_send_no_host; +static volatile uint64_t oh_sent_vib, oh_sent_stop, oh_sent_impact, oh_send_failed, oh_send_no_host; +static uint32_t oh_impacts_logged; int oneios_haptic_vib(uint32_t ms, uint32_t intensity, uint32_t frequency_hz) @@ -114,6 +118,30 @@ oneios_haptic_vib(uint32_t ms, uint32_t intensity, uint32_t frequency_hz) return rc; } +/* A separately tagged single impact; never reinterpret duration-based VIB + * traffic. The receiver is available only through the host's extended HELLO. + * The host does not make an unsafe fallback to the Samsung sine path. */ +int +oneios_haptic_impact(uint32_t kind) +{ + if (!oh_ready || !oh_native_impacts || !(oneios_bridge_features() & OB_FEAT_HAPTIC_IMPACT) || + kind < OB_IMPACT_LIGHT || kind > OB_IMPACT_HEAVY) { + return -1; + } + struct ob_haptic_impact impact = { .kind = kind }; + int rc = oneios_bridge_send(OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &impact, sizeof impact); + if (rc == 0) { + oh_sent_impact++; + if (oh_impacts_logged < OH_LOG) { + oh_impacts_logged++; + printf("ONEIOS HAPTIC: native impact %u: kind %u sent to the host\n", oh_impacts_logged, kind); + } + } else { + oh_send_failed++; + } + return rc; +} + /* ---- the Actuator IOAudio2Device (audio archive) --------------------------------------------------- */ static LCK_MTX_DECLARE(oh_alock, &oh_grp); /* the Actuator's state */ @@ -158,6 +186,7 @@ oneios_haptic_actuator_running(bool on) oh_act_stops++; } bzero(&oh_act, sizeof(oh_act)); + oh_act.native_taps = oh_native_impacts; lck_mtx_unlock(&oh_alock); if (starts <= 3u || !on) { char who[32]; @@ -183,6 +212,7 @@ oneios_haptic_actuator_play(const int16_t *frames, uint32_t count, uint32_t chan peak = m > peak ? m : peak; } lck_mtx_lock(&oh_alock); + oh_act.native_taps = oh_native_impacts; struct oa_request r = oa_period(&oh_act, frames, count, channels); oh_act_periods++; oh_act_frames += count; @@ -201,6 +231,12 @@ oneios_haptic_actuator_play(const int16_t *frames, uint32_t count, uint32_t chan (void)oneios_haptic_vib(r.ms, r.intensity, r.hz); } else if (r.action == OA_STOP) { (void)oneios_haptic_vib(0, 0, 0); + } else if (r.action == OA_IMPACT) { + /* Short isolated samples are distinct from 20/50 ms segments + * of a sustained waveform. The 3 thresholds are experimental. */ + uint32_t kind = r.intensity <= 250 ? OB_IMPACT_LIGHT : + r.intensity <= 800 ? OB_IMPACT_MEDIUM : OB_IMPACT_HEAVY; + (void)oneios_haptic_impact(kind); } return count; } @@ -266,19 +302,19 @@ oh_report_thread(__unused void *arg, __unused wait_result_t wr) for (;;) { delay_for_interval(OH_REPORT_S, NSEC_PER_SEC); uint64_t now = oh_act_opens + oh_act_closes + oh_act_selectors + oh_act_maps + oh_act_periods + oh_sent_vib + oh_sent_stop + - oh_send_failed + oh_send_no_host + oneios_vibrator_requests + oh_frames; + oh_send_failed + oh_send_no_host + oh_sent_impact + oneios_vibrator_requests + oh_frames; if (now == last) { continue; } last = now; printf("ONEIOS HAPTIC: counters: Actuator %u opens (%u closed, last by %s), %llu selectors (%u StartIO, %u StopIO, " "%u refused, %u formats asked, last %d), %u maps; %llu periods (%llu ms), %llu with samples, %llu loud, peak %u of 32768; " - "%llu requests to the motor | vibrator service %u requests | /dev/oneios-haptic %llu frames | bridge %llu vib + %llu stop sent, " + "%llu requests to the motor | vibrator service %u requests | /dev/oneios-haptic %llu frames | bridge %llu vib + %llu stop + %llu impacts sent, " "%llu failed, %llu with no host actuator\n", oh_act_opens, oh_act_closes, oh_act_opener[0] ? oh_act_opener : "-", oh_act_selectors, oh_act_starts, oh_act_stops, oh_act_refused, oh_act_formats, (int)oh_act_last_selector, oh_act_maps, oh_act_periods, oh_act_frames / 48u, oh_act_sounding, oh_act_loud, oh_act_peak, oh_act_requests, oneios_vibrator_requests, oh_frames, oh_sent_vib, - oh_sent_stop, oh_send_failed, oh_send_no_host); + oh_sent_stop, oh_sent_impact, oh_send_failed, oh_send_no_host); } } @@ -501,6 +537,14 @@ oneios_haptic_start(void) printf("ONEIOS HAPTIC: off: the host has no actuator (no force-feedback device opened)\n"); return -1; } + /* The normal audio envelope path is unchanged unless BOTH the guest + * boot argument and the host's negotiated feature enable native taps. */ + uint32_t impact_optin = 0; + (void)PE_parse_boot_argn("oneios_native_impacts", &impact_optin, sizeof impact_optin); + oh_native_impacts = impact_optin == 1 && + (oneios_bridge_features() & OB_FEAT_HAPTIC_IMPACT) != 0; + printf("ONEIOS HAPTIC: native impacts %s (guest opt-in %u, host features %#x)\n", + oh_native_impacts ? "enabled" : "off", impact_optin, oneios_bridge_features()); oh_ready = true; printf("ONEIOS HAPTIC: on: host actuator over the bridge channel (amplitude 0..1000, frequency in Hz)\n"); if (kernel_thread_start(oh_root_thread, NULL, &th) == KERN_SUCCESS) { diff --git a/drivers/haptics/test_actuator.c b/drivers/haptics/test_actuator.c index f3908239..8a55b7a6 100644 --- a/drivers/haptics/test_actuator.c +++ b/drivers/haptics/test_actuator.c @@ -10,7 +10,7 @@ static int failures, checks; #define PERIOD 240u // the engine's period: 5 ms at 48 kHz -struct tally { unsigned vibs, stops, first_ms, last_intensity, last_hz; }; +struct tally { unsigned vibs, stops, impacts, impact_intensity, first_ms, last_intensity, last_hz; }; // Feeds `ms` of a sine of `hz` at `amplitude` (0: silence) in engine periods; counts the requests. static void feed(struct oa_state *s, struct tally *t, unsigned ms, double hz, double amplitude, unsigned channels, double *phase) @@ -30,6 +30,9 @@ static void feed(struct oa_state *s, struct tally *t, unsigned ms, double hz, do t->last_hz = r.hz; } else if (r.action == OA_STOP) { t->stops++; + } else if (r.action == OA_IMPACT) { + t->impacts++; + t->impact_intensity = r.intensity; } } } @@ -106,6 +109,33 @@ int main(void) feed(&s, &t, 5, 230, 32000, 1, &phase); CHECK(t.vibs == 1, "after a long silence: %u requests", t.vibs); } + /* Opt-in native taps: do not turn the first 20-ms segment of a + * continuous waveform into a spurious impact. A short isolated burst + * becomes one tagged impact after 10 ms of silence. */ + { + struct oa_state s; memset(&s, 0, sizeof s); s.native_taps = true; + struct tally t = { 0 }; + feed(&s, &t, 5, 230, 32000, 1, &phase); + feed(&s, &t, 100, 0, 0, 1, &phase); + CHECK(t.impacts == 1 && t.vibs == 0 && t.stops == 0 && t.impact_intensity > 900, + "native tap: impacts %u vibs %u stops %u intensity %u", + t.impacts, t.vibs, t.stops, t.impact_intensity); + feed(&s, &t, 10, 145, 3277, 1, &phase); + feed(&s, &t, 100, 0, 0, 1, &phase); + CHECK(t.impacts == 2 && t.vibs == 0 && t.stops == 0 && t.impact_intensity >= 80 && + t.impact_intensity <= 120, + "native keyboard: impacts %u vibs %u intensity %u", + t.impacts, t.vibs, t.impact_intensity); + } + { + struct oa_state s; memset(&s, 0, sizeof s); s.native_taps = true; + struct tally t = { 0 }; + feed(&s, &t, 1000, 160, 16000, 1, &phase); + feed(&s, &t, 100, 0, 0, 1, &phase); + CHECK(t.impacts == 0 && t.vibs >= 15 && t.vibs <= 40 && t.stops == 1, + "native sustained: impacts %u, vib %u, stops %u", t.impacts, t.vibs, t.stops); + } + printf("actuator: %d checks, %d failures\n", checks, failures); return failures ? 1 : 0; } diff --git a/kernel/patches/oneios-hosted/0073-mac-exec-label-report.patch b/kernel/patches/oneios-hosted/0073-mac-exec-label-report.patch new file mode 100644 index 00000000..8b1102f3 --- /dev/null +++ b/kernel/patches/oneios-hosted/0073-mac-exec-label-report.patch @@ -0,0 +1,91 @@ +diff --git a/security/mac_vfs.c b/security/mac_vfs.c +--- a/security/mac_vfs.c ++++ b/security/mac_vfs.c +@@ -788,6 +788,65 @@ + return error; + } + ++#if XNU_HOSTED ++/* ++ * OneiOS hosted (0073): which MAC policy refuses an exec's credential update, and a way past one. iOS 16.5's ++ * mediaserverd (20F66) never ran on the A56: launchd's log has xpcproxy exiting with OS_REASON_EXEC code 8 ++ * (EXEC_EXIT_REASON_SECURITY_POLICY) every 5 s, with nothing on the console, which is process_signature() seeing ++ * ip_mac_return, the error of this hook (kauth_proc_label_update_execve). SpringBoard then waits forever in ++ * MediaExperience for com.apple.coremedia.systemcontroller.xpc, which mediaserverd serves. ++ * One line per (executable, policy, error), at most 200: ++ * oneios-mac-exec: mediaserverd: policy Sandbox refused the credential update (error 1) ++ * Boot argument oneios-mac-exec-skip=NAME[,NAME...]: for those executables (the file's name) a refusal by the Sandbox ++ * policy is ignored and the process runs without its sandbox profile. Off without it; other policies are never skipped. ++ */ ++static char hosted_mac_exec_skip[256]; ++static int hosted_mac_exec_state = -1; ++static uint32_t hosted_mac_exec_lines; ++static bool ++hosted_mac_exec_listed(const char *name) ++{ ++ if (hosted_mac_exec_state < 0) { ++ hosted_mac_exec_state = PE_parse_boot_argn("oneios-mac-exec-skip", hosted_mac_exec_skip, sizeof(hosted_mac_exec_skip)) && ++ hosted_mac_exec_skip[0]; ++ } ++ if (hosted_mac_exec_state == 0 || name == NULL) { ++ return false; ++ } ++ size_t length = strlen(name); ++ for (const char *at = hosted_mac_exec_skip; *at;) { ++ const char *end = strchr(at, ','); ++ size_t n = end ? (size_t)(end - at) : strlen(at); ++ if (n == length && !strncmp(at, name, n)) { ++ return true; ++ } ++ at += n + (end ? 1 : 0); ++ } ++ return false; ++} ++static int ++hosted_mac_exec_result(struct mac_policy_conf *mpc, struct vnode *vp, int error) ++{ ++ if (error == 0 || mpc == NULL) { ++ return error; ++ } ++ const char *name = vp ? vnode_getname(vp) : NULL; ++ bool skip = mpc->mpc_name != NULL && !strcmp(mpc->mpc_name, "Sandbox") && hosted_mac_exec_listed(name); ++ if (hosted_mac_exec_lines < 200) { ++ hosted_mac_exec_lines++; ++ printf("oneios-mac-exec: %s: policy %s refused the credential update (error %d)%s\n", name ? name : "?", ++ mpc->mpc_name ? mpc->mpc_name : "?", error, skip ? ": ignored (oneios-mac-exec-skip)" : ""); ++ } ++ if (name != NULL) { ++ vnode_putname(name); ++ } ++ return skip ? 0 : error; ++} ++#define HOSTED_MAC_WRAP(m, v, e) hosted_mac_exec_result((m), (v), (e)) ++#else ++#define HOSTED_MAC_WRAP(m, v, e) (e) ++#endif /* XNU_HOSTED */ ++ + void + mac_cred_label_update_execve(vfs_context_t ctx, kauth_cred_t new, struct vnode *vp, off_t offset, + struct vnode *scriptvp, struct label *scriptvnodelabel, struct label *execl, u_int *csflags, +@@ -835,8 +894,8 @@ + size_t spawnattrlen = 0; + void *spawnattr = exec_spawnattr_getmacpolicyinfo(macextensions, mpc->mpc_name, &spawnattrlen); + +- error = mac_error_select(hook(cred, new, vfs_context_proc(ctx), vp, offset, scriptvp, +- mac_vnode_label(vp), scriptvnodelabel, execl, csflags, spawnattr, spawnattrlen, disjoint), ++ error = mac_error_select(HOSTED_MAC_WRAP(mpc, vp, hook(cred, new, vfs_context_proc(ctx), vp, offset, scriptvp, ++ mac_vnode_label(vp), scriptvnodelabel, execl, csflags, spawnattr, spawnattrlen, disjoint)), + error); + } + if (mac_policy_list_conditional_busy() != 0) { +@@ -854,8 +913,8 @@ + size_t spawnattrlen = 0; + void *spawnattr = exec_spawnattr_getmacpolicyinfo(macextensions, mpc->mpc_name, &spawnattrlen); + +- error = mac_error_select(hook(cred, new, vfs_context_proc(ctx), vp, offset, scriptvp, +- mac_vnode_label(vp), scriptvnodelabel, execl, csflags, spawnattr, spawnattrlen, disjoint), ++ error = mac_error_select(HOSTED_MAC_WRAP(mpc, vp, hook(cred, new, vfs_context_proc(ctx), vp, offset, scriptvp, ++ mac_vnode_label(vp), scriptvnodelabel, execl, csflags, spawnattr, spawnattrlen, disjoint)), + error); + } + mac_policy_list_unbusy(); diff --git a/kernel/patches/oneios-hosted/README.md b/kernel/patches/oneios-hosted/README.md index dc9189bc..1a2d0fbc 100644 --- a/kernel/patches/oneios-hosted/README.md +++ b/kernel/patches/oneios-hosted/README.md @@ -1097,6 +1097,16 @@ cache maintenance, so only arm64 hardware runs the fault itself). (`type=0xa`), which an earlier PC boot on main had too. No WebContent process ran (Safari is not opened on the PC), and qemu does not fault on cache maintenance, so the fix itself is proven on the phone only. +## 0073-mac-exec-label-report.patch (2026-11-20; ported from Musicalista-OneiOS-A56) + +A debugging aid, off by default. When an exec's credential update is refused, the console has only the hook's error +(a launcher's `xpcproxy` exiting with a security-policy code, nothing naming the policy, and a daemon then waited on +forever). 0073 wraps `mac_cred_label_update_execve`'s two `mac_error_select` calls: one line per (executable, policy, +error), at most 200 per boot (`oneios-mac-exec: NAME: policy P refused the credential update (error E)`), and with +`oneios-mac-exec-skip=NAME[,NAME...]` a Sandbox refusal for those executables is ignored (they run unsandboxed). +Other policies are never skipped. Applies cleanly to xnu-12377.121.6 (checked with `patch -p1 --dry-run`); the kernel +is not rebuilt here, so the first boot with it proves it. + ## gpu/: the blobs' kinds and ages, `oneios-cpu`'s span (hang, 2026-11-13; the archive, not a numbered patch) No XNU source changes, so no patch in the series: `oneios-tool kernel gen gpu` compiles a staged diff --git a/kernel/patches/oneios-hosted/series b/kernel/patches/oneios-hosted/series index 406bdcdf..c1802186 100644 --- a/kernel/patches/oneios-hosted/series +++ b/kernel/patches/oneios-hosted/series @@ -232,6 +232,13 @@ # and a user CM fault reaches XNU with CM and WnR kept and an access flag fault (XNU's own CM rule makes it a read). # The runtime's stub says XH_PROT_READ for it too (runtime/xnuhost/stub/stub_abi.h, xs_fault_access). 0071-cache-maintenance-fault-read.patch +# sandbox-triage, a debugging aid (ported from Musicalista-OneiOS-A56's 0073; applies cleanly to xnu-12377.121.6, +# kernel not rebuilt here): mac_cred_label_update_execve's refusal says only the hook's error on the console (an +# xpcproxy exec ending in a security-policy exit, with a daemon then waited on forever). 0073 logs which MAC policy +# refused whose credential update ("oneios-mac-exec: NAME: policy P refused the credential update (error E)", at most +# 200 lines) and, with oneios-mac-exec-skip=NAME[,NAME...], ignores a Sandbox refusal for those executables (they run +# unsandboxed). Off without it; other policies are never skipped. README.md, "0073". +0073-mac-exec-label-report.patch # fix-host-overhead (2026-11-15): the trap path's counters per vCPU (every vCPU wrote the same lines on every user stay: # the stats, the audit tick's atomic, the perf report's per-call atomics); the fill's time without the time its thread # was switched out (the phone's "filled from the tables 11417628 us" was mostly preemption inside the fill); a kernel diff --git a/runtime/bridges/Makefile b/runtime/bridges/Makefile index 98fa515d..f5cc2732 100644 --- a/runtime/bridges/Makefile +++ b/runtime/bridges/Makefile @@ -10,12 +10,12 @@ ANDROID_CC ?= $(TOOLS)/aarch64-linux-android30-clang ANDROID_AR ?= $(TOOLS)/llvm-ar XNUHOST := ../xnuhost WARN := -Wall -Wextra -Werror -INC := -Iinclude -I../../drivers/bridge -I../../drivers/net -I$(XNUHOST)/src -I$(XNUHOST)/include +INC := -Iinclude -I../../drivers/bridge -I../../drivers/net -I../../drivers/haptics -I$(XNUHOST)/src -I$(XNUHOST)/include CFLAGS ?= -O2 -g WIFI := wifi/frames wifi/station wifi/wlan wifi/sim wifi/aidl_parcel wifi/aidl_binder wifi/supplicant CORE := cpu/topology hw/hw_backend hw/hw_log hal/hal haptics/haptic net/net bt/hci bt/le_scan bt/hci_sim bt/hidl_parcel bt/hci_hidl audio/backend brightness/brightness battery/battery thermal/thermal $(WIFI) DEVICES := devices/bridge_dev devices/virtio_net devices/virtio_snd -HDR := $(wildcard include/bridges/*.h hal/*.h bt/*.h audio/*.h brightness/*.h battery/*.h thermal/*.h wifi/*.h ../../drivers/bridge/*.h ../../drivers/net/*.h $(XNUHOST)/src/xnuhost.h) +HDR := $(wildcard include/bridges/*.h hal/*.h bt/*.h audio/*.h brightness/*.h battery/*.h thermal/*.h wifi/*.h ../../drivers/bridge/*.h ../../drivers/net/*.h ../../drivers/haptics/*.h $(XNUHOST)/src/xnuhost.h) A := build/android H := build/host diff --git a/runtime/bridges/README.md b/runtime/bridges/README.md index 22534c76..0ddc616c 100644 --- a/runtime/bridges/README.md +++ b/runtime/bridges/README.md @@ -16,7 +16,7 @@ tests/host.sh # both; CI runs it (Linux only: on a Mac, runtime/host-tests. | `include/bridges/hw_backend.h`, `hw/` | the backend layer: `hw-backend=samsung\|treble`, `hw-backend-`, `hw-backend-fallback` (`hw_backend.c`, pure: the settings, the choice; `hw_log.c`: the `hw: : backend ...` and `... treble: missing: ...` lines); `test_hw_backend.c` (in `make test`). `docs/hardware.md` 7e: the audit table | | `hal/` | the treble backend's HAL client (`hal.c`: a HAL by name from servicemanager on `/dev/binder`, its descriptor checked, the calls; the Wi-Fi bridge's `aidl_binder.c` underneath) and the HALs' parcels both ways (`HealthInfo`, `Temperature[]`); `tests/fake_hal.c` (`build/host/fake-hal DIR`: a fake servicemanager with fake health, thermal and vibrator HALs whose values are files of DIR) and `tests/test_hal_binder.c` (`make test-binder`: the treble bridges against it on a real binder driver) | | `cpu/` | host topology from sysfs, the vCPU plan (E first, then P), thread placement, the cpufreq register window | -| `haptics/` | evdev force feedback (`sec_vibrator_inputff`) or, with `hw-backend-haptics=treble`, the vibrator HAL (`br_haptic_open_as`), a worker thread, the iOS-to-effect mapping, the counters (`haptics: effect N played`, `haptics: counters:`) and the stand-in actuator of xnuhost's `haptics=sim` (a boot with no vibrator) | +| `haptics/` | evdev force feedback (`sec_vibrator_inputff`) or, with `hw-backend-haptics=treble`, the vibrator HAL (`br_haptic_open_as`), a worker thread, the iOS-to-effect mapping, the counters (`haptics: effect N played`, `haptics: counters:`) and the stand-in actuator of xnuhost's `haptics=sim` (a boot with no vibrator). Native impacts (off by default): with `ONEIOS_HAPTIC_NATIVE_IMPACTS=1` and TICK/CLICK/HEAVY_CLICK presets advertised, an explicit `OB_HAPTIC_IMPACT` plays the matching `IVibrator.perform()` preset (`docs/hardware.md` 5); the guest opts in with `oneios_native_impacts=1` | | `net/` | the old route, only with xnuhost's `wifi=tap`: tap back end, the built-in DHCP answer, `oneios-net.sh` (routing and NAT, root) | | `wifi/` | the phone's Wi-Fi for iOS (`docs/hardware.md` section 3): wlan0 is the guest's en0. `frames.c` (which frames cross, coalesced frames cut), `station.c` (the guest driver's station messages, `drivers/net/oneios_wifi_proto.h`), `sim.c` (a made-up radio, xnuhost's `wifi=sim`), `wlan.c` (AF_PACKET, nl80211 scans and signal, wlan0's settings kept and given back; three threads), `supplicant.c` (joins through the vendor's wpa_supplicant), `aidl_parcel.c` + `aidl_binder.c` (stable AIDL over `/dev/binder` without Android libraries) | | `bt/` | the Bluetooth HAL (HIDL 1.0/1.1) over `/dev/hwbinder` without Android libraries (two threads: one answers the HAL's callbacks, one makes the calls from a queue, so a vCPU never waits on the HAL); packet checks; `br_hci_hidl_probe` for xnuhost's start; `hci_sim.c`: the stand-in controller of `bluetooth=sim` (a boot with no phone): Command Complete with a 5.4 controller's return parameters for every command (Command Status for the ones answered that way), Unknown HCI Command for vendor commands, one made-up device ("OneiOS sim") heard by an LE scan, data dropped; `test_bridges.c` checks its answers | diff --git a/runtime/bridges/devices/bridge_dev.c b/runtime/bridges/devices/bridge_dev.c index 096d2a54..515b8547 100644 --- a/runtime/bridges/devices/bridge_dev.c +++ b/runtime/bridges/devices/bridge_dev.c @@ -127,7 +127,12 @@ static void from_guest(bridge_state *s, const struct ob_header *h, const uint8_t (s->config.brightness ? 1u << OB_CH_BRIGHTNESS : 0) | (s->config.battery ? 1u << OB_CH_BATTERY : 0) | (s->config.thermal ? 1u << OB_CH_THERMAL : 0) }; - to_guest(s, OB_CH_CONTROL, OB_CTL_HELLO, &hello, sizeof hello); + if (br_haptic_impacts_available(s->config.haptic)) { + struct ob_ctl_hello_ext ext = { hello.version, hello.channels, OB_FEAT_HAPTIC_IMPACT }; + to_guest(s, OB_CH_CONTROL, OB_CTL_HELLO, &ext, sizeof ext); + } else { + to_guest(s, OB_CH_CONTROL, OB_CTL_HELLO, &hello, sizeof hello); + } } break; case OB_CH_HAPTIC: @@ -136,6 +141,15 @@ static void from_guest(bridge_state *s, const struct ob_header *h, const uint8_t memcpy(&vib, payload, sizeof vib); br_haptic_vib(s->config.haptic, vib.on_ms, vib.intensity, vib.frequency_hz); } else if (h->type == OB_HAPTIC_STOP) br_haptic_stop(s->config.haptic); + else if (h->type == OB_HAPTIC_IMPACT && + h->length == sizeof(struct ob_haptic_impact) && + br_haptic_impacts_available(s->config.haptic)) { + struct ob_haptic_impact impact; + memcpy(&impact, payload, sizeof impact); + if (impact.kind >= OB_IMPACT_LIGHT && impact.kind <= OB_IMPACT_HEAVY) + (void)br_haptic_impact(s->config.haptic, impact.kind); + // Malformed/unsupported impacts are never silently mapped to VIB. + } break; case OB_CH_HCI: if (!s->config.hci_factory) break; diff --git a/runtime/bridges/hal/hal.h b/runtime/bridges/hal/hal.h index d8cbd5e1..19093117 100644 --- a/runtime/bridges/hal/hal.h +++ b/runtime/bridges/hal/hal.h @@ -32,6 +32,14 @@ #define HAL_VIB_GET_CAPABILITIES 1u // getCapabilities(): int #define HAL_VIB_OFF 2u // off() #define HAL_VIB_ON 3u // on(int timeoutMs, IVibratorCallback callback): callback null here +#define HAL_VIB_PERFORM 4u // perform(Effect, EffectStrength, IVibratorCallback): duration in ms +#define HAL_VIB_EFFECT_CLICK 0 // android.hardware.vibrator.Effect.CLICK +#define HAL_VIB_EFFECT_TICK 2 // android.hardware.vibrator.Effect.TICK +#define HAL_VIB_EFFECT_HEAVY_CLICK 5 // android.hardware.vibrator.Effect.HEAVY_CLICK +#define HAL_VIB_STRENGTH_LIGHT 0 // android.hardware.vibrator.EffectStrength.LIGHT +#define HAL_VIB_STRENGTH_MEDIUM 1 // android.hardware.vibrator.EffectStrength.MEDIUM +#define HAL_VIB_STRENGTH_STRONG 2 // android.hardware.vibrator.EffectStrength.STRONG +#define HAL_VIB_SUPPORTED_EFFECTS 5u // getSupportedEffects(): Effect[] (read only) #define HAL_VIB_SET_AMPLITUDE 6u // setAmplitude(float 0 < a <= 1) #define HAL_VIB_CAP_AMPLITUDE 4 // IVibrator.CAP_AMPLITUDE_CONTROL diff --git a/runtime/bridges/haptics/haptic.c b/runtime/bridges/haptics/haptic.c index 60ece7e7..e6799859 100644 --- a/runtime/bridges/haptics/haptic.c +++ b/runtime/bridges/haptics/haptic.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #ifdef __linux__ #include @@ -50,6 +51,14 @@ void br_haptic_map(unsigned intensity, unsigned frequency_hz, unsigned *period_m *magnitude = intensity ? LEVEL_FLOOR + (LEVEL_MAX - LEVEL_FLOOR) * intensity / 1000 : 0; } +enum { HREQ_VIB = 1, HREQ_STOP = 2, HREQ_IMPACT = 3 }; +static uint64_t haptic_ms(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000u + (uint64_t)ts.tv_nsec / 1000000u; +} + struct br_haptic { const br_haptic_backend *backend; void *ctx; @@ -58,7 +67,9 @@ struct br_haptic { pthread_cond_t wake, idle; bool quit, pending, busy; uint32_t on_ms; - unsigned intensity, frequency_hz; + unsigned intensity, frequency_hz, impact_kind, request, active_kind; + bool impact_enabled; // HAL preset inventory + explicit opt-in + uint64_t impact_until_ms; // bound off(): never cancel an already-finished native tick int effect; // -1 until the first upload bool playing; unsigned failures; @@ -71,41 +82,99 @@ static void *worker(void *arg) br_haptic *h = arg; pthread_mutex_lock(&h->lock); for (;;) { - while (!h->pending && !h->quit) { h->busy = false; pthread_cond_broadcast(&h->idle); pthread_cond_wait(&h->wake, &h->lock); } + while (!h->pending && !h->quit) { + h->busy = false; + pthread_cond_broadcast(&h->idle); + pthread_cond_wait(&h->wake, &h->lock); + } if (h->quit && !h->pending) break; uint32_t on_ms = h->on_ms; unsigned intensity = h->intensity, frequency = h->frequency_hz; + unsigned request = h->request, kind = h->impact_kind; h->pending = false; h->busy = true; pthread_mutex_unlock(&h->lock); - unsigned period, magnitude; + unsigned period = 0, magnitude = 0, duration = 0; br_haptic_map(intensity, frequency, &period, &magnitude); int rc = 0; + const char *step = "stop"; + int effect_id = h->effect; bool played = false, stopped = false; - if (!on_ms || !magnitude) { - if (h->playing && h->effect >= 0) { rc = h->backend->play(h->ctx, h->effect, false); stopped = rc == 0; } + // HAL preset effects finish by themselves. A later guest STOP must never + // issue off() after the vendor's reported duration, because One UI could + // already be playing a different vibration. + if (h->playing && h->active_kind == HREQ_IMPACT && + haptic_ms() >= h->impact_until_ms) { h->playing = false; + h->active_kind = 0; + } + if (request == HREQ_STOP || (request == HREQ_VIB && (!on_ms || !magnitude))) { + if (h->playing) { + rc = h->backend->play(h->ctx, h->effect < 0 ? 0 : h->effect, false); + stopped = rc == 0; + } + h->playing = false; + h->active_kind = 0; + } else if (request == HREQ_IMPACT) { + step = "native impact"; + if (!h->impact_enabled || !h->backend->impact || + kind < BR_HAPTIC_IMPACT_LIGHT || kind > BR_HAPTIC_IMPACT_HEAVY) rc = -EOPNOTSUPP; + // A continuous buzz is explicitly stopped before the new discrete tap. + if (!rc && h->playing && h->active_kind == HREQ_VIB) { + rc = h->backend->play(h->ctx, h->effect < 0 ? 0 : h->effect, false); + stopped = rc == 0; + if (!rc) { h->playing = false; h->active_kind = 0; } + } + if (!rc) { + rc = h->backend->impact(h->ctx, kind, &duration); + if (!rc && (duration < 1 || duration > 1000)) rc = -EPROTO; + if (!rc) { + h->playing = played = true; + h->active_kind = HREQ_IMPACT; + h->impact_until_ms = haptic_ms() + duration; + } + } } else { - int id = h->backend->upload(h->ctx, h->effect, on_ms > LENGTH_MAX_MS ? LENGTH_MAX_MS : on_ms, period, magnitude); - if (id < 0) rc = id; - else { - h->effect = id; - rc = h->backend->play(h->ctx, id, true); - h->playing = played = rc == 0; + step = "effect upload"; + // Switching from a currently running preset back to a continuous + // waveform cancels that preset; otherwise no spurious off() call. + if (h->playing && h->active_kind == HREQ_IMPACT) { + rc = h->backend->play(h->ctx, h->effect < 0 ? 0 : h->effect, false); + stopped = rc == 0; + if (!rc) { h->playing = false; h->active_kind = 0; } + } + if (!rc) { + int id = h->backend->upload(h->ctx, h->effect, + on_ms > LENGTH_MAX_MS ? LENGTH_MAX_MS : on_ms, period, magnitude); + if (id < 0) rc = id; + else { + h->effect = effect_id = id; + step = "effect play"; + rc = h->backend->play(h->ctx, id, true); + h->playing = played = rc == 0; + h->active_kind = played ? HREQ_VIB : 0; + } } } - if (rc < 0 && h->failures++ < 8) br_log(0, "haptics: request (%u ms, intensity %u) failed: %s", on_ms, intensity, strerror(-rc)); + if (rc < 0 && h->failures++ < 8) + br_log(0, "haptics: %s failed: %s (%u ms, intensity %u, impact %u, period %u ms, level %u, effect id %d)", + step, strerror(-rc), on_ms, intensity, kind, period, magnitude, effect_id); pthread_mutex_lock(&h->lock); if (played) h->stats.played++; if (stopped) h->stats.stopped++; if (rc < 0) h->stats.failed++; uint64_t n = h->stats.played; pthread_mutex_unlock(&h->lock); - // The first effects one by one, then at 16, 32, 64, ...: what reached the force-feedback device. - if (played && (n <= 8 || !(n & (n - 1)))) - br_log(1, "haptics: effect %llu played on %s: %u ms, period %u ms, level %u (intensity %u, %u Hz asked)", (unsigned long long)n, h->name, - on_ms > LENGTH_MAX_MS ? LENGTH_MAX_MS : on_ms, period, magnitude, intensity, frequency); + if (played && (n <= 8 || !(n & (n - 1)))) { + if (request == HREQ_IMPACT) + br_log(1, "haptics: native impact %u played on %s: HAL duration %u ms (effect %llu)", + kind, h->name, duration, (unsigned long long)n); + else + br_log(1, "haptics: effect %llu played on %s: %u ms, period %u ms, level %u (intensity %u, %u Hz asked)", + (unsigned long long)n, h->name, on_ms > LENGTH_MAX_MS ? LENGTH_MAX_MS : on_ms, + period, magnitude, intensity, frequency); + } if (played && n > 8 && !(n & (n - 1))) br_haptic_report(h); pthread_mutex_lock(&h->lock); } @@ -122,11 +191,18 @@ br_haptic *br_haptic_open_backend(const br_haptic_backend *backend, void *ctx) h->backend = backend; h->ctx = ctx; h->effect = -1; + // Custom/fake backends can opt in explicitly. The Treble backend overrides + // this after querying getSupportedEffects() on the real vendor HAL. + const char *opt = getenv("ONEIOS_HAPTIC_NATIVE_IMPACTS"); + h->impact_enabled = backend && backend->impact && opt && !strcmp(opt, "1"); snprintf(h->name, sizeof h->name, "the back end"); pthread_mutex_init(&h->lock, NULL); pthread_cond_init(&h->wake, NULL); pthread_cond_init(&h->idle, NULL); - if (backend->gain) (void)backend->gain(ctx, 10000); + if (backend->gain) { + int rc = backend->gain(ctx, 10000); + if (rc < 0) br_log(0, "haptics: initial gain setting failed: %s", strerror(-rc)); + } if (pthread_create(&h->thread, NULL, worker, h)) { free(h); return NULL; } return h; } @@ -146,9 +222,9 @@ void br_haptic_report(br_haptic *h) if (!h) return; br_haptic_stats_get(h, &s); br_log(1, "haptics: counters: %llu requests from the guest (%llu vibrate, %llu stop; %llu replaced before they started), " - "%llu effects played, %llu stopped, %llu failed on %s", (unsigned long long)(s.vib + s.stop), (unsigned long long)s.vib, + "%llu effects played, %llu stopped, %llu failed on %s (%llu discrete impacts)", (unsigned long long)(s.vib + s.stop + s.impacts), (unsigned long long)s.vib, (unsigned long long)s.stop, (unsigned long long)s.replaced, (unsigned long long)s.played, (unsigned long long)s.stopped, - (unsigned long long)s.failed, h->name); + (unsigned long long)s.failed, h->name, (unsigned long long)s.impacts); } // ---- the stand-in actuator (haptics=sim: a PC boot, which has no vibrator) -------------------------------- @@ -179,9 +255,31 @@ void br_haptic_vib(br_haptic *h, uint32_t on_ms, unsigned intensity, unsigned fr if (on_ms) h->stats.vib++; else h->stats.stop++; h->on_ms = on_ms; h->intensity = intensity; h->frequency_hz = frequency_hz; + h->request = on_ms && intensity ? HREQ_VIB : HREQ_STOP; + h->pending = true; + pthread_cond_signal(&h->wake); + pthread_mutex_unlock(&h->lock); +} + +bool br_haptic_impacts_available(br_haptic *h) +{ + return h && h->impact_enabled && h->backend && h->backend->impact; +} + +int br_haptic_impact(br_haptic *h, unsigned kind) +{ + if (!br_haptic_impacts_available(h) || kind < BR_HAPTIC_IMPACT_LIGHT || + kind > BR_HAPTIC_IMPACT_HEAVY) return -EOPNOTSUPP; + pthread_mutex_lock(&h->lock); + if (h->pending) h->stats.replaced++; + h->stats.impacts++; + h->impact_kind = kind; + h->on_ms = 0; + h->request = HREQ_IMPACT; h->pending = true; pthread_cond_signal(&h->wake); pthread_mutex_unlock(&h->lock); + return 0; } void br_haptic_stop(br_haptic *h) { br_haptic_vib(h, 0, 0, 0); } @@ -297,7 +395,13 @@ static br_haptic *open_evdev(const char *dev_dir) { (void)dev_dir; return NULL; // ---- the vibrator HAL back end (treble) ---------------------------------------------------------- // The effect is a length and a level: on(length) then, with amplitude control, setAmplitude(level / 255 x gain), as // AOSP's vibrator service orders them. The period has no place in IVibrator's on(): the HAL plays at its own resonance. -typedef struct { br_hal *hal; int32_t caps; unsigned length_ms, magnitude, gain; } vib_ctx; +typedef struct { + br_hal *hal; + int32_t caps; + unsigned length_ms, magnitude, gain; + uint32_t preset_mask; // validated at open, only with explicit opt-in + bool native_requested, native_enabled, continuous; // opt-in inspection must never emit an unused off() +} vib_ctx; static int vib_simple(vib_ctx *v, uint32_t code) { @@ -317,12 +421,17 @@ static int vib_play(void *ctx, int id, bool on) { vib_ctx *v = ctx; (void)id; - if (!on) return vib_simple(v, HAL_VIB_OFF); + if (!on) { + int rc = vib_simple(v, HAL_VIB_OFF); + if (!rc) v->continuous = false; + return rc; + } ab_parcel p; br_hal_parcel(&p, HAL_VIBRATOR); ab_put_i32(&p, (int32_t)v->length_ms); ab_put_null_binder(&p); // no callback: the worker does not wait for the end int rc = br_hal_call(v->hal, HAL_VIB_ON, &p, NULL, NULL); + if (!rc) v->continuous = true; // even if a later setAmplitude() fails if (rc || !(v->caps & HAL_VIB_CAP_AMPLITUDE)) return rc; float amplitude = (float)v->magnitude / (float)LEVEL_MAX * (float)v->gain / 10000.0f; if (amplitude > 1.0f) amplitude = 1.0f; @@ -331,15 +440,65 @@ static int vib_play(void *ctx, int id, bool on) ab_put_float(&p, amplitude); return br_hal_call(v->hal, HAL_VIB_SET_AMPLITUDE, &p, NULL, NULL); } +static int vib_take_i32(void *ctx, ab_reader *r) +{ + *(int32_t *)ctx = ab_get_i32(r); + return r->bad ? -EPROTO : 0; +} + +static int vib_take_effects(void *ctx, ab_reader *r) +{ + uint32_t *mask = ctx; + int32_t n = ab_get_i32(r); + if (r->bad || n < 0 || n > 32) return -EPROTO; + for (int32_t i = 0; i < n; ++i) { + int32_t e = ab_get_i32(r); + if (e >= 0 && e < 32) *mask |= 1u << e; + } + return r->bad ? -EPROTO : 0; +} + +// Explicit one-shot impact: the calibrated vendor preset is separate from +// the legacy duration/frequency path. No EVIOCSFF or Samsung trigger indices. +static int vib_impact(void *ctx, unsigned kind, unsigned *duration_ms) +{ + vib_ctx *v = ctx; + if (!v->native_enabled) return -EOPNOTSUPP; + int32_t effect, strength; + switch (kind) { + case BR_HAPTIC_IMPACT_LIGHT: effect = HAL_VIB_EFFECT_TICK; strength = HAL_VIB_STRENGTH_LIGHT; break; + case BR_HAPTIC_IMPACT_MEDIUM: effect = HAL_VIB_EFFECT_CLICK; strength = HAL_VIB_STRENGTH_MEDIUM; break; + case BR_HAPTIC_IMPACT_HEAVY: effect = HAL_VIB_EFFECT_HEAVY_CLICK; strength = HAL_VIB_STRENGTH_STRONG; break; + default: return -EINVAL; + } + if (!(v->preset_mask & (1u << effect))) return -EOPNOTSUPP; + ab_parcel p; + br_hal_parcel(&p, HAL_VIBRATOR); + ab_put_i32(&p, effect); + ab_put_i32(&p, strength); + ab_put_null_binder(&p); + int32_t duration = -1; + int rc = br_hal_call(v->hal, HAL_VIB_PERFORM, &p, vib_take_i32, &duration); + if (rc) return rc; + if (duration < 1 || duration > 1000) return -EPROTO; + *duration_ms = (unsigned)duration; + return 0; +} static int vib_gain(void *ctx, unsigned gain) { ((vib_ctx *)ctx)->gain = gain > 10000 ? 10000 : gain; return 0; } static void vib_close(void *ctx) { vib_ctx *v = ctx; - (void)vib_simple(v, HAL_VIB_OFF); + // Keep legacy shutdown behavior when native mode was not requested. + // During explicit native opt-in, closing an unused or completed bridge + // must NOT send off(): One UI could currently own the same actuator. + // A continuous on(ms) started by this bridge still needs to be stopped. + if (!v->native_requested || v->continuous) (void)vib_simple(v, HAL_VIB_OFF); br_hal_close(v->hal); free(v); } -static const br_haptic_backend hal_backend = { .upload = vib_upload, .play = vib_play, .gain = vib_gain, .close = vib_close }; +static const br_haptic_backend hal_backend = { + .upload = vib_upload, .play = vib_play, .gain = vib_gain, .impact = vib_impact, .close = vib_close +}; static int take_caps(void *ctx, ab_reader *r) { *(int32_t *)ctx = ab_get_i32(r); return r->bad ? -EPROTO : 0; } @@ -356,9 +515,29 @@ static br_haptic *open_hal(const char *binder, char *why, size_t size) int rc = br_hal_call(v->hal, HAL_VIB_GET_CAPABILITIES, &p, take_caps, &v->caps); if (rc) { snprintf(why, size, "%s: getCapabilities: %s", HAL_VIBRATOR_INSTANCE, br_hal_error(rc)); br_hal_close(v->hal); free(v); return NULL; } int32_t version = br_hal_version(v->hal); + const char *opt = getenv("ONEIOS_HAPTIC_NATIVE_IMPACTS"); + v->native_requested = opt && !strcmp(opt, "1"); + if (v->native_requested) { + uint32_t mask = 0; + br_hal_parcel(&p, HAL_VIBRATOR); + rc = br_hal_call(v->hal, HAL_VIB_SUPPORTED_EFFECTS, &p, vib_take_effects, &mask); + const uint32_t required = (1u << HAL_VIB_EFFECT_TICK) | + (1u << HAL_VIB_EFFECT_CLICK) | + (1u << HAL_VIB_EFFECT_HEAVY_CLICK); + if (!rc && (mask & required) == required) { + v->preset_mask = mask; + v->native_enabled = true; + } else { + br_log(0, "haptics: native impacts unavailable: %s (supported preset mask %#x), continuous path unchanged", + rc ? br_hal_error(rc) : "not all TICK/CLICK/HEAVY_CLICK presets advertised", mask); + } + } br_haptic *h = br_haptic_open_backend(&hal_backend, v); if (!h) { br_hal_close(v->hal); free(v); snprintf(why, size, "no worker thread"); return NULL; } + h->impact_enabled = v->native_enabled; snprintf(h->name, sizeof h->name, "the vibrator HAL"); + if (h->impact_enabled) + br_log(1, "haptics: native impacts enabled (explicit opt-in; TICK/CLICK/HEAVY_CLICK preflight PASS)"); br_log(1, "haptics: on: the vibrator HAL %s (version %d, capabilities 0x%x: %s; level %u..%u as the amplitude)", HAL_VIBRATOR_INSTANCE, version, (unsigned)v->caps, v->caps & HAL_VIB_CAP_AMPLITUDE ? "amplitude control" : "no amplitude control, every effect at the HAL's own strength", LEVEL_FLOOR, LEVEL_MAX); return h; diff --git a/runtime/bridges/include/bridges/bridges.h b/runtime/bridges/include/bridges/bridges.h index 37d006f6..ab5a07c9 100644 --- a/runtime/bridges/include/bridges/bridges.h +++ b/runtime/bridges/include/bridges/bridges.h @@ -104,6 +104,9 @@ typedef struct { int (*upload)(void *ctx, int id, unsigned length_ms, unsigned period_ms, unsigned magnitude); int (*play)(void *ctx, int id, bool on); int (*gain)(void *ctx, unsigned gain); // 0..10000 (Samsung's scale) + // An EXPLICIT single impact, not a 20/50ms fragment of a long vibration. + // 0 and duration_ms (1..1000), or a negative errno. NULL: unsupported. + int (*impact)(void *ctx, unsigned kind, unsigned *duration_ms); void (*close)(void *ctx); } br_haptic_backend; @@ -121,6 +124,12 @@ br_haptic *br_haptic_open_backend(const br_haptic_backend *backend, void *ctx); // Never blocks: the newest request replaces one that has not started. void br_haptic_vib(br_haptic *h, uint32_t on_ms, unsigned intensity, unsigned frequency_hz); void br_haptic_stop(br_haptic *h); +// Explicit semantic impact events, using the same host-side queue as VIB and STOP. +// Only offered after opt-in and a successful native HAL preset inventory. +// LIGHT/medium mappings are experimental; only HEAVY has a tactile S26 acceptance. +enum { BR_HAPTIC_IMPACT_LIGHT = 1, BR_HAPTIC_IMPACT_MEDIUM = 2, BR_HAPTIC_IMPACT_HEAVY = 3 }; +bool br_haptic_impacts_available(br_haptic *h); +int br_haptic_impact(br_haptic *h, unsigned kind); // Waits until the worker has carried out everything asked so far (tests, shutdown). void br_haptic_flush(br_haptic *h); // Logs the counter line and stops the motor. @@ -130,7 +139,7 @@ br_haptic *br_haptic_open_sim(void); // What reached this side: requests from the guest (vibrate, stop, and those a newer one replaced before the worker // started them) and what the device then did. br_haptic_report logs them as one "haptics: counters:" line; the // worker also logs the first 8 effects and every power of two after that. -typedef struct { uint64_t vib, stop, replaced, played, stopped, failed; } br_haptic_stats; +typedef struct { uint64_t vib, stop, replaced, played, stopped, failed, impacts; } br_haptic_stats; void br_haptic_stats_get(br_haptic *h, br_haptic_stats *out); void br_haptic_report(br_haptic *h); // The mapping, exposed for tests: iOS intensity/frequency to the effect's parameters. diff --git a/runtime/bridges/tests/fake_hal.c b/runtime/bridges/tests/fake_hal.c index ac3eac54..b5c29c9c 100644 --- a/runtime/bridges/tests/fake_hal.c +++ b/runtime/bridges/tests/fake_hal.c @@ -129,6 +129,45 @@ static int incoming(void *ctx, uint64_t object, uint32_t code, uint32_t flags, a ab_put_i32(reply, caps); return 0; } + // One-shot active preset test. Unlike getters, perform() is logged so + // tests can prove it was called once, with the right parcel and no off(). + case HAL_VIB_PERFORM: { + int32_t effect = ab_get_i32(r), strength = ab_get_i32(r); + uint32_t handle = 0; + uint64_t local = 0; + bool callback = ab_get_binder(r, &handle, &local); + bool click = effect == HAL_VIB_EFFECT_CLICK && strength == HAL_VIB_STRENGTH_MEDIUM; + bool tick = effect == HAL_VIB_EFFECT_TICK && strength == HAL_VIB_STRENGTH_LIGHT; + bool heavy = effect == HAL_VIB_EFFECT_HEAVY_CLICK && strength == HAL_VIB_STRENGTH_STRONG; + if (r->bad || callback || (!click && !heavy && !tick) || + (click && file_text("vibrator_effects_no_click", text, sizeof text)) || + (heavy && file_text("vibrator_effects_no_heavy_click", text, sizeof text))) { + ab_put_service_error(reply, 1); + return 0; + } + note("perform %d %d", effect, strength); + ab_put_ok(reply); + ab_put_i32(reply, heavy ? 60 : tick ? 20 : 20); + return 0; + } + // The supported-effects query. It never actuates (no note()). + case HAL_VIB_SUPPORTED_EFFECTS: + ab_put_ok(reply); + if (file_text("vibrator_effects_no_click", text, sizeof text)) { + ab_put_i32(reply, 2); + ab_put_i32(reply, 2); // TICK + ab_put_i32(reply, 5); // HEAVY_CLICK + } else if (file_text("vibrator_effects_no_heavy_click", text, sizeof text)) { + ab_put_i32(reply, 2); + ab_put_i32(reply, 0); // CLICK + ab_put_i32(reply, 2); // TICK + } else { + ab_put_i32(reply, 3); + ab_put_i32(reply, 0); // CLICK + ab_put_i32(reply, 2); // TICK + ab_put_i32(reply, 5); // HEAVY_CLICK + } + return 0; case HAL_VIB_OFF: note("off"); ab_put_ok(reply); return 0; case HAL_VIB_ON: { int32_t ms = ab_get_i32(r); diff --git a/runtime/bridges/tests/test_bridges.c b/runtime/bridges/tests/test_bridges.c index 427f14d4..a63bd7f9 100644 --- a/runtime/bridges/tests/test_bridges.c +++ b/runtime/bridges/tests/test_bridges.c @@ -4,6 +4,7 @@ #define _GNU_SOURCE #include "bridges/devices.h" #include "oneios_bridge_proto.h" +#include "oneios_actuator.h" #include "../bt/hidl_parcel.h" #include #include @@ -190,7 +191,11 @@ static void test_cpu(const char *tmp) } // ---- haptics ------------------------------------------------------------------------------------- -typedef struct { unsigned uploads, plays, stops, last_length, last_period, last_magnitude, gain; int next_id; } fake_motor; +typedef struct { + unsigned uploads, plays, stops, last_length, last_period, last_magnitude, gain; + unsigned impacts, last_kind, impact_ms; + int next_id; +} fake_motor; static int fm_upload(void *ctx, int id, unsigned length_ms, unsigned period_ms, unsigned magnitude) { fake_motor *m = ctx; @@ -199,7 +204,16 @@ static int fm_upload(void *ctx, int id, unsigned length_ms, unsigned period_ms, } static int fm_play(void *ctx, int id, bool on) { fake_motor *m = ctx; (void)id; if (on) m->plays++; else m->stops++; return 0; } static int fm_gain(void *ctx, unsigned gain) { ((fake_motor *)ctx)->gain = gain; return 0; } -static const br_haptic_backend fake_motor_backend = { .upload = fm_upload, .play = fm_play, .gain = fm_gain }; +static int fm_impact(void *ctx, unsigned kind, unsigned *duration_ms) +{ + fake_motor *m = ctx; + m->impacts++; m->last_kind = kind; + *duration_ms = m->impact_ms ? m->impact_ms : 400; + return 0; +} +static const br_haptic_backend fake_motor_backend = { + .upload = fm_upload, .play = fm_play, .gain = fm_gain, .impact = fm_impact +}; static void test_haptic(void) { @@ -254,6 +268,39 @@ static void test_haptic(void) br_haptic_stats_get(sim, &st); CHECK(st.vib == 20 && st.played == 20 && st.stop == 1 && st.stopped == 1 && st.failed == 0 && st.replaced == 0); br_haptic_close(sim); + + // Explicit native impacts are opt-in and use the same serialized worker. + // One isolated impact is not mapped to repeated VIB segments. + fake_motor impact_motor = { .impact_ms = 400 }; + br_haptic *native = br_haptic_open_backend(&fake_motor_backend, &impact_motor); + CHECK(native != NULL && !br_haptic_impacts_available(native)); + CHECK(br_haptic_impact(native, BR_HAPTIC_IMPACT_HEAVY) == -EOPNOTSUPP); + br_haptic_close(native); + setenv("ONEIOS_HAPTIC_NATIVE_IMPACTS", "1", 1); + native = br_haptic_open_backend(&fake_motor_backend, &impact_motor); + CHECK(native != NULL && br_haptic_impacts_available(native)); + CHECK(br_haptic_impact(native, 999) == -EOPNOTSUPP); + CHECK(br_haptic_impact(native, BR_HAPTIC_IMPACT_HEAVY) == 0); + br_haptic_flush(native); + br_haptic_stats_get(native, &st); + CHECK(impact_motor.impacts == 1 && impact_motor.last_kind == BR_HAPTIC_IMPACT_HEAVY && + impact_motor.plays == 0 && st.vib == 0 && st.stop == 0 && + st.impacts == 1 && st.played == 1 && st.failed == 0); + br_haptic_stop(native); + br_haptic_flush(native); + CHECK(impact_motor.stops == 1); // immediate stop cancels in-flight preset + CHECK(br_haptic_impact(native, BR_HAPTIC_IMPACT_LIGHT) == 0); + br_haptic_flush(native); + br_haptic_stats_get(native, &st); + CHECK(impact_motor.impacts == 2 && impact_motor.last_kind == BR_HAPTIC_IMPACT_LIGHT && + st.impacts == 2 && st.played == 2 && st.failed == 0); + usleep(450000); + br_haptic_stop(native); + br_haptic_flush(native); + CHECK(impact_motor.stops == 1); // completed preset: do not interrupt One UI + br_haptic_close(native); + CHECK(impact_motor.stops == 1); + unsetenv("ONEIOS_HAPTIC_NATIVE_IMPACTS"); } // ---- network ------------------------------------------------------------------------------------- @@ -577,6 +624,10 @@ static void test_bridge_device(const char *tmp) send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_STOP, NULL, 0); br_haptic_flush(haptic); CHECK(motor.stops == 1); + struct ob_haptic_impact ignored = { OB_IMPACT_HEAVY }; + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &ignored, sizeof ignored); + br_haptic_flush(haptic); + CHECK(motor.impacts == 0 && motor.plays == 1); // feature absent => fail closed br_haptic_stats hs; // the guest's two messages (and the device start's stops), as counted br_haptic_stats_get(haptic, &hs); CHECK(hs.vib == 1 && hs.stop >= 1 && hs.played == 1 && hs.stopped == 1 && hs.failed == 0); @@ -644,6 +695,125 @@ static void test_bridge_device(const char *tmp) br_haptic_close(haptic); } +// Exercise the same PCM classifier and impact-kind mapping as oneios_haptic_actuator_play() +// through the real VirtIO queues, not by calling br_haptic_impact() directly. +// 240 mono frames are one 5 ms Actuator period at 48 kHz. The fake motor +// stands in for Android's vibrator HAL and never touches a real device. +static void send_pcm_periods(guest *g, br_haptic *haptic, struct oa_state *actuator, + unsigned periods, int16_t sample) +{ + int16_t samples[240]; + for (unsigned i = 0; i < 240; i++) samples[i] = sample; + for (unsigned p = 0; p < periods; p++) { + struct oa_request request = oa_period(actuator, samples, 240, 1); + if (request.action == OA_IMPACT) { + struct ob_haptic_impact impact = { + .kind = request.intensity <= 250 ? OB_IMPACT_LIGHT : + request.intensity <= 800 ? OB_IMPACT_MEDIUM : OB_IMPACT_HEAVY + }; + send_message(g, OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &impact, sizeof impact); + } else if (request.action == OA_VIB) { + struct ob_haptic_vib vib = { request.ms, (uint16_t)request.intensity, (uint16_t)request.hz }; + send_message(g, OB_CH_HAPTIC, OB_HAPTIC_VIB, &vib, sizeof vib); + } else if (request.action == OA_STOP) { + send_message(g, OB_CH_HAPTIC, OB_HAPTIC_STOP, NULL, 0); + } + if (request.action != OA_NONE) br_haptic_flush(haptic); + } +} + +// A native-impacts-enabled host replies with an extended HELLO without +// changing OB_PROTO_VERSION, and accepts only correctly typed impact payloads. +static void test_bridge_native_impacts(void) +{ + setenv("ONEIOS_HAPTIC_NATIVE_IMPACTS", "1", 1); + fake_motor motor = { .impact_ms = 400 }; + br_haptic *haptic = br_haptic_open_backend(&fake_motor_backend, &motor); + CHECK(haptic && br_haptic_impacts_available(haptic)); + br_bridge_config cfg = { .haptic = haptic }; + xh_virtio *dev = br_bridge_create(0, 41, &cfg); + CHECK(dev != NULL); + guest g; + guest_up(&g, dev, 2, 0); + static uint8_t rx[OB_MAX_MESSAGE]; + post1(&g, OB_QUEUE_RX, rx, sizeof rx, true); + struct ob_ctl_hello request = { OB_PROTO_VERSION, 0 }; + send_message(&g, OB_CH_CONTROL, OB_CTL_HELLO, &request, sizeof request); + CHECK(reap(&g, OB_QUEUE_RX) == (int)(sizeof(struct ob_header) + sizeof(struct ob_ctl_hello_ext))); + struct ob_ctl_hello_ext reply; + memcpy(&reply, rx + sizeof(struct ob_header), sizeof reply); + CHECK(reply.version == OB_PROTO_VERSION && (reply.channels & (1u << OB_CH_HAPTIC)) && + (reply.features & OB_FEAT_HAPTIC_IMPACT)); + + struct ob_haptic_impact impact = { OB_IMPACT_HEAVY }; + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &impact, sizeof impact); + br_haptic_flush(haptic); + CHECK(motor.impacts == 1 && motor.plays == 0 && motor.last_kind == BR_HAPTIC_IMPACT_HEAVY); + impact.kind = 99; + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &impact, sizeof impact); + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_IMPACT, &impact, 2); + br_haptic_flush(haptic); + CHECK(motor.impacts == 1); // invalid kind and truncated payload ignored + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_STOP, NULL, 0); + br_haptic_flush(haptic); + CHECK(motor.stops == 1); // guest STOP cancels the active impact + + // Model the guest's boot arg oneios_native_impacts=1 plus negotiated + // OB_FEAT_HAPTIC_IMPACT. Only an isolated PCM burst becomes a preset. + struct oa_state actuator = { .native_taps = !!(reply.features & OB_FEAT_HAPTIC_IMPACT) }; + CHECK(actuator.native_taps); + send_pcm_periods(&g, haptic, &actuator, 1, 32000); // 5 ms strong pulse + send_pcm_periods(&g, haptic, &actuator, 2, 0); // 10 ms silence: classify + br_haptic_stats st; + br_haptic_stats_get(haptic, &st); + CHECK(motor.impacts == 2 && motor.last_kind == BR_HAPTIC_IMPACT_HEAVY && + motor.uploads == 0 && motor.plays == 0 && st.impacts == 2 && + st.vib == 0 && st.failed == 0); + + // Also validate the low/medium branches of the guest's threshold mapping. + send_pcm_periods(&g, haptic, &actuator, 1, 3200); + send_pcm_periods(&g, haptic, &actuator, 2, 0); + CHECK(motor.impacts == 3 && motor.last_kind == BR_HAPTIC_IMPACT_LIGHT); + send_pcm_periods(&g, haptic, &actuator, 1, 16000); + send_pcm_periods(&g, haptic, &actuator, 2, 0); + CHECK(motor.impacts == 4 && motor.last_kind == BR_HAPTIC_IMPACT_MEDIUM && + motor.uploads == 0 && motor.plays == 0); + + // If the guest did not opt in, the same short PCM must remain a legacy + // duration-based VIB, despite native support being advertised by the host. + struct oa_state legacy = { 0 }; + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_STOP, NULL, 0); + br_haptic_flush(haptic); + send_pcm_periods(&g, haptic, &legacy, 1, 32000); + send_pcm_periods(&g, haptic, &legacy, 2, 0); + br_haptic_stats_get(haptic, &st); + CHECK(motor.impacts == 4 && motor.plays == 1 && st.vib == 1); + + // An opted-in sustained waveform (>=30 ms) must also use the ordinary + // VIB/STOP route, not get misclassified as an impact. + send_message(&g, OB_CH_HAPTIC, OB_HAPTIC_STOP, NULL, 0); + br_haptic_flush(haptic); + struct oa_state sustained = { .native_taps = true }; + send_pcm_periods(&g, haptic, &sustained, 12, 20000); // 60 ms continuous + send_pcm_periods(&g, haptic, &sustained, 2, 0); + br_haptic_stats_get(haptic, &st); + CHECK(motor.impacts == 4 && motor.plays >= 2 && st.vib >= 2 && + st.stop >= 3 && st.failed == 0); + + // Allow a full-second preset so a loaded CI host cannot accidentally + // let the fake effect expire between dispatch and reset. + motor.impact_ms = 1000; + // A guest reset cancels a still-active native impact, with no evdev fallback. + send_pcm_periods(&g, haptic, &actuator, 1, 32000); + send_pcm_periods(&g, haptic, &actuator, 2, 0); + unsigned stops_before_reset = motor.stops; + w32(&g, 0x70, 0); + br_haptic_flush(haptic); + CHECK(motor.impacts == 5 && motor.stops == stops_before_reset + 1); + br_haptic_close(haptic); + unsetenv("ONEIOS_HAPTIC_NATIVE_IMPACTS"); +} + // The battery channel: the hello's bit, the first state on the query, a change pushed by the worker, no more after a reset. static void write_node(const char *dir, const char *name, const char *text) { @@ -992,6 +1162,7 @@ int main(void) test_le_scan(); test_bt_sim(); test_bridge_device(tmp); + test_bridge_native_impacts(); test_bridge_brightness(tmp); test_bridge_battery(tmp); test_net_device(); diff --git a/runtime/bridges/tests/test_hal_binder.c b/runtime/bridges/tests/test_hal_binder.c index a2b2cab8..b5ab7691 100644 --- a/runtime/bridges/tests/test_hal_binder.c +++ b/runtime/bridges/tests/test_hal_binder.c @@ -209,6 +209,39 @@ static void test_haptics(void) h = br_haptic_open_as("/nonexistent", BR_HW_TREBLE, NULL); CHECK(h != NULL && logged("no amplitude control")); if (h) { br_haptic_vib(h, 20, 300, 0); br_haptic_flush(h); CHECK(!strcmp(vib_log(), "on 20\n")); br_haptic_close(h); vib_log(); } + // Explicit native impact mode, never used by default. HAL advertises all + // three standard presets in fake_hal, and perform() is serialized through + // the same worker as ordinary VIB and STOP. + setenv("ONEIOS_HAPTIC_NATIVE_IMPACTS", "1", 1); + put("vibrator", "36\n"); // amplitude + compose + h = br_haptic_open_as("/nonexistent", BR_HW_TREBLE, NULL); + CHECK(h != NULL && br_haptic_impacts_available(h)); + if (h) { + CHECK(br_haptic_impact(h, BR_HAPTIC_IMPACT_HEAVY) == 0); + br_haptic_flush(h); + CHECK(!strcmp(vib_log(), "perform 5 2\n")); + br_haptic_stats st; + br_haptic_stats_get(h, &st); + CHECK(st.impacts == 1 && st.played == 1 && st.failed == 0); + usleep(120000); // fake HAL says 60ms; it finished naturally + br_haptic_stop(h); + br_haptic_flush(h); + CHECK(!strcmp(vib_log(), "")); // no late off() to interrupt One UI + br_haptic_close(h); + CHECK(!strcmp(vib_log(), "")); // no unconditional off() after an impact + } + put("vibrator_effects_no_heavy_click", "1\n"); + h = br_haptic_open_as("/nonexistent", BR_HW_TREBLE, NULL); + CHECK(h && !br_haptic_impacts_available(h)); + if (h) { + CHECK(br_haptic_impact(h, BR_HAPTIC_IMPACT_HEAVY) == -EOPNOTSUPP); + br_haptic_close(h); + CHECK(!strstr(vib_log(), "perform")); + } + char disabled_path[300]; + snprintf(disabled_path, sizeof disabled_path, "%s/vibrator_effects_no_heavy_click", values); + unlink(disabled_path); + unsetenv("ONEIOS_HAPTIC_NATIVE_IMPACTS"); // Not registered: the missing line, off; with the fallback the evdev search (nothing under /nonexistent here). char path[300]; snprintf(path, sizeof path, "%s/vibrator", values); diff --git a/userland/metal/build.sh b/userland/metal/build.sh index 3854bea5..f142a859 100755 --- a/userland/metal/build.sh +++ b/userland/metal/build.sh @@ -66,6 +66,24 @@ stage() { mkdir -p "$R/drivers" "$R/kits" "$R/.cache/gpu-reference" "$R/.cache/mesa-venv/bin" "$R/.cache/mesa-tools/bin" "$R/build" rsync -a --delete "$BASE/scripts/" "$R/scripts/" rsync -a --delete "$BASE/patches/" "$R/patches/" + # This project's extra metal2vulkan patches (userland/metal/patches/metal2vulkan: the Adreno-generic shader + # translation fixes of hakios-arm64e-dada, rebased on the pin): added after the base's own, numbered 9xxx so that + # they sort last. The base's build script is assumed to apply patches/metal2vulkan/*.patch in name order; + # `.github/workflows/gpu-patch-check.yml` checks that they apply to the pin, the build log shows if they did. + if ls "$HERE"/patches/metal2vulkan/*.patch >/dev/null 2>&1; then + mkdir -p "$R/patches/metal2vulkan" + for p in "$HERE"/patches/metal2vulkan/*.patch; do cp "$p" "$R/patches/metal2vulkan/9$(basename "$p")"; done + say "added $(ls "$HERE"/patches/metal2vulkan/*.patch | wc -l) metal2vulkan patches of OneiOS (9xxx)" + fi + # Lasting debug tooling, off by default (each patch only logs when its environment variable is set: + # ONEIOS_VK_INIT, ONEIOS_SURFACE_TRACE): the trace patches staged beside the base's own, applied by the + # python below. Re-running stage is idempotent: the mesa-work copy is applied only once. + cp "$HERE/trace-turnip-init.patch" "$R/patches/mesa/" + if ! git -C "$R/.cache/mesa-work" apply --reverse --check "$HERE/trace-turnip-init.patch" 2>/dev/null; then + git -C "$R/.cache/mesa-work" apply "$HERE/trace-turnip-init.patch" + fi + cp "$HERE/trace-metal-vulkan-init.patch" "$R/patches/metal2vulkan/" + cp "$HERE/trace-metal-surfaces.patch" "$R/patches/" rsync -a --delete --exclude .git "$EXT/NativeMetal/" "$R/drivers/AdrenoMetal/" rsync -a --delete --exclude .git "$EXT/NativeAdreno/" "$R/drivers/Adreno740/" rsync -a --delete --exclude .git "$EXT/NativeMobileDisplay/" "$R/drivers/GopFramebuffer/" @@ -96,6 +114,11 @@ import json, re, sys from pathlib import Path root, hooks, jobs, knows = Path(sys.argv[1]), json.load(open(sys.argv[2])), sys.argv[3], sys.argv[4] == '1' +pins = root / 'scripts/data/adreno-compiler-inputs.json' +source = json.loads(pins.read_text()) +source['patches'].append('patches/mesa/trace-turnip-init.patch') +pins.write_text(json.dumps(source, indent=2) + '\n') + def edit(path, pairs): text = (root / path).read_text() for old, new, why in pairs: @@ -113,10 +136,17 @@ edit('scripts/build-turnip-darwin.py', [ ]) edit('scripts/build-adreno-metal-bridge.py', [ ('timeout=1800)', 'timeout=10800)', 'a longer limit for the fat-LTO Rust build'), + ('\n\ndef git_tree(*steps):', + "\n\nPATCHES.append(ROOT / 'patches/metal2vulkan/trace-metal-vulkan-init.patch')\n\n\ndef git_tree(*steps):", + 'record Vulkan initialization diagnostics in the translator patch stack'), ]) edit('scripts/build-adreno-metal-plugin.py', [ ("subprocess.run(['python3', ROOT / 'scripts/gen-turnip-replay.py'], check=True)\n", '', "no TurnipReplay.h: it is recorded on a Mac's host simulation, and NativeAdrenoUserTest.h includes it only when it exists"), + ('staged_frontend.write_text(frontend)\n', + 'staged_frontend.write_text(frontend)\n' + "subprocess.run(['patch', '-s', '-F', '0', '-d', OUT, '-p1', '-i', ROOT / 'patches/trace-metal-surfaces.patch'], check=True)\n", + 'instrument the frontend after the upstream replacements'), ] + ([ ("'-Wall', '-Wextra', '-Werror',", "'-Wall', '-Wextra', '-Werror', '-Wno-error=unused-but-set-global',", "clang 23's -Wunused-but-set-global (gZeroRest), which Xcode's clang does not have, is not an error"), diff --git a/userland/metal/patches/metal2vulkan/0101-large-indexed-constants-to-blob.patch b/userland/metal/patches/metal2vulkan/0101-large-indexed-constants-to-blob.patch new file mode 100644 index 00000000..a6260d6d --- /dev/null +++ b/userland/metal/patches/metal2vulkan/0101-large-indexed-constants-to-blob.patch @@ -0,0 +1,34 @@ +diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs +index 02a23865..aa6b94b5 100644 +--- a/crates/metal2vulkan/src/memory/plan.rs ++++ b/crates/metal2vulkan/src/memory/plan.rs +@@ -271,6 +271,10 @@ pub struct SharedPlan { + pub bytes: u64, + } + ++/// The most bytes a constant indexed at run time keeps as a `Private` variable; a larger one is read ++/// from the constant blob. ++const PRIVATE_CONSTANT_BYTES: u64 = 4096; ++ + /// Where a program-scope constant lives. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub enum ConstGlobalForm { +@@ -1059,8 +1063,16 @@ impl Planner<'_> { + let closed = !u.merged && !u.escapes && !u.stored && !u.cross_compare && !u.write; + // A type no typed object holds stays `Private`: selection refuses it, as before, + // which only sends a typed object past the room to the blob. +- let form = +- if closed && u.typed && self.fit(global.value_ty, room, m)? != Fit::OverRoom { ++ // A table indexed at run time and past PRIVATE_CONSTANT_BYTES goes to the blob: as a ++ // `Private` variable every thread holds its own copy in scratch memory, which an Adreno ++ // backs per fiber (MercuryPoster's Flocon: 192 KiB of ramp tables a thread, refused). ++ let big = u.indexed ++ && self.layouts.alloc_size(global.value_ty).unwrap_or(0) > PRIVATE_CONSTANT_BYTES; ++ let form = if closed ++ && u.typed ++ && !big ++ && self.fit(global.value_ty, room, m)? != Fit::OverRoom ++ { + ConstGlobalForm::Private + } else { + let align = self.global_align(g, global.value_ty)?; diff --git a/userland/metal/patches/metal2vulkan/0102-blob-constant-gep-pointers.patch b/userland/metal/patches/metal2vulkan/0102-blob-constant-gep-pointers.patch new file mode 100644 index 00000000..fff62452 --- /dev/null +++ b/userland/metal/patches/metal2vulkan/0102-blob-constant-gep-pointers.patch @@ -0,0 +1,42 @@ +diff --git a/crates/metal2vulkan/src/lower/access/blob.rs b/crates/metal2vulkan/src/lower/access/blob.rs +index 1ed5aed3..8052d5a8 100644 +--- a/crates/metal2vulkan/src/lower/access/blob.rs ++++ b/crates/metal2vulkan/src/lower/access/blob.rs +@@ -169,10 +169,36 @@ pub fn blob_ptr(cx: &SelectCx<'_>, v: Value) -> Result { + let Value::Const(c) = v else { + return Ok(LocalPtr::Value(operand(cx, v)?)); + }; ++ blob_const_offset(cx, c).map(LocalPtr::Offset) ++} ++ ++/// The blob offset of pointer constant `c`: a global's address, a pointer cast of one, or a ++/// `getelementptr` constant expression over one at constant indices (Flocon's fragment shaders ++/// hand their helpers `getelementptr (@rampValuesIndex, 0, 0, 0)` and then index from it). ++fn blob_const_offset(cx: &SelectCx<'_>, c: crate::air::ir::ConstId) -> Result { ++ use crate::air::ir::ConstExpr; + match cx.entry.module.consts().get(c).map(|k| &k.value) { + Some(Const::GlobalAddr(g)) => { + let off = global_offset(cx.memory, *g).ok_or_else(refuse)?; +- Ok(LocalPtr::Offset(u32::try_from(off).map_err(|_| refuse())?)) ++ u32::try_from(off).map_err(|_| refuse()) ++ } ++ Some(Const::Expr(ConstExpr::Cast { ++ op: CastOp::Bitcast | CastOp::AddrSpaceCast, ++ ops, ++ })) => blob_const_offset(cx, ops[0]), ++ Some(Const::Expr(ConstExpr::Gep { src_ty, ops, .. })) => { ++ let (base, idx) = ops.split_first().ok_or_else(refuse)?; ++ let base = blob_const_offset(cx, *base)?; ++ let idx: Vec = idx.iter().map(|&i| Value::Const(i)).collect(); ++ let (delta, strides) = crate::memory::provenance::gep_displacement( ++ cx.entry, ++ &cx.memory.layouts, ++ *src_ty, ++ &idx, ++ )?; ++ let delta = delta.filter(|_| strides.is_empty()).ok_or_else(refuse)?; ++ let off = i64::from(base).checked_add(delta).ok_or_else(refuse)?; ++ u32::try_from(off).map_err(|_| refuse()) + } + _ => Err(refuse()), + } diff --git a/userland/metal/patches/metal2vulkan/0103-block-bytes-per-process.patch b/userland/metal/patches/metal2vulkan/0103-block-bytes-per-process.patch new file mode 100644 index 00000000..547e399a --- /dev/null +++ b/userland/metal/patches/metal2vulkan/0103-block-bytes-per-process.patch @@ -0,0 +1,36 @@ +diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs +index 93b2ca98..96182eb3 100644 +--- a/crates/metal2vulkan-runtime/src/memory.rs ++++ b/crates/metal2vulkan-runtime/src/memory.rs +@@ -64,7 +64,22 @@ use std::sync::{Arc, Mutex}; + use std::time::{Duration, Instant}; + + /// The size of a pooled block, at most the device's `maxMemoryAllocationSize`. ++// dada: 8 MiB, not 64: the kernel refuses a 64 MiB buffer to the system's small sandboxed Metal clients (posters, widgets: g2vk8, ++// kIOReturnNoMemory), and every one of them had its first allocation refused. + pub(super) const BLOCK_BYTES: u64 = 64 << 20; ++/// dada: the pooled block's size for this process: `M2V_BLOCK_MB` (the Metal plugin sets 8 for the system's small sandboxed clients, ++/// whose 64 MiB allocations the kernel refuses), else [`BLOCK_BYTES`]. 8 MiB everywhere made every full-screen texture of the render ++/// server (12.6 MB) a dedicated allocation of its own, about 2 ms each (g2vk19: 238 textures in 10 s). ++pub(super) fn block_bytes() -> u64 { ++ static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); ++ *BYTES.get_or_init(|| { ++ std::env::var("M2V_BLOCK_MB") ++ .ok() ++ .and_then(|v| v.parse::().ok()) ++ .filter(|&mb| (1..=256).contains(&mb)) ++ .map_or(BLOCK_BYTES, |mb| mb << 20) ++ }) ++} + + /// The most empty pooled blocks a pool keeps for its next placements ([`Pool::release`]), at + /// most 128 MiB of empty memory a pool. In a pool the encodings place in, one of them is mostly +@@ -1047,7 +1062,7 @@ impl Memory { + .map(|_| Pool::default()) + .collect(), + types, +- block_bytes: BLOCK_BYTES.min(max_allocation.max(1)), ++ block_bytes: block_bytes().min(max_allocation.max(1)), + device_address, + address_types: None, + kept: None, diff --git a/userland/metal/trace-metal-surfaces.patch b/userland/metal/trace-metal-surfaces.patch new file mode 100644 index 00000000..ced6ef2f --- /dev/null +++ b/userland/metal/trace-metal-surfaces.patch @@ -0,0 +1,86 @@ +diff --git a/NativeBridgeMetalFrontend.mm b/NativeBridgeMetalFrontend.mm +--- a/NativeBridgeMetalFrontend.mm ++++ b/NativeBridgeMetalFrontend.mm +@@ -1083,7 +1083,20 @@ + gNoCopyReleased++; + void (^deallocator)(void *,NSUInteger)=(__bridge_transfer void (^)(void *,NSUInteger))context;deallocator(pointer,(NSUInteger)length); + } +-static void releaseSurface(void *context,void *,uint64_t) {gSurfaceImportsReleased++;CFRelease((IOSurfaceRef)context);} ++// These identities belong to NativeMetal, independent of QuartzCore's software ++// wrappers and the host's virtio resource IDs. ++static void traceSurface(const char *event, IOSurfaceRef surface, const void *owner) { ++ static const bool enabled = getenv("ONEIOS_SURFACE_TRACE") != nullptr; ++ if (enabled) ++ fprintf(stderr,"oneios-metal-surface process=%s pid=%d event=%s iosurface=%u object=%p owner=%p\n", ++ getprogname(),getpid(),event,IOSurfaceGetID(surface),static_cast(surface),owner); ++} ++static void releaseSurface(void *context,void *,uint64_t) { ++ IOSurfaceRef surface=(IOSurfaceRef)context; ++ traceSurface("import-release",surface,nullptr); ++ gSurfaceImportsReleased++; ++ CFRelease(surface); ++} + @implementation NBBuffer + - (void)dealloc { + nmb_buffer_release(_handle); +@@ -1130,7 +1143,11 @@ + // held, and its retain count was then read from freed memory (backboardd faulted in this loop on a completion thread). + static void pruneHeldImports(bool all,std::vector &gone) { + for(auto it=gHeldImports.begin();it!=gHeldImports.end();) { +- if(all || CFGetRetainCount(it->second.surface)<=1){gone.push_back(it->second.buffer);it=gHeldImports.erase(it);} ++ if(all || CFGetRetainCount(it->second.surface)<=1){ ++ traceSurface("cache-remove",it->second.surface,(__bridge const void *)it->second.buffer); ++ gone.push_back(it->second.buffer); ++ it=gHeldImports.erase(it); ++ } + else ++it; + } + } +@@ -1182,6 +1199,7 @@ + static void holdImport(uint64_t identity,uint64_t address,uint64_t bytes,NBBuffer *buffer,std::vector &gone) { + pruneHeldImports(false,gone); + gHeldImports[{identity,address,bytes}]={buffer,buffer.importedSurface}; ++ traceSurface("cache-hold",buffer.importedSurface,(__bridge const void *)buffer); + } + static NBBuffer *surfaceBuffer(IOSurfaceRef surface,void *base,size_t bytes) { + struct Key {uint64_t identity,address,bytes;}; +@@ -1194,9 +1212,11 @@ + NBBuffer *buffer=key?[gSurfaceImports objectForKey:key]:nil; + if(buffer){if(key)holdImport(value.identity,value.address,value.bytes,buffer,gone);return buffer;} + // The surface keeps its CPU mapping (the imported pages) until the import is freed. ++ traceSurface("import-retain",surface,gDevice); + NmbBuffer *handle=nmb_buffer_new_no_copy_releasing(gDevice,base,bytes,MTLResourceStorageModeShared,releaseSurface,(void *)CFRetain(surface)); +- if(!handle){CFRelease(surface);NBLOG(@"native-metal: surface import refused: %@",lastError());return nil;} ++ if(!handle){traceSurface("import-refused",surface,gDevice);CFRelease(surface);NBLOG(@"native-metal: surface import refused: %@",lastError());return nil;} + gSurfaceImportsMade++;buffer=[NBBuffer new];buffer.handle=handle;buffer.options=MTLResourceStorageModeShared;buffer.importedSurface=surface; ++ traceSurface("import-created",surface,(__bridge const void *)buffer); + if(key) { + // Associations whose import is gone are pruned whenever the table has doubled since the last pruning; a live one is never evicted. + if(gSurfaceImports.count>=gSurfaceImportsPruned) { +@@ -1306,7 +1326,14 @@ + return true; + } + @implementation NBTexture +-- (void)dealloc {nmb_texture_release(_handle);if(_surface){if(_counted)IOSurfaceDecrementUseCount(_surface);CFRelease(_surface);}} ++- (void)dealloc { ++ nmb_texture_release(_handle); ++ if(_surface){ ++ traceSurface("texture-release",_surface,(__bridge const void *)self); ++ if(_counted)IOSurfaceDecrementUseCount(_surface); ++ CFRelease(_surface); ++ } ++} + - (void)countUse {if(_surface && !_counted && gCountsSurfaceUse){IOSurfaceIncrementUseCount(_surface);_counted=YES;}} + - (MTLTextureType)textureType {return (MTLTextureType)_descriptor.type;} + // The word an argument buffer holds for the texture (MTLArgumentEncoder writes the same); a view has its own. +@@ -4601,7 +4628,9 @@ + NBTexture *texture=planes>=2?textureOnSurface(buffer,d,surface,plane,start-(uintptr_t)base,row):textureOnBuffer(buffer,d,start-(uintptr_t)base,row,true); + if(!texture){refuseSurface(5,surface,d,plane,start-(uintptr_t)base,row);return nil;} + if(gLogTextures)logTexture("iosurface",d,surface,plane,base,start-(uintptr_t)base,row,texture!=nil); +- gSurfaceTextures++;texture.surface=(IOSurfaceRef)CFRetain(surface);[texture countUse];return (id)texture; ++ gSurfaceTextures++;texture.surface=(IOSurfaceRef)CFRetain(surface);[texture countUse]; ++ traceSurface("texture-retain",surface,(__bridge const void *)texture); ++ return (id)texture; + } + // One L line per library made (its source, size and function names), and with /private/var/ngpu/debug/dump-libraries each library made + // from data written beside the journal (libs/-.metallib): RenderBox links a function of a library it builds at run time diff --git a/userland/metal/trace-metal-vulkan-init.patch b/userland/metal/trace-metal-vulkan-init.patch new file mode 100644 index 00000000..91f445e0 --- /dev/null +++ b/userland/metal/trace-metal-vulkan-init.patch @@ -0,0 +1,158 @@ +diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs +--- a/crates/metal2vulkan-runtime/src/device/create.rs ++++ b/crates/metal2vulkan-runtime/src/device/create.rs +@@ -448,6 +448,16 @@ + vk::FALSE + } + ++// Initialization diagnostics are opt-in and do not change the Vulkan result. ++macro_rules! trace_init { ++ ($($arg:tt)*) => { ++ if std::env::var_os("ONEIOS_VK_INIT").is_some() { ++ use std::io::Write as _; ++ let _ = writeln!(std::io::stderr(), "oneios-vk-init pid={} {}", std::process::id(), format_args!($($arg)*)); ++ } ++ }; ++} ++ + /// Whether `entry`'s loader lists `VK_KHR_portability_enumeration`. + pub(super) fn lists_portability(entry: &ash::Entry) -> Result { + lists_instance_extension(entry, ash::khr::portability_enumeration::NAME) +@@ -456,8 +466,9 @@ + /// Whether the loader lists the instance extension `name`. + fn lists_instance_extension(entry: &ash::Entry, name: &CStr) -> Result { + // SAFETY: a global command of a loaded entry. +- let available = +- unsafe { entry.enumerate_instance_extension_properties(None) }.map_err(vulkan)?; ++ let result = unsafe { entry.enumerate_instance_extension_properties(None) }; ++ trace_init!("vkEnumerateInstanceExtensionProperties result={}", result.as_ref().err().map_or(0, |r| r.as_raw())); ++ let available = result.map_err(vulkan)?; + Ok(available + .iter() + .any(|extension| extension.extension_name_as_c_str() == Ok(name))) +@@ -522,8 +533,12 @@ + }; + for path in &tried { + // SAFETY: opening the loader runs its initialization; the runtime assumes nothing else. +- if let Ok(entry) = unsafe { ash::Entry::load_from(path) } { +- return Ok(entry); ++ match unsafe { ash::Entry::load_from(path) } { ++ Ok(entry) => { ++ trace_init!("Vulkan entry path={} loaded", path.display()); ++ return Ok(entry); ++ } ++ Err(err) => trace_init!("Vulkan entry path={} error={err}", path.display()), + } + } + Err(Error::LoaderNotFound(LoaderNotFound { tried })) +@@ -585,7 +600,9 @@ + let extension_names: Vec<*const c_char> = extensions.iter().map(|n| n.as_ptr()).collect(); + let api_version = instance_version(options.instance_api_version, || { + // SAFETY: a global command of a loaded entry. +- let version = unsafe { entry.try_enumerate_instance_version() }.map_err(vulkan)?; ++ let result = unsafe { entry.try_enumerate_instance_version() }; ++ trace_init!("vkEnumerateInstanceVersion result={:?}", result.as_ref().map_err(|r| r.as_raw())); ++ let version = result.map_err(vulkan)?; + // A loader without `vkEnumerateInstanceVersion` is a Vulkan 1.0 loader. + Ok(version.map_or(ApiVersion { major: 1, minor: 0 }, ApiVersion::from_packed)) + })?; +@@ -636,7 +653,10 @@ + let mut dropped: Vec = Vec::new(); + let raw = loop { + // SAFETY: `info` and everything it points at live for the call. +- match unsafe { new_instance(&entry, &info) } { ++ let result = unsafe { new_instance(&entry, &info) }; ++ trace_init!("vkCreateInstance result={} api={}.{} extensions={extensions:?} layers={layers:?}", ++ result.as_ref().err().map_or(0, |r| r.as_raw()), api_version.major, api_version.minor); ++ match result { + Ok(raw) => break raw, + Err(vk::Result::ERROR_INCOMPATIBLE_DRIVER) => return Err(Error::NoDevice), + Err(error) if drops_layers(error, layers) => { +@@ -651,7 +671,9 @@ + (Some(sink), Some(info)) => { + let loader = ash::ext::debug_utils::Instance::new(&entry, &raw); + // SAFETY: the instance enabled `VK_EXT_debug_utils`; the sink lives in the messenger. +- match unsafe { loader.create_debug_utils_messenger(info, None) } { ++ let result = unsafe { loader.create_debug_utils_messenger(info, None) }; ++ trace_init!("vkCreateDebugUtilsMessengerEXT result={}", result.as_ref().err().map_or(0, |r| r.as_raw())); ++ match result { + Ok(handle) => Some(Messenger { + loader, + handle, +@@ -668,7 +690,9 @@ + }; + let relay = if relays { + // SAFETY: the instance is live, from `entry`, and enabled `VK_EXT_debug_utils`. +- match unsafe { super::relay::Messenger::new(&entry, &raw) } { ++ let result = unsafe { super::relay::Messenger::new(&entry, &raw) }; ++ trace_init!("vkCreateDebugUtilsMessengerEXT relay result={}", result.as_ref().err().map_or(0, |r| r.as_raw())); ++ match result { + Ok(relay) => Some(relay), + Err(error) => { + if let Some(messenger) = &messenger { +@@ -732,13 +756,18 @@ + options: &DeviceOptions, + ) -> Result, Error> { + // SAFETY: the instance is live. +- let physical = unsafe { instance.raw.enumerate_physical_devices() }.map_err(vulkan)?; ++ let result = unsafe { instance.raw.enumerate_physical_devices() }; ++ trace_init!("vkEnumeratePhysicalDevices result={} device_count={}", ++ result.as_ref().err().map_or(0, |r| r.as_raw()), result.as_ref().map_or(0, Vec::len)); ++ let physical = result.map_err(vulkan)?; + let mut ranked: Vec<(u8, vk::PhysicalDevice)> = physical + .into_iter() + .filter_map(|physical| { + // SAFETY: `physical` was enumerated from the instance. +- let ty = unsafe { instance.raw.get_physical_device_properties(physical) }.device_type; +- let kind = DeviceKind::of(ty); ++ let properties = unsafe { instance.raw.get_physical_device_properties(physical) }; ++ trace_init!("vkGetPhysicalDeviceProperties device={:?} vendor={:#x} id={:#x} api={:#x} driver={:#x}", ++ properties.device_name_as_c_str(), properties.vendor_id, properties.device_id, properties.api_version, properties.driver_version); ++ let kind = DeviceKind::of(properties.device_type); + (options.kinds.is_empty() || options.kinds.contains(&kind)) + .then_some((kind.preference(), physical)) + }) +@@ -1287,13 +1316,13 @@ + let compile = + metal2vulkan::device::Device::new(enabled.clone(), options.policy).map_err(device_error)?; + // SAFETY: as above. +- let listed: BTreeSet = +- unsafe { instance.raw.enumerate_device_extension_properties(physical) } +- .map_err(vulkan)? +- .iter() +- .filter_map(|extension| extension.extension_name_as_c_str().ok()) +- .map(CStr::to_owned) +- .collect(); ++ let extensions = unsafe { instance.raw.enumerate_device_extension_properties(physical) }; ++ trace_init!("vkEnumerateDeviceExtensionProperties device={:?} result={}", ++ enabled.device_name, extensions.as_ref().err().map_or(0, |r| r.as_raw())); ++ let listed: BTreeSet = extensions.map_err(vulkan)?.iter() ++ .filter_map(|extension| extension.extension_name_as_c_str().ok()) ++ .map(CStr::to_owned) ++ .collect(); + // The runtime's own need, outside the vocabulary, where listed: GPU times on the host's + // clock (`gpu_time.rs`). + let calibration = gpu_time::Extension::among(&listed); +@@ -1474,7 +1503,9 @@ + }) + .collect(); + // At the user-initiated class: MoltenVK compiles its command shaders as it makes the device. +- let raw = enables ++ trace_init!("vkCreateDevice request device={:?} driver_version={:#x} queue_families={taken:?} extensions={:?} features={:?}", ++ enabled.device_name, enabled.driver_version, enables.names().collect::>(), set.features); ++ let result = enables + .with_create_info(&queues, |info| { + let asked = super::compiles::Sent::new(info); + let instance = &instance.raw; +@@ -1483,8 +1514,9 @@ + // waits for it; `physical` is the instance's. + unsafe { instance.create_device(physical, asked.into_inner(), None) } + }) +- }) +- .map_err(vulkan)?; ++ }); ++ trace_init!("vkCreateDevice device={:?} result={}", enabled.device_name, result.as_ref().err().map_or(0, |r| r.as_raw())); ++ let raw = result.map_err(vulkan)?; + // SAFETY: the device was just created: its word is the loader's. + let loader_word = unsafe { LoaderWord::of_device(raw.handle()) }; + let primary = families.get(queue_family as usize); diff --git a/userland/metal/trace-turnip-init.patch b/userland/metal/trace-turnip-init.patch new file mode 100644 index 00000000..123bd602 --- /dev/null +++ b/userland/metal/trace-turnip-init.patch @@ -0,0 +1,136 @@ +diff --git a/src/freedreno/vulkan/tu_knl_darwin_virtgpu.cc b/src/freedreno/vulkan/tu_knl_darwin_virtgpu.cc +--- a/src/freedreno/vulkan/tu_knl_darwin_virtgpu.cc ++++ b/src/freedreno/vulkan/tu_knl_darwin_virtgpu.cc +@@ -25,6 +25,14 @@ + #include "util/os_time.h" + + #define DWV_TUNNEL_MAGIC 0x4e544e4cu ++ ++#define DWV_INIT_LOG(...) do { \ ++ if (getenv("ONEIOS_VK_INIT")) { \ ++ fprintf(stderr, "oneios-vk-init pid=%d Turnip ", getpid()); \ ++ fprintf(stderr, __VA_ARGS__); \ ++ fputc('\n', stderr); \ ++ } \ ++} while (0) + + enum { + DWV_CAPSET_DRM = 6, +@@ -109,9 +117,15 @@ + break; + const struct droidvm_virtgpu_getparam param = {DROIDVM_VIRTGPU_PARAM_DEFAULT_3D}; + struct droidvm_virtgpu_getparam_reply reply = {}; +- if (dwv.selector < 256 && +- vg_call(DROIDVM_VIRTGPU_GETPARAM, ¶m, sizeof(param), &reply, sizeof(reply)) == KERN_SUCCESS) +- answer = reply.value == 1; ++ if (dwv.selector < 256) { ++ kr = vg_call(DROIDVM_VIRTGPU_GETPARAM, ¶m, sizeof(param), &reply, sizeof(reply)); ++ if (kr == KERN_SUCCESS) ++ answer = reply.value == 1; ++ DWV_INIT_LOG("DEFAULT_3D selector=%u status=%#x value=%llu", dwv.selector, kr, ++ (unsigned long long)reply.value); ++ } else { ++ DWV_INIT_LOG("DEFAULT_3D selector probe refused"); ++ } + IOServiceClose(dwv.conn); + dwv.conn = IO_OBJECT_NULL; + return answer; +@@ -221,6 +235,7 @@ + return kIOReturnNotFound; + kern_return_t kr = IOServiceOpen(service, mach_task_self(), DROIDVM_VIRTGPU_OPEN_TYPE, &dwv.conn); + IOObjectRelease(service); ++ DWV_INIT_LOG("DRM native IOServiceOpen type=%#x status=%#x", DROIDVM_VIRTGPU_OPEN_TYPE, kr); + if (kr != KERN_SUCCESS) + return kr; + const uint32_t probe[2] = {DWV_TUNNEL_MAGIC, 0xffffffffu}; +@@ -231,31 +246,46 @@ + kr = kIOReturnNotPermitted; + + pthread_mutex_lock(&dwv.lock); ++ DWV_INIT_LOG("DRM native selector=%u status=%#x", dwv.selector, kr); + const struct droidvm_virtgpu_get_caps get_caps = {DWV_CAPSET_DRM, 0}; +- if (kr == KERN_SUCCESS) ++ if (kr == KERN_SUCCESS) { + kr = vg_call(DROIDVM_VIRTGPU_GET_CAPS, &get_caps, sizeof(get_caps), &dwv.caps, sizeof(dwv.caps)); ++ DWV_INIT_LOG("GET_CAPS status=%#x capset=%u wire=%u msm=%u.%u context_type=%u chip=%#llx gpu=%u gmem=%u priorities=%u", ++ kr, DWV_CAPSET_DRM, dwv.caps.wire_format, dwv.caps.major, dwv.caps.minor, ++ dwv.caps.context_type, (unsigned long long)dwv.caps.chip_id, dwv.caps.gpu_id, ++ dwv.caps.gmem_size, dwv.caps.priorities); ++ } + const struct droidvm_virtgpu_context_init init = {DWV_CAPSET_DRM, 64}; + struct droidvm_virtgpu_context_init_reply context = {}; +- if (kr == KERN_SUCCESS) ++ if (kr == KERN_SUCCESS) { + kr = vg_call(DROIDVM_VIRTGPU_CONTEXT_INIT, &init, sizeof(init), &context, sizeof(context)); ++ DWV_INIT_LOG("CONTEXT_INIT status=%#x context=%u", kr, context.context_id); ++ } + /* The msm shmem: a host blob (blob id 0) the host carves from its pool, where it answers ccmds. */ + const struct droidvm_virtgpu_create_blob shmem = {DROIDVM_VIRTGPU_BLOB_MEM_HOST3D, DROIDVM_VIRTGPU_BLOB_FLAG_MAPPABLE, + DWV_SHMEM_BYTES, 0, 0, 0}; + struct droidvm_virtgpu_create_blob_reply blob = {}; +- if (kr == KERN_SUCCESS) ++ if (kr == KERN_SUCCESS) { + kr = vg_call(DROIDVM_VIRTGPU_CREATE_BLOB, &shmem, sizeof(shmem), &blob, sizeof(blob)); ++ DWV_INIT_LOG("CREATE_BLOB shmem status=%#x resource=%u handle=%u", kr, blob.resource_id, blob.handle); ++ } + const struct droidvm_virtgpu_handle handle = {blob.handle, 0}; + struct droidvm_virtgpu_map_reply map = {}; +- if (kr == KERN_SUCCESS) ++ if (kr == KERN_SUCCESS) { + kr = vg_call(DROIDVM_VIRTGPU_MAP, &handle, sizeof(handle), &map, sizeof(map)); ++ DWV_INIT_LOG("MAP shmem status=%#x", kr); ++ } + if (kr == KERN_SUCCESS) { + dwv.shmem = (volatile uint8_t *)(uintptr_t)map.address; + dwv.shmem_handle = blob.handle; + dwv.seqno = 0; + dwv.va_start = vg_get_param(DWV_MSM_PARAM_VA_START, &kr); +- } +- if (kr == KERN_SUCCESS) ++ DWV_INIT_LOG("MSM_PARAM_VA_START status=%#x value=%#llx", kr, (unsigned long long)dwv.va_start); ++ } ++ if (kr == KERN_SUCCESS) { + dwv.va_size = vg_get_param(DWV_MSM_PARAM_VA_SIZE, &kr); ++ DWV_INIT_LOG("MSM_PARAM_VA_SIZE status=%#x value=%#llx", kr, (unsigned long long)dwv.va_size); ++ } + /* Asking for the fault count is what has drm2kgsl count this context's GPU resets in the shmem's global_faults (GetStatus); + * a host without that answers 0 and counts only refused submissions (async_error). */ + if (kr == KERN_SUCCESS) { +@@ -266,8 +296,10 @@ + * submission rides it, so its fences are one increasing sequence, as the NativeAdreno ABI's are. A Vulkan queue asking for a + * higher priority moves it (dwv_set_priority). */ + struct { uint32_t flags, prio, id; } queue = {0, dwv_priorities() - 1, 0}; +- if (kr == KERN_SUCCESS) ++ if (kr == KERN_SUCCESS) { + kr = vg_ioctl_simple(DWV_MSM_SUBMITQUEUE_NEW, &queue, sizeof(queue)); ++ DWV_INIT_LOG("SUBMITQUEUE_NEW status=%#x", kr); ++ } + if (kr == KERN_SUCCESS) { + dwv.queue_id = queue.id; + dwv.priority = queue.prio; +diff --git a/src/freedreno/vulkan/tu_knl_darwin.cc b/src/freedreno/vulkan/tu_knl_darwin.cc +--- a/src/freedreno/vulkan/tu_knl_darwin.cc ++++ b/src/freedreno/vulkan/tu_knl_darwin.cc +@@ -340,7 +340,10 @@ + static VkResult + dw_open_connection(struct tu_instance *instance) + { +- if (dwv_enabled()) ++ const bool virtgpu = dwv_enabled(); ++ if (getenv("ONEIOS_VK_INIT")) ++ mesa_logi("oneios-vk-init pid=%d Turnip backend=%s", getpid(), virtgpu ? "DRM native" : "legacy NativeAdreno"); ++ if (virtgpu) + return dw_open_virtgpu(instance); + /* TU_DARWIN_SERVICE names the IOKit service (default: the AGX accelerator the original Metal discovery finds), TU_DARWIN_OPEN_TYPE its open + * type (default 0x4147, the type the driver serves to the plugin). NativeAdrenoGpuPublished with type 0 is the unsandboxed direct form. */ +@@ -1902,6 +1905,10 @@ + instance->knl = &darwin_knl_funcs; + + result = tu_physical_device_init(device, instance); ++ if (getenv("ONEIOS_VK_INIT")) ++ mesa_logi("oneios-vk-init pid=%d tu_physical_device_init result=%d chip=%#llx gpu=%u gmem=%u flags=%#x priorities=%u", ++ getpid(), result, (unsigned long long)device->dev_id.chip_id, device->dev_id.gpu_id, ++ device->gmem_size, info->flags, device->submitqueue_priority_count); + /* The enumeration probe only needed the facts; the device takes the slot again in device_init. */ + dw_close_connection(); + if (result != VK_SUCCESS) {