diff --git a/docs/plan-ios-first-session.md b/docs/plan-ios-first-session.md index 84fc2932..9c603550 100644 --- a/docs/plan-ios-first-session.md +++ b/docs/plan-ios-first-session.md @@ -262,7 +262,7 @@ so each candidate needs the same "nobody calls it" proof as a stop. | **1** (done here) | `oneios-tool phone procs`: the process list with CPU and RAM, read only | none: named files are read, nothing is written | unit tests, the stand-in phone; then the three captures of 1.3 on the phone | - | | **2a** (built, section 5b) | the fork's stop loop without 15 `getprop` a second: one long-lived wait on the three properties (a small `propwait` in the runtime: `__system_property_wait`, as `usb.c` reads serials), or the same loop at 1 s | a zygote that starts is stopped up to 1 s later | the fork's script tests; `phone procs`: the fork's group at about 0 % | the old loop | | **2b** (built for `session-mode=takeover`, section 5b) | the switch stops zygote's restart list where no bridge uses it: `cameraserver`, `mediaextractor`, `mediametrics`, `media.tuner`, `perfmond`, `wificond`; then `netd` (after a session's Wi-Fi join without it) and `media` (after one HEIC encode without it) | a kept HAL waits for a stopped service and spins or blocks [U] | stand-in tests of the fork's scripts (the record, the return's starts); a session: `phone procs` before and after, Wi-Fi join, a sound, a photo tile, the return in place | the return starts them; take the name off the list | -| **3a** | `displayctl drm`: the read-only probe of 2.1 step 2, beside One UI | none: no master, nothing set | host test against a stand-in device; one run on the phone | - | +| **3a** (built) | `displayctl drm [PATH]`: the read-only probe of 2.1 step 2, beside One UI (`runtime/display/src/drm_probe.rs`) | none: no master, nothing set | unit tests + `displayctl` test; one run on the phone (`displayctl drm`) | - | | **3b** | the fork's part alone: a session with `display=none` in which the switch stops surfaceflinger and the composer, 60 s, automatic return | the panel stays dark for the session (the dead-man timer and the chord return); the composer or surfaceflinger does not come back: the failsafe reboot | the fork's script tests; one session: `return.log` shows the composer and surfaceflinger started, One UI's screen back | `display=shm` (today's path) stays the default | | **3c** | xnuhost's KMS back end as the probe says (atomic, two buffers, flips), `display=drm` | a dark or wrong picture: return by the chord or the timer; nothing persists | host tests against a stand-in DRM device (vkms in the Linux container [U]); a session: the Apple logo, touch to frame, `display:` lines | `display=shm` | | **3d** | panel power at display off, the real vsync, then the import of the guest's surface (no copy) | as 3c | as 3c, the `display: 10 s` line with 0 rows copied | the copy path | diff --git a/docs/switches.md b/docs/switches.md index a0493546..6a13bc36 100644 --- a/docs/switches.md +++ b/docs/switches.md @@ -28,7 +28,7 @@ a new switch is on the screen with the runtime that has it. xnuhost logs every switch once, after the `versions:` line: ```text -switches: session-mode=hosted stop-loop=wait takeover-reclaim=1 takeover-swappiness=keep task-trim=1 timer-coalesce=1 ram-fit-terms=tasks ram-ondemand=0 uclamp-rule=work gpu-down=governor gpu-blob-entries=65532 wifi-ring-wait=1 wifi-send-wait=1 wifi-buffers=1 wifi-joined-scan=cache encoder-10bit=main10 encoder-warmup=1 display-post=apart display-present=ahb decoder=auto decoder-codecs=h264,hevc,vp9,av1 astc=1 sensors=auto sensors-hz=50 sensors-light=auto oneios-motion=0 oneios-als-spu=0 oneios-wifi-rssi=1 oneios-telemetry-jobs=0 oneios-pool-cut=1 oneios-pressure-big=512 oneios-disable-allowed=1 oneios-nested-exact=1 oneios-upgrade-flush=0 oneios-fill-fast-fault=1 oneios-audio-rt=1 oneios-audio-curve=1 oneios-codec-irq=1 oneios-idle-spares=1 oneios-bo-cache-idle=1 oneios-keep-room=8 oneios-dl-full=1 sheng-vsync-min=60 oneios-compile-s=120 oneios-snapshot-astc=0 oneios-camera-notify=1 oneios-m2v-shader-fix=1 oneios-dont-care=1 oneios-queue-priority=1 (docs/switches.md); all at their defaults +switches: session-mode=hosted stop-loop=wait takeover-reclaim=1 takeover-swappiness=keep task-trim=1 timer-coalesce=1 ram-fit-terms=tasks ram-ondemand=0 uclamp-rule=work gpu-down=governor gpu-kgsl-ui-rb=0 gpu-off-level=1 gpu-blob-entries=65532 wifi-ring-wait=1 wifi-send-wait=1 wifi-buffers=1 wifi-joined-scan=cache encoder-10bit=main10 encoder-warmup=1 display-post=apart display-present=ahb decoder=auto decoder-codecs=h264,hevc,vp9,av1 astc=1 sensors=auto sensors-hz=50 sensors-light=auto oneios-motion=0 oneios-als-spu=0 oneios-wifi-rssi=1 oneios-telemetry-jobs=0 oneios-pool-cut=1 oneios-pressure-big=512 oneios-disable-allowed=1 oneios-nested-exact=1 oneios-upgrade-flush=0 oneios-fill-fast-fault=1 oneios-audio-rt=1 oneios-audio-curve=1 oneios-codec-irq=1 oneios-idle-spares=1 oneios-bo-cache-idle=1 oneios-keep-room=8 oneios-dl-full=1 sheng-vsync-min=60 oneios-compile-s=120 oneios-snapshot-astc=0 oneios-camera-notify=1 oneios-m2v-shader-fix=1 oneios-dont-care=1 oneios-queue-priority=1 (docs/switches.md); all at their defaults ``` When some are changed, the end says which: `not at the default: wifi-send-wait gpu-down`. Kernel switches are read @@ -52,6 +52,8 @@ change (the default value), and whether one has run the other value. | `ram-fit-terms` | `tasks\|old` | `tasks` | tasks: ram=auto's 3b8742a terms (tasks, hold share, 1536 MiB headroom locked); old: the terms before 3b8742a (headroom 768 MiB locked / 1 GiB unlocked, page tables 8 %, no task cost, no hold share; any of those keys given still wins). With `task-trim=0` too this is the v0.1.19 sizing | this build (3b8742a) | tasks: no; old: v0.1.19's sessions | | `uclamp-rule` | `work\|all` | `work` | work: xnuhost alone sets a vCPU thread's uclamp (0 at idle, the released thread's floor, the guest's request); drm2kgsl's animation boost only for the frame's threads; background/utility 0. all: before 03d85ac: drm2kgsl's boost on every started vCPU thread and every iOS thread not background, the cpufreq device sets the vCPU thread's clamp, nothing at idle | 03d85ac + this build | no | | `gpu-down` | `governor\|bottom` | `governor` | governor: the GPU level leaves the top when a frame fits at the governor's clock in a burst (learned ratio); bottom: when it fits at KGSL's lowest clock (before 3b36ff0: on the S24 Ultra it never came down) | 3b36ff0 + this build | bottom: every session up to 21:11 (the GPU at the top all session); governor: no | +| `gpu-kgsl-ui-rb` | `0\|1` | `0` | 0: render server and front app run at KGSL priority 8 (out of Android's 4-7 UI ringbuffer, avoiding tile-memory collisions with One UI; drm2kgsl patch 0011, G5 of `docs/ports-2026-11-25-gpu.md`); 1: priority 4 (in the UI ringbuffer, as before) | `feat/takeover-drm-gpu` | no | +| `gpu-off-level` | `0\|1` | `1` | 1: hold KGSL at `KGSL_CONSTRAINT_PWR_MIN` while iOS's display is off (`brightness::display_on() == false`, drm2kgsl patch 0011, T4 of `docs/ports-2026-11-25-gpu.md`) so standby wakes do not boost the GPU; 0: render server stays at the governor's choice (as before) | `feat/takeover-drm-gpu` | no | | `gpu-blob-entries` | `16384..65532` | `65532` | the most entries of a guest 3D blob the device takes; 16384: the limit before 78c4b86 (an 80 MiB blob of single pages refused; drm2kgsl 0010 keeps that from aborting) | 78c4b86 + this build | no | | `wifi-ring-wait` | `0\|1` | `1` | 1: a frame for iOS that finds its receive ring full waits for the guest's kick (20 ms data, 50 ms the station's own); 0: dropped at once (before cbf97ea) | cbf97ea + this build | 1: 2026-11-23 19:40 | | `wifi-send-wait` | `0\|1` | `1` | 1: a frame of iOS's that finds wlan0's send buffer full waits (256 at most, 20 ms); 0: it fails at once (`send failed, last errno 11`, before b704922) | b704922 + this build | 0: 19:40 (the old code); 1: no | @@ -134,6 +136,8 @@ ram-fit-terms=tasks ram-ondemand=0 uclamp-rule=work gpu-down=governor +gpu-kgsl-ui-rb=0 +gpu-off-level=1 gpu-blob-entries=65532 wifi-ring-wait=1 wifi-send-wait=1 diff --git a/runtime/bridges/brightness/mod.rs b/runtime/bridges/brightness/mod.rs index 3182aba3..43878000 100644 --- a/runtime/bridges/brightness/mod.rs +++ b/runtime/bridges/brightness/mod.rs @@ -15,7 +15,7 @@ mod session; #[cfg(test)] pub(crate) mod tests; -pub use session::{AlsFn, AlsSample, Bright, Info, Options, TraceFn}; +pub use session::{display_on, AlsFn, AlsSample, Bright, Info, Options, TraceFn}; /// The level scale of the bridge channel (struct ob_bright_set; drivers/brightness/oneios_bl_request.h's /// OBL_FRACTION_FULL). diff --git a/runtime/bridges/brightness/session.rs b/runtime/bridges/brightness/session.rs index 4def5b84..b62db4b4 100644 --- a/runtime/bridges/brightness/session.rs +++ b/runtime/bridges/brightness/session.rs @@ -10,6 +10,14 @@ use std::os::fd::AsRawFd; use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +/// Whether iOS's display is currently on (updated by [`Bright::display`]). +pub static DISPLAY_ON: AtomicBool = AtomicBool::new(true); + +/// Returns whether iOS's display is currently on. +pub fn display_on() -> bool { + DISPLAY_ON.load(Ordering::Relaxed) +} use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; @@ -615,6 +623,7 @@ impl Bright { /// off when nothing has set another, then the IC woken. A level of 0 alone does neither: it is a dim panel, not an /// off one. pub fn display(&self, on: bool, why: Option<&str>) { + DISPLAY_ON.store(on, Ordering::Relaxed); { let mut s = lock(&self.panel.state); let was = s.display_on; diff --git a/runtime/display/README.md b/runtime/display/README.md index 8a4aca54..cdee201f 100644 --- a/runtime/display/README.md +++ b/runtime/display/README.md @@ -300,6 +300,8 @@ adb shell su -c '/data/local/tmp/oneios-display-test/displayctl test -- --datasp adb shell su -c '/data/local/tmp/oneios-display-test/displayctl test --seconds 20 --format rgba16f' # what surfaceflinger has while it runs (second shell) adb shell su -c 'dumpsys SurfaceFlinger --list' | grep OneiOS +# read-only DRM/KMS probe (stage 3a of docs/plan-ios-first-session.md; no master, nothing set) +adb shell su -c '/data/local/tmp/oneios-display-test/displayctl drm' # clean up adb shell su -c 'rm -rf /data/local/tmp/oneios-display-test' ``` diff --git a/runtime/display/src/bin/displayctl.rs b/runtime/display/src/bin/displayctl.rs index 8f99ee22..a8aa0103 100644 --- a/runtime/display/src/bin/displayctl.rs +++ b/runtime/display/src/bin/displayctl.rs @@ -119,7 +119,7 @@ impl Pattern { fn usage() -> ExitCode { eprintln!( - "usage: displayctl test [--seconds N] [--size WxH] [--format bgrx|rgba16f] [--helper PATH] [-- helper options]" + "usage: displayctl test [--seconds N] [--size WxH] [--format bgrx|rgba16f] [--helper PATH] [-- helper options]\n displayctl drm [PATH]" ); ExitCode::from(2) } @@ -218,8 +218,28 @@ fn mkdtemp(template: &str) -> Result { Ok(PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())) } +fn run_drm(args: &[String]) -> ExitCode { + if args.len() > 3 { + return usage(); + } + let path = args.get(2).map(String::as_str).unwrap_or("/dev/dri/card0"); + match oneios_display::drm_probe::probe(path) { + Ok(report) => { + print!("{report}"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("displayctl drm: {e}"); + ExitCode::from(1) + } + } +} + fn main() -> ExitCode { let args: Vec = std::env::args().collect(); + if args.get(1).map(String::as_str) == Some("drm") { + return run_drm(&args); + } let o = match parse(&args) { Ok(o) => o, Err(code) => return code, diff --git a/runtime/display/src/drm_probe.rs b/runtime/display/src/drm_probe.rs new file mode 100644 index 00000000..e0e0ddb3 --- /dev/null +++ b/runtime/display/src/drm_probe.rs @@ -0,0 +1,554 @@ +// SPDX-License-Identifier: MIT +//! Read-only DRM/KMS probe (`displayctl drm`, stage 3a of `docs/plan-ios-first-session.md`): inspects `/dev/dri/card0` +//! (or a named node) beside One UI without taking DRM master or changing any state. Reports driver version, dumb +//! buffer capability, universal planes / atomic support, connectors and their modes (including whether 1440x3120@120 +//! is present), CRTCs, planes (type, formats, possible CRTCs), and property names/values. + +/// Mode flags/types from ``. +pub const MODE_TYPE_PREFERRED: u32 = 1 << 3; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct ModeInfo { + pub clock: u32, + pub hdisplay: u16, + pub hsync_start: u16, + pub hsync_end: u16, + pub htotal: u16, + pub hskew: u16, + pub vdisplay: u16, + pub vsync_start: u16, + pub vsync_end: u16, + pub vtotal: u16, + pub vscan: u16, + pub vrefresh: u32, + pub flags: u32, + pub kind: u32, + pub name: [u8; 32], +} + +/// Computes refresh rate in Hz from `vrefresh` or pixel clock and totals. +pub fn mode_hz(clock_khz: u32, htotal: u16, vtotal: u16, vrefresh: u32) -> u32 { + if vrefresh != 0 { + return vrefresh; + } + let total = htotal as u64 * vtotal as u64; + if total == 0 { + return 0; + } + ((clock_khz as u64 * 1000 + total / 2) / total) as u32 +} + +/// Formats a DRM `ModeInfo` as a human-readable line. +pub fn format_mode(m: &ModeInfo) -> String { + let hz = mode_hz(m.clock, m.htotal, m.vtotal, m.vrefresh); + let end = m.name.iter().position(|&b| b == 0).unwrap_or(m.name.len()); + let name = String::from_utf8_lossy(&m.name[..end]); + let pref = if m.kind & MODE_TYPE_PREFERRED != 0 { " preferred" } else { "" }; + format!("{}x{}@{} ({}, clock {} kHz, flags {:#x}{})", m.hdisplay, m.vdisplay, hz, name, m.clock, m.flags, pref) +} + +/// Decodes a DRM FourCC code into a 4-character string or hex fallback. +pub fn fourcc_name(fourcc: u32) -> String { + let bytes = fourcc.to_le_bytes(); + if bytes.iter().all(|&b| b.is_ascii_graphic() || b == b' ') { + String::from_utf8_lossy(&bytes).into_owned() + } else { + format!("{fourcc:#010x}") + } +} + +/// Human-readable DRM connector type name (`DRM_MODE_CONNECTOR_*`). +pub fn connector_type_name(t: u32) -> &'static str { + match t { + 0 => "Unknown", + 1 => "VGA", + 2 => "DVII", + 3 => "DVID", + 4 => "DVIA", + 5 => "Composite", + 6 => "SVIDEO", + 7 => "LVDS", + 8 => "Component", + 9 => "9PinDIN", + 10 => "DisplayPort", + 11 => "HDMIA", + 12 => "HDMIB", + 13 => "TV", + 14 => "eDP", + 15 => "VIRTUAL", + 16 => "DSI", + 17 => "DPI", + 18 => "Writeback", + 19 => "SPI", + 20 => "USB", + _ => "Other", + } +} + +/// Human-readable DRM connector status (`drm_mode_connection`). +pub fn connection_name(c: u32) -> &'static str { + match c { + 1 => "connected", + 2 => "disconnected", + _ => "unknown", + } +} + +/// Human-readable DRM plane `type` property value. +pub fn plane_type_name(v: u64) -> &'static str { + match v { + 0 => "Overlay", + 1 => "Primary", + 2 => "Cursor", + _ => "Unknown", + } +} + +#[cfg(any(target_os = "linux", target_os = "android"))] +mod linux { + use super::{connection_name, connector_type_name, format_mode, fourcc_name, mode_hz, plane_type_name, ModeInfo}; + use std::ffi::CString; + use std::fmt::Write as _; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; + use xh_core::ioctl::{ioctl, iow, iowr}; + + const DRM_IOCTL_VERSION: u32 = iowr(b'd', 0x00, std::mem::size_of::()); + const DRM_IOCTL_GET_CAP: u32 = iowr(b'd', 0x0c, std::mem::size_of::()); + const DRM_IOCTL_SET_CLIENT_CAP: u32 = iow(b'd', 0x0d, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETRESOURCES: u32 = iowr(b'd', 0xa0, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETCRTC: u32 = iowr(b'd', 0xa1, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETCONNECTOR: u32 = iowr(b'd', 0xa7, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETPROPERTY: u32 = iowr(b'd', 0xaa, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETPLANERESOURCES: u32 = iowr(b'd', 0xb5, std::mem::size_of::()); + const DRM_IOCTL_MODE_GETPLANE: u32 = iowr(b'd', 0xb6, std::mem::size_of::()); + const DRM_IOCTL_MODE_OBJ_GETPROPERTIES: u32 = iowr(b'd', 0xb9, std::mem::size_of::()); + + const DRM_CAP_DUMB_BUFFER: u64 = 0x1; + const DRM_CAP_TIMESTAMP_MONOTONIC: u64 = 0x6; + const DRM_CLIENT_CAP_UNIVERSAL_PLANES: u64 = 2; + const DRM_CLIENT_CAP_ATOMIC: u64 = 3; + const DRM_MODE_OBJECT_CRTC: u32 = 0xcccccccc; + const DRM_MODE_OBJECT_PLANE: u32 = 0xeeeeeeee; + + #[repr(C)] + #[derive(Default)] + struct Version { + version_major: i32, + version_minor: i32, + version_patchlevel: i32, + name_len: usize, + name: u64, + date_len: usize, + date: u64, + desc_len: usize, + desc: u64, + } + + #[repr(C)] + #[derive(Default)] + struct GetCap { + capability: u64, + value: u64, + } + + #[repr(C)] + #[derive(Default)] + struct SetClientCap { + capability: u64, + value: u64, + } + + #[repr(C)] + #[derive(Default)] + struct CardRes { + fb_id_ptr: u64, + crtc_id_ptr: u64, + connector_id_ptr: u64, + encoder_id_ptr: u64, + count_fbs: u32, + count_crtcs: u32, + count_connectors: u32, + count_encoders: u32, + min_width: u32, + max_width: u32, + min_height: u32, + max_height: u32, + } + + #[repr(C)] + #[derive(Default)] + struct Connector { + encoders_ptr: u64, + modes_ptr: u64, + props_ptr: u64, + prop_values_ptr: u64, + count_modes: u32, + count_props: u32, + count_encoders: u32, + encoder_id: u32, + connector_id: u32, + connector_type: u32, + connector_type_id: u32, + connection: u32, + mm_width: u32, + mm_height: u32, + subpixel: u32, + pad: u32, + } + + #[repr(C)] + #[derive(Default)] + struct Crtc { + set_connectors_ptr: u64, + count_connectors: u32, + crtc_id: u32, + fb_id: u32, + x: u32, + y: u32, + gamma_size: u32, + mode_valid: u32, + mode: ModeInfo, + } + + #[repr(C)] + #[derive(Default)] + struct PlaneRes { + plane_id_ptr: u64, + count_planes: u32, + } + + #[repr(C)] + #[derive(Default)] + struct Plane { + plane_id: u32, + crtc_id: u32, + fb_id: u32, + possible_crtcs: u32, + gamma_size: u32, + count_format_types: u32, + format_type_ptr: u64, + } + + #[repr(C)] + #[derive(Default)] + struct ObjGetProperties { + props_ptr: u64, + prop_values_ptr: u64, + count_props: u32, + obj_id: u32, + obj_type: u32, + } + + #[repr(C)] + struct GetProperty { + values_ptr: u64, + enum_blob_ptr: u64, + prop_id: u32, + flags: u32, + name: [u8; 32], + count_values: u32, + count_enum_blobs: u32, + } + + impl Default for GetProperty { + fn default() -> Self { + // SAFETY: GetProperty is plain old data; zeroing is valid. + unsafe { std::mem::zeroed() } + } + } + + fn call(fd: RawFd, req: u32, arg: *mut T) -> bool { + // SAFETY: callers pass matching DRM ioctl structs and valid array pointers. + unsafe { ioctl(fd, req, arg) }.is_ok() + } + + fn prop_name(fd: RawFd, prop_id: u32) -> String { + let mut p = GetProperty { prop_id, ..Default::default() }; + if !call(fd, DRM_IOCTL_MODE_GETPROPERTY, &mut p) { + return format!("prop#{prop_id}"); + } + let end = p.name.iter().position(|&b| b == 0).unwrap_or(p.name.len()); + String::from_utf8_lossy(&p.name[..end]).into_owned() + } + + fn open_node(path: &str) -> Result { + let c_path = CString::new(path).map_err(|_| format!("{path}: invalid path"))?; + // SAFETY: c_path is NUL-terminated. + let mut fd = unsafe { libc::open(c_path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) }; + if fd < 0 { + // SAFETY: c_path is NUL-terminated. + fd = unsafe { libc::open(c_path.as_ptr(), libc::O_RDWR | libc::O_CLOEXEC) }; + } + if fd < 0 { + return Err(format!("{path}: {}", std::io::Error::last_os_error())); + } + // SAFETY: fd is a newly opened descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + } + + pub fn probe(path: &str) -> Result { + let fd = open_node(path)?; + let raw = fd.as_raw_fd(); + let mut out = String::new(); + let _ = writeln!(out, "drm: node {path} (read-only, no master)"); + + let mut name_buf = [0u8; 64]; + let mut date_buf = [0u8; 64]; + let mut desc_buf = [0u8; 128]; + let mut ver = Version { + name_len: name_buf.len(), + name: name_buf.as_mut_ptr() as u64, + date_len: date_buf.len(), + date: date_buf.as_mut_ptr() as u64, + desc_len: desc_buf.len(), + desc: desc_buf.as_mut_ptr() as u64, + ..Default::default() + }; + if call(raw, DRM_IOCTL_VERSION, &mut ver) { + let n = &name_buf[..ver.name_len.min(name_buf.len())]; + let d = &date_buf[..ver.date_len.min(date_buf.len())]; + let s = &desc_buf[..ver.desc_len.min(desc_buf.len())]; + let _ = writeln!( + out, + "driver: {} {}.{}.{} ({}, {})", + String::from_utf8_lossy(n).trim_end_matches('\0'), + ver.version_major, + ver.version_minor, + ver.version_patchlevel, + String::from_utf8_lossy(d).trim_end_matches('\0'), + String::from_utf8_lossy(s).trim_end_matches('\0'), + ); + } + + let mut cap_dumb = GetCap { capability: DRM_CAP_DUMB_BUFFER, value: 0 }; + let dumb_ok = call(raw, DRM_IOCTL_GET_CAP, &mut cap_dumb); + let mut cap_mono = GetCap { capability: DRM_CAP_TIMESTAMP_MONOTONIC, value: 0 }; + let mono_ok = call(raw, DRM_IOCTL_GET_CAP, &mut cap_mono); + let univ_ok = call( + raw, + DRM_IOCTL_SET_CLIENT_CAP, + &mut SetClientCap { capability: DRM_CLIENT_CAP_UNIVERSAL_PLANES, value: 1 }, + ); + let atomic_ok = + call(raw, DRM_IOCTL_SET_CLIENT_CAP, &mut SetClientCap { capability: DRM_CLIENT_CAP_ATOMIC, value: 1 }); + let _ = writeln!( + out, + "caps: dumb_buffer={} monotonic_ts={} universal_planes={} atomic={}", + if dumb_ok { cap_dumb.value } else { 0 }, + if mono_ok { cap_mono.value } else { 0 }, + univ_ok as u8, + atomic_ok as u8 + ); + + let mut crtcs = [0u32; 32]; + let mut connectors = [0u32; 32]; + let mut encoders = [0u32; 32]; + let mut res = CardRes { + crtc_id_ptr: crtcs.as_mut_ptr() as u64, + count_crtcs: crtcs.len() as u32, + connector_id_ptr: connectors.as_mut_ptr() as u64, + count_connectors: connectors.len() as u32, + encoder_id_ptr: encoders.as_mut_ptr() as u64, + count_encoders: encoders.len() as u32, + ..Default::default() + }; + if !call(raw, DRM_IOCTL_MODE_GETRESOURCES, &mut res) { + return Err(format!("{path}: GETRESOURCES: {}", std::io::Error::last_os_error())); + } + let _ = writeln!( + out, + "resources: crtcs={} connectors={} encoders={} min={}x{} max={}x{}", + res.count_crtcs, + res.count_connectors, + res.count_encoders, + res.min_width, + res.min_height, + res.max_width, + res.max_height + ); + + for &id in connectors.iter().take((res.count_connectors as usize).min(connectors.len())) { + let mut modes = vec![ModeInfo::default(); 256]; + let mut props = [0u32; 64]; + let mut prop_vals = [0u64; 64]; + let mut conn_encs = [0u32; 16]; + let mut conn = Connector { + connector_id: id, + modes_ptr: modes.as_mut_ptr() as u64, + count_modes: modes.len() as u32, + props_ptr: props.as_mut_ptr() as u64, + prop_values_ptr: prop_vals.as_mut_ptr() as u64, + count_props: props.len() as u32, + encoders_ptr: conn_encs.as_mut_ptr() as u64, + count_encoders: conn_encs.len() as u32, + ..Default::default() + }; + if !call(raw, DRM_IOCTL_MODE_GETCONNECTOR, &mut conn) { + continue; + } + let n_modes = (conn.count_modes as usize).min(modes.len()); + let has_1440_120 = modes[..n_modes].iter().any(|m| { + m.hdisplay == 1440 && m.vdisplay == 3120 && mode_hz(m.clock, m.htotal, m.vtotal, m.vrefresh) == 120 + }); + let _ = writeln!( + out, + "connector {}: {}-{} {} {}x{}mm encoder={} modes={} (1440x3120@120={})", + conn.connector_id, + connector_type_name(conn.connector_type), + conn.connector_type_id, + connection_name(conn.connection), + conn.mm_width, + conn.mm_height, + conn.encoder_id, + conn.count_modes, + if has_1440_120 { "yes" } else { "no" } + ); + for m in &modes[..n_modes] { + let _ = writeln!(out, " mode: {}", format_mode(m)); + } + let n_props = (conn.count_props as usize).min(props.len()); + if n_props > 0 { + let names: Vec = + (0..n_props).map(|i| format!("{}={}", prop_name(raw, props[i]), prop_vals[i])).collect(); + let _ = writeln!(out, " props: {}", names.join(", ")); + } + } + + for &id in crtcs.iter().take((res.count_crtcs as usize).min(crtcs.len())) { + let mut crtc = Crtc { crtc_id: id, ..Default::default() }; + if !call(raw, DRM_IOCTL_MODE_GETCRTC, &mut crtc) { + continue; + } + let mode_str = if crtc.mode_valid != 0 { format_mode(&crtc.mode) } else { "none".into() }; + let _ = writeln!( + out, + "crtc {}: fb={} mode_valid={} mode={}", + crtc.crtc_id, crtc.fb_id, crtc.mode_valid, mode_str + ); + let mut props = [0u32; 64]; + let mut prop_vals = [0u64; 64]; + let mut obj = ObjGetProperties { + obj_id: id, + obj_type: DRM_MODE_OBJECT_CRTC, + props_ptr: props.as_mut_ptr() as u64, + prop_values_ptr: prop_vals.as_mut_ptr() as u64, + count_props: props.len() as u32, + }; + if call(raw, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, &mut obj) { + let n = (obj.count_props as usize).min(props.len()); + if n > 0 { + let names: Vec = + (0..n).map(|i| format!("{}={}", prop_name(raw, props[i]), prop_vals[i])).collect(); + let _ = writeln!(out, " props: {}", names.join(", ")); + } + } + } + + let mut plane_ids = [0u32; 64]; + let mut pres = PlaneRes { plane_id_ptr: plane_ids.as_mut_ptr() as u64, count_planes: plane_ids.len() as u32 }; + if call(raw, DRM_IOCTL_MODE_GETPLANERESOURCES, &mut pres) { + let _ = writeln!(out, "planes: {}", pres.count_planes); + for &pid in plane_ids.iter().take((pres.count_planes as usize).min(plane_ids.len())) { + let mut fmts = [0u32; 64]; + let mut plane = Plane { + plane_id: pid, + format_type_ptr: fmts.as_mut_ptr() as u64, + count_format_types: fmts.len() as u32, + ..Default::default() + }; + if !call(raw, DRM_IOCTL_MODE_GETPLANE, &mut plane) { + continue; + } + let mut props = [0u32; 64]; + let mut prop_vals = [0u64; 64]; + let mut obj = ObjGetProperties { + obj_id: pid, + obj_type: DRM_MODE_OBJECT_PLANE, + props_ptr: props.as_mut_ptr() as u64, + prop_values_ptr: prop_vals.as_mut_ptr() as u64, + count_props: props.len() as u32, + }; + let mut ptype = "Unknown"; + let mut prop_list = Vec::new(); + if call(raw, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, &mut obj) { + let n = (obj.count_props as usize).min(props.len()); + for i in 0..n { + let name = prop_name(raw, props[i]); + if name == "type" { + ptype = plane_type_name(prop_vals[i]); + } + prop_list.push(format!("{name}={}", prop_vals[i])); + } + } + let nf = (plane.count_format_types as usize).min(fmts.len()); + let fmt_names: Vec = fmts[..nf].iter().map(|&f| fourcc_name(f)).collect(); + let _ = writeln!( + out, + "plane {}: type={} crtc={} fb={} possible_crtcs={:#x} formats=[{}]", + plane.plane_id, + ptype, + plane.crtc_id, + plane.fb_id, + plane.possible_crtcs, + fmt_names.join(",") + ); + if !prop_list.is_empty() { + let _ = writeln!(out, " props: {}", prop_list.join(", ")); + } + } + } + Ok(out) + } +} + +/// Probes the DRM/KMS node at `path` (read-only, no master) and returns a formatted report. +pub fn probe(path: &str) -> Result { + #[cfg(any(target_os = "linux", target_os = "android"))] + { + linux::probe(path) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + let _ = path; + Err("displayctl drm requires Linux or Android".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mode_formatting_and_hz() { + assert_eq!(mode_hz(555_000, 1500, 3150, 0), 117); + assert_eq!(mode_hz(0, 0, 0, 120), 120); + let mut name = [0u8; 32]; + name[..9].copy_from_slice(b"1440x3120"); + let m = ModeInfo { + clock: 540_000, + hdisplay: 1440, + vdisplay: 3120, + vrefresh: 120, + kind: MODE_TYPE_PREFERRED, + name, + ..Default::default() + }; + let line = format_mode(&m); + assert!(line.contains("1440x3120@120")); + assert!(line.contains("preferred")); + } + + #[test] + fn names_and_fourcc() { + assert_eq!(fourcc_name(0x3432_5258), "XR24"); + assert_eq!(fourcc_name(0x3432_5241), "AR24"); + assert_eq!(connector_type_name(16), "DSI"); + assert_eq!(connector_type_name(15), "VIRTUAL"); + assert_eq!(connection_name(1), "connected"); + assert_eq!(plane_type_name(0), "Overlay"); + assert_eq!(plane_type_name(1), "Primary"); + assert_eq!(plane_type_name(2), "Cursor"); + assert_eq!(std::mem::size_of::(), 68); + } +} diff --git a/runtime/display/src/lib.rs b/runtime/display/src/lib.rs index 3b5c5603..9a1e8391 100644 --- a/runtime/display/src/lib.rs +++ b/runtime/display/src/lib.rs @@ -6,6 +6,7 @@ //! - [`frame_perf`] (frame_perf.c): bounded frame timing statistics. //! - `jni` (jni.c, feature `jni`, Android only): liboneios-display.so, the native half of OneiOSDisplay.java. //! - the programs: `oneios-display` (launcher.c, src/bin/launcher.rs) and `displayctl` (displayctl.c). +pub mod drm_probe; pub mod frame_perf; pub use xh_core::pixels; // the pixel formats and conversions (include/xnuhost/pixels.h), shared with xnuhost pub mod sys; diff --git a/runtime/display/tests/displayctl.rs b/runtime/display/tests/displayctl.rs index 98eda5be..0c964904 100644 --- a/runtime/display/tests/displayctl.rs +++ b/runtime/display/tests/displayctl.rs @@ -111,6 +111,10 @@ fn test_displayctl(c: &mut Checks, dir: &Path, me: &str) { } let (code, _) = displayctl(dir, &["test", "--format", "rgb565"]); c.check(code == Some(2), "a format it does not make: usage"); + let (code, out) = displayctl(dir, &["drm", "/no/such/card0"]); + c.check(code == Some(1) && out.contains("displayctl drm:"), "drm missing node reports error"); + let (code, out) = displayctl(dir, &["drm", "a", "b"]); + c.check(code == Some(2) && out.contains("usage:"), "drm extra args rejected"); } /// This program as the helper displayctl starts (--socket PATH --wait N): connects, takes the hello, reads flushes diff --git a/runtime/switches/src/lib.rs b/runtime/switches/src/lib.rs index 2c84ed86..396eb695 100644 --- a/runtime/switches/src/lib.rs +++ b/runtime/switches/src/lib.rs @@ -244,6 +244,20 @@ pub const SWITCHES: &[Switch] = &[ "governor: the GPU leaves its top level when a frame fits at the governor's clock, which saves heat. bottom: \ only when it would fit at the lowest clock (before: on the S24 Ultra it stayed at the top).", ), + text( + conf("gpu-kgsl-ui-rb", BOOL, "0", Some("1")), + "GPU", + "Skip Android UI GPU ringbuffer", + "0: the render server and front app run at KGSL priority 8 (out of Android's 4-7 UI ringbuffer, avoiding tile-memory \ + collisions with One UI). 1: priority 4 (in the UI ringbuffer, as before).", + ), + text( + conf("gpu-off-level", BOOL, "1", Some("0")), + "GPU", + "Lowest GPU level when iOS display is off", + "1: hold KGSL at its lowest clock while iOS's display is off so standby wakes do not boost the GPU. 0: leave the \ + render server at the governor's choice (as before).", + ), text( conf("gpu-blob-entries", Kind::Int { min: 16384, max: 65532 }, "65532", Some("16384")), "GPU", diff --git a/runtime/xnuhost/drm2kgsl/oneios_gpu_policy.h b/runtime/xnuhost/drm2kgsl/oneios_gpu_policy.h index 38ec41d2..b41df4d9 100644 --- a/runtime/xnuhost/drm2kgsl/oneios_gpu_policy.h +++ b/runtime/xnuhost/drm2kgsl/oneios_gpu_policy.h @@ -123,9 +123,14 @@ static inline enum og_class og_class_of(const char *name, size_t n, uint8_t hint // fences had no bound, and the class a queue was made with (by name or by role at the context's creation) stays its // priority for good. None takes the first ringbuffer (0-3, Android's compositor's). Every class gets an explicit one, so // the order holds whatever the kernel's default for KGSL_CONTEXT_PRIORITY_UNDEF is. +static inline unsigned og_kgsl_priority_for(enum og_class c, bool ui_rb) +{ + return (c == OG_CLASS_RENDER || c == OG_CLASS_FRONT) && ui_rb ? 4u : 8u; +} + static inline unsigned og_kgsl_priority(enum og_class c) { - return c == OG_CLASS_RENDER || c == OG_CLASS_FRONT ? 4u : 8u; + return og_kgsl_priority_for(c, true); } // ---- whose surfaces another process reads ---------------------------------------------------------------------------- diff --git a/runtime/xnuhost/drm2kgsl/patches/0011-kgsl-ui-rb-and-off-level.patch b/runtime/xnuhost/drm2kgsl/patches/0011-kgsl-ui-rb-and-off-level.patch new file mode 100644 index 00000000..5a3fbe87 --- /dev/null +++ b/runtime/xnuhost/drm2kgsl/patches/0011-kgsl-ui-rb-and-off-level.patch @@ -0,0 +1,59 @@ +--- a/src/drm/drm2kgsl/drm2kgsl_renderer.c ++++ b/src/drm/drm2kgsl/drm2kgsl_renderer.c +@@ -2019,7 +2019,7 @@ + { + struct kgsl_context *kctx = to_kgsl_context(to_drm_context(vctx)); + kctx->oneios_class = cls; +- kctx->oneios_lowest = lowest && cls == OG_CLASS_BACKGROUND; ++ kctx->oneios_lowest = lowest; + } + + void +@@ -2038,6 +2038,13 @@ + { + if (!__atomic_load_n(&g_oneios_driven, __ATOMIC_ACQUIRE)) + oneios_hold_extend(); /* ONEIOS (0008): xnuhost holds the clock itself (drm2kgsl_renderer_set_level) */ ++ if (kctx->oneios_lowest) { ++ if (kctx->constraint_on && kgsl_set_pwr_constraint(kctx->base.fd, drawctxt_id, false)) ++ kctx->constraint_on = false; ++ oneios_lowest_update(kctx, drawctxt_id); ++ return; ++ } ++ oneios_lowest_update(kctx, drawctxt_id); + const bool want = kgsl_constraint_now(kctx); + if (want != kctx->constraint_on && kgsl_set_pwr_constraint(kctx->base.fd, drawctxt_id, want)) { + kctx->constraint_on = want; +@@ -2059,19 +2066,21 @@ + * ONEIOS_GPU_PRIORITY=off: the guest's queue priority as upstream), and a background + * context's queues can carry KGSL's lowest level. A priority this KGSL refuses: the queue is made without one, once said. */ + static int by_class = -1; ++ static int ui_rb = -1; + if (by_class < 0) { + const char *env = getenv("ONEIOS_GPU_PRIORITY"); + by_class = !env || strcmp(env, "off"); ++ const char *rb = getenv("ONEIOS_GPU_KGSL_UI_RB"); ++ ui_rb = rb && !strcmp(rb, "1"); + } +- const bool background = kctx->oneios_class == OG_CLASS_BACKGROUND; +- const uint32_t priority = by_class ? ((og_kgsl_priority(kctx->oneios_class) << KGSL_CONTEXT_PRIORITY_SHIFT) & KGSL_CONTEXT_PRIORITY_MASK) ++ const uint32_t priority = by_class ? ((og_kgsl_priority_for(kctx->oneios_class, ui_rb) << KGSL_CONTEXT_PRIORITY_SHIFT) & KGSL_CONTEXT_PRIORITY_MASK) + : kgsl_priority_flags(prio); + struct kgsl_drawctxt_create req = { + .flags = KGSL_CONTEXT_SAVE_GMEM | + KGSL_CONTEXT_NO_GMEM_ALLOC | + KGSL_CONTEXT_PREAMBLE | + KGSL_CONTEXT_USER_GENERATED_TS | +- (constrained || (by_class && background) ? KGSL_CONTEXT_PWR_CONSTRAINT : 0) | ++ (constrained || by_class ? KGSL_CONTEXT_PWR_CONSTRAINT : 0) | + priority, + }; + +@@ -2165,7 +2174,7 @@ + _drm_log(VIRGL_LOG_LEVEL_WARNING, "context %u: %s\n", id, __atomic_load_n(&g_oneios_driven, __ATOMIC_ACQUIRE) + ? "a deadline queue: at the top level only for frames that would miss their deadline (xnuhost's policy)" + : "constrained while it submits at an animation's rate"); +- const bool lowest = kctx->oneios_class == OG_CLASS_BACKGROUND && (!getenv("ONEIOS_GPU_PRIORITY") || strcmp(getenv("ONEIOS_GPU_PRIORITY"), "off")); ++ const bool lowest = !getenv("ONEIOS_GPU_PRIORITY") || strcmp(getenv("ONEIOS_GPU_PRIORITY"), "off"); + unsigned ring_idx = (MIN2(q->prio, g_nr_timelines - 1) + 1) | + (constrained ? KGSL_RING_IDX_CONSTRAINED : 0) | (lowest && !constrained ? KGSL_RING_IDX_LOWEST : 0); + _mesa_hash_table_insert(kctx->sq_to_ring_idx_table, diff --git a/runtime/xnuhost/src/config.rs b/runtime/xnuhost/src/config.rs index 097073d2..4fc3e1ee 100644 --- a/runtime/xnuhost/src/config.rs +++ b/runtime/xnuhost/src/config.rs @@ -498,6 +498,8 @@ const GIVEN_KEYS: &[&str] = &[ "astc", "gpu-blob-entries", "gpu-down", + "gpu-kgsl-ui-rb", + "gpu-off-level", "stop-loop", "uclamp-rule", "task-trim", @@ -725,6 +727,10 @@ pub struct Config { pub gpu_blob_entries: u32, /// gpu-down (governor): when the GPU level leaves the top pub gpu_down: GpuDown, + /// gpu-kgsl-ui-rb (0): keep render server and front app out of Android's UI ringbuffer (4-7) + pub gpu_kgsl_ui_rb: bool, + /// gpu-off-level (1): hold KGSL at its lowest level while iOS's display is off + pub gpu_off_level: bool, /// stop-loop (wait): for the fork's stop loop; xnuhost checks it and names it in the switches line pub stop_loop: StopLoop, /// uclamp-rule (work): who sets the vCPU threads' clamps and where drm2kgsl's boost goes @@ -971,6 +977,8 @@ impl Config { decoder_codecs: oneencoder::switches::ALL_CODECS, gpu_blob_entries: GPU_BLOB_ENTRIES, gpu_down: GpuDown::Governor, + gpu_kgsl_ui_rb: false, + gpu_off_level: true, stop_loop: StopLoop::Wait, uclamp_rule: UclampRule::Work, task_trim: true, @@ -1193,6 +1201,8 @@ impl Config { "decoder-codecs" => self.decoder_codecs = named(oneencoder::switches::parse_codecs(value))?, "gpu-blob-entries" => self.gpu_blob_entries = number(value, 16384, i64::from(GPU_BLOB_ENTRIES))?, "gpu-down" => self.gpu_down = named(GpuDown::parse(value))?, + "gpu-kgsl-ui-rb" => self.gpu_kgsl_ui_rb = flag(value)?, + "gpu-off-level" => self.gpu_off_level = flag(value)?, "stop-loop" => self.stop_loop = named(StopLoop::parse(value))?, "uclamp-rule" => self.uclamp_rule = named(UclampRule::parse(value))?, "task-trim" => self.task_trim = flag(value)?, @@ -1440,6 +1450,8 @@ impl Config { take!(self, image, "astc", astc); take!(self, image, "gpu-blob-entries", gpu_blob_entries); take!(self, image, "gpu-down", gpu_down); + take!(self, image, "gpu-kgsl-ui-rb", gpu_kgsl_ui_rb); + take!(self, image, "gpu-off-level", gpu_off_level); take!(self, image, "stop-loop", stop_loop); take!(self, image, "uclamp-rule", uclamp_rule); take!(self, image, "task-trim", task_trim); @@ -2369,6 +2381,8 @@ impl Config { "ram-ondemand" => on(self.ram_ondemand), "uclamp-rule" => self.uclamp_rule.as_str().to_string(), "gpu-down" => self.gpu_down.as_str().to_string(), + "gpu-kgsl-ui-rb" => on(self.gpu_kgsl_ui_rb), + "gpu-off-level" => on(self.gpu_off_level), "gpu-blob-entries" => self.gpu_blob_entries.to_string(), "wifi-ring-wait" => on(self.wifi_ring_wait), "wifi-send-wait" => on(self.wifi_send_wait), diff --git a/runtime/xnuhost/src/config/tests.rs b/runtime/xnuhost/src/config/tests.rs index 83053341..ea6e3c99 100644 --- a/runtime/xnuhost/src/config/tests.rs +++ b/runtime/xnuhost/src/config/tests.rs @@ -1569,6 +1569,8 @@ fn the_switches() { ("decoder-codecs", "vp9,av1"), ("gpu-blob-entries", "16384"), ("gpu-down", "bottom"), + ("gpu-kgsl-ui-rb", "1"), + ("gpu-off-level", "0"), ("stop-loop", "poll"), ("uclamp-rule", "all"), ("display-post", "serial"), @@ -1589,6 +1591,8 @@ fn the_switches() { ("decoder-codecs", "vp8"), ("decoder-codecs", ""), ("gpu-down", "top"), + ("gpu-kgsl-ui-rb", "on"), + ("gpu-off-level", "off"), ("stop-loop", "sleep"), ("uclamp-rule", "some"), ("wifi-buffers", "off"), @@ -1623,7 +1627,7 @@ fn the_switches() { ); assert!( line.ends_with( - "not at the default: stop-loop timer-coalesce uclamp-rule gpu-down gpu-blob-entries wifi-ring-wait wifi-send-wait \ + "not at the default: stop-loop timer-coalesce uclamp-rule gpu-down gpu-kgsl-ui-rb gpu-off-level gpu-blob-entries wifi-ring-wait wifi-send-wait \ wifi-buffers wifi-joined-scan encoder-10bit encoder-warmup display-post display-present decoder decoder-codecs astc \ oneios-wifi-rssi oneios-telemetry-jobs oneios-pool-cut oneios-pressure-big oneios-disable-allowed \ oneios-nested-exact oneios-upgrade-flush oneios-fill-fast-fault oneios-audio-rt oneios-audio-curve \ diff --git a/runtime/xnuhost/src/display.rs b/runtime/xnuhost/src/display.rs index 35281bbc..d1fffac9 100644 --- a/runtime/xnuhost/src/display.rs +++ b/runtime/xnuhost/src/display.rs @@ -170,11 +170,20 @@ struct Client { stats: Stats, } -/// The DRM back end's buffer and mode. -struct Drm { - fd: OwnedFd, +/// One KMS dumb buffer. +struct DrmBuf { fb: u32, map: *mut u8, +} + +/// The DRM back end's double-buffered dumb buffers and mode. +struct Drm { + fd: OwnedFd, + crtc: u32, + bufs: [DrmBuf; 2], + front: usize, + page_flip: bool, + prev_dirty: (u32, u32, u32, u32), w: u32, h: u32, stride: u32, @@ -599,6 +608,7 @@ mod kms { pub const GETENCODER: u32 = iowr(0xa6, std::mem::size_of::()); pub const GETCONNECTOR: u32 = iowr(0xa7, std::mem::size_of::()); pub const ADDFB: u32 = iowr(0xae, std::mem::size_of::()); + pub const PAGE_FLIP: u32 = iowr(0xb0, std::mem::size_of::()); pub const DIRTYFB: u32 = iowr(0xb1, std::mem::size_of::()); pub const CREATE_DUMB: u32 = iowr(0xb2, std::mem::size_of::()); pub const MAP_DUMB: u32 = iowr(0xb3, std::mem::size_of::()); @@ -720,6 +730,15 @@ mod kms { } #[repr(C)] #[derive(Default)] + pub struct PageFlip { + pub crtc_id: u32, + pub fb_id: u32, + pub flags: u32, + pub reserved: u32, + pub user_data: u64, + } + #[repr(C)] + #[derive(Default)] pub struct FbDirty { pub fb_id: u32, pub flags: u32, @@ -732,7 +751,7 @@ mod kms { const _: () = assert!(std::mem::size_of::() == 80 && std::mem::size_of::() == 20); const _: () = assert!(std::mem::size_of::() == 32 && std::mem::size_of::() == 28); const _: () = assert!(std::mem::size_of::() == 16 && std::mem::size_of::() == 104); - const _: () = assert!(std::mem::size_of::() == 24); + const _: () = assert!(std::mem::size_of::() == 24 && std::mem::size_of::() == 24); /// The ioctl, true when it worked. pub fn call(fd: RawFd, request: u32, arg: *mut T) -> bool { @@ -835,7 +854,11 @@ fn drm_init() -> Result { continue; } let n = conn.count_modes.min(32) as usize; - let mode = modes[..n].iter().find(|m| m.kind & kms::MODE_TYPE_PREFERRED != 0).copied().unwrap_or(modes[0]); + let mode = modes[..n] + .iter() + .max_by_key(|m| (m.vrefresh, (m.kind & kms::MODE_TYPE_PREFERRED != 0) as u32)) + .copied() + .unwrap_or(modes[0]); let mut enc = kms::Encoder { encoder_id: if conn.encoder_id != 0 { conn.encoder_id } else { conn_encoders[0] }, ..Default::default() @@ -852,49 +875,56 @@ fn drm_init() -> Result { if crtc == 0 { continue; } - let mut dumb = kms::CreateDumb { - width: mode.hdisplay as u32, - height: mode.vdisplay as u32, - bpp: 32, - ..Default::default() - }; - if !kms::call(raw, kms::CREATE_DUMB, &mut dumb) { - loge!("display: dumb buffer: {}", std::io::Error::last_os_error()); - return Err(()); - } - let mut fb = kms::FbCmd { - width: dumb.width, - height: dumb.height, - pitch: dumb.pitch, - bpp: 32, - depth: 24, - handle: dumb.handle, - ..Default::default() - }; - let mut map = kms::MapDumb { handle: dumb.handle, ..Default::default() }; - if !kms::call(raw, kms::ADDFB, &mut fb) || !kms::call(raw, kms::MAP_DUMB, &mut map) { - loge!("display: framebuffer: {}", std::io::Error::last_os_error()); - return Err(()); - } - // SAFETY: maps the dumb buffer the kernel just made, at the offset it gave. - let p = unsafe { - libc::mmap( - std::ptr::null_mut(), - dumb.size as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_SHARED, - raw, - map.offset as libc::off_t, - ) - }; - if p == libc::MAP_FAILED { - return Err(()); + let mut bufs = Vec::with_capacity(2); + let mut pitch = 0u32; + for _ in 0..2 { + let mut dumb = kms::CreateDumb { + width: mode.hdisplay as u32, + height: mode.vdisplay as u32, + bpp: 32, + ..Default::default() + }; + if !kms::call(raw, kms::CREATE_DUMB, &mut dumb) { + loge!("display: dumb buffer: {}", std::io::Error::last_os_error()); + return Err(()); + } + let mut fb = kms::FbCmd { + width: dumb.width, + height: dumb.height, + pitch: dumb.pitch, + bpp: 32, + depth: 24, + handle: dumb.handle, + ..Default::default() + }; + let mut map = kms::MapDumb { handle: dumb.handle, ..Default::default() }; + if !kms::call(raw, kms::ADDFB, &mut fb) || !kms::call(raw, kms::MAP_DUMB, &mut map) { + loge!("display: framebuffer: {}", std::io::Error::last_os_error()); + return Err(()); + } + // SAFETY: maps the dumb buffer the kernel just made, at the offset it gave. + let p = unsafe { + libc::mmap( + std::ptr::null_mut(), + dumb.size as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + raw, + map.offset as libc::off_t, + ) + }; + if p == libc::MAP_FAILED { + return Err(()); + } + // SAFETY: the mapping just made, dumb.size bytes. + unsafe { std::ptr::write_bytes(p as *mut u8, 0, dumb.size as usize) }; + pitch = dumb.pitch; + bufs.push(DrmBuf { fb: fb.fb_id, map: p as *mut u8 }); } - // SAFETY: the mapping just made, dumb.size bytes. - unsafe { std::ptr::write_bytes(p as *mut u8, 0, dumb.size as usize) }; + let Ok([b0, b1]) = <[DrmBuf; 2]>::try_from(bufs) else { return Err(()) }; let mut set = kms::Crtc { crtc_id: crtc, - fb_id: fb.fb_id, + fb_id: b0.fb, set_connectors_ptr: connector as *const u32 as u64, count_connectors: 1, mode, @@ -905,41 +935,84 @@ fn drm_init() -> Result { loge!("display: mode set {}x{}: {}", mode.hdisplay, mode.vdisplay, std::io::Error::last_os_error()); return Err(()); } - logi!("display: KMS {}x{} on connector {}, crtc {}", dumb.width, dumb.height, connector, crtc); - return Ok(Drm { fd, fb: fb.fb_id, map: p as *mut u8, w: dumb.width, h: dumb.height, stride: dumb.pitch }); + logi!( + "display: KMS {}x{}@{} on connector {}, crtc {} (double-buffered)", + mode.hdisplay, + mode.vdisplay, + mode.vrefresh, + connector, + crtc + ); + return Ok(Drm { + fd, + crtc, + bufs: [b0, b1], + front: 0, + page_flip: true, + prev_dirty: (0, 0, mode.hdisplay as u32, mode.vdisplay as u32), + w: mode.hdisplay as u32, + h: mode.vdisplay as u32, + stride: pitch, + }); } loge!("display: no connected KMS connector"); Err(()) } -fn drm_flush(d: &Display, drm: &Drm, x: u32, y: u32, w: u32, h: u32) { - // The guest frame is copied to the panel's buffer, centred if their sizes differ. +fn drm_flush(d: &Display, drm: &mut Drm, x: u32, y: u32, w: u32, h: u32) { + // Copy the union of this frame's damage and the previous frame's damage into the back buffer so both + // buffers stay in sync across page-flips. + let (px, py, pw, ph) = drm.prev_dirty; + let (cx, cy, cw, ch) = if drm.page_flip && pw > 0 && ph > 0 { + let nx = x.min(px); + let ny = y.min(py); + let nx2 = (x + w).max(px + pw); + let ny2 = (y + h).max(py + ph); + (nx, ny, nx2 - nx, ny2 - ny) + } else { + (x, y, w, h) + }; + let target = if drm.page_flip { 1 - drm.front } else { drm.front }; + let buf = &drm.bufs[target]; let f = &d.frame; let ox = if drm.w > f.width { (drm.w - f.width) / 2 } else { 0 }; let oy = if drm.h > f.height { (drm.h - f.height) / 2 } else { 0 }; - let mut row = y; - while row < y + h && row + oy < drm.h { - let width = if x + w + ox <= drm.w { - w - } else if x + ox < drm.w { - drm.w - x - ox + let mut row = cy; + while row < cy + ch && row + oy < drm.h { + let width = if cx + cw + ox <= drm.w { + cw + } else if cx + ox < drm.w { + drm.w - cx - ox } else { 0 }; // SAFETY: both rows lie inside their buffers (the clipping above); the frame is mapped for the process's life. unsafe { std::ptr::copy_nonoverlapping( - f.as_ptr().add(row as usize * f.stride as usize + x as usize * 4), - drm.map.add((row + oy) as usize * drm.stride as usize + (x + ox) as usize * 4), + f.as_ptr().add(row as usize * f.stride as usize + cx as usize * 4), + buf.map.add((row + oy) as usize * drm.stride as usize + (cx + ox) as usize * 4), width as usize * 4, ) }; row += 1; } - let mut clip = - kms::ClipRect { x1: (x + ox) as u16, y1: (y + oy) as u16, x2: (x + ox + w) as u16, y2: (y + oy + h) as u16 }; + if drm.page_flip { + let mut flip = kms::PageFlip { crtc_id: drm.crtc, fb_id: buf.fb, ..Default::default() }; + if kms::call(drm.fd.as_raw_fd(), kms::PAGE_FLIP, &mut flip) { + drm.front = target; + drm.prev_dirty = (x, y, w, h); + return; + } + drm.page_flip = false; + } + let mut clip = kms::ClipRect { + x1: (cx + ox) as u16, + y1: (cy + oy) as u16, + x2: (cx + ox + cw) as u16, + y2: (cy + oy + ch) as u16, + }; let mut dirty = - kms::FbDirty { fb_id: drm.fb, clips_ptr: &mut clip as *mut _ as u64, num_clips: 1, ..Default::default() }; + kms::FbDirty { fb_id: buf.fb, clips_ptr: &mut clip as *mut _ as u64, num_clips: 1, ..Default::default() }; kms::call(drm.fd.as_raw_fd(), kms::DIRTYFB, &mut dirty); // command-mode panels need it; others ignore it } @@ -1115,7 +1188,7 @@ pub fn flush(x: u32, y: u32, w: u32, h: u32) { crate::input::frame_shown(); // input.rs's touch-to-frame measurement let Some(d) = DISPLAY.get() else { return }; if let Some(drm) = d.drm.as_ref() { - drm_flush(d, &drm.lock().unwrap_or_else(|e| e.into_inner()), x, y, w, h); + drm_flush(d, &mut drm.lock().unwrap_or_else(|e| e.into_inner()), x, y, w, h); } if d.backend != DisplayBackend::Shm { return; diff --git a/runtime/xnuhost/src/gpu3d_kgsl.rs b/runtime/xnuhost/src/gpu3d_kgsl.rs index a8a72e8c..f246a611 100644 --- a/runtime/xnuhost/src/gpu3d_kgsl.rs +++ b/runtime/xnuhost/src/gpu3d_kgsl.rs @@ -26,6 +26,10 @@ use crate::gpu3d::{self, Chunk, Entry, Errno, Gpu3d, LogFn, Retire}; static SINK: AtomicUsize = AtomicUsize::new(0); /// gpu-down=bottom (docs/switches.md), set once by session.rs before the GPU opens. pub static DOWN_AT_BOTTOM: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// gpu-kgsl-ui-rb=1 (docs/switches.md), set once by session.rs before the GPU opens. +pub static UI_RB: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// gpu-off-level=1 (docs/switches.md), set once by session.rs before the GPU opens. +pub static OFF_LEVEL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); /// A line to the sink set at the open: at most 511 bytes, line breaks at its end dropped (as say() did). fn say(level: u8, line: &str) { @@ -706,7 +710,7 @@ impl Gpu3d for Kgsl { h[0] & policy::HINT_ROLE, if h[0] & policy::HINT_DARWINBG != 0 { ", DarwinBG" } else { "" }, h[1] & 7, - policy::kgsl_priority(cls) + policy::kgsl_priority_for(cls, UI_RB.load(Ordering::Relaxed)) ); } } @@ -744,14 +748,27 @@ impl Gpu3d for Kgsl { Some(i) => { let now = now_us() * 1000; let c = s.ctx[i]; - let (action, next) = s.pol.frame_start(c.cls, now, c.hint[2] as u32 * policy::HINT_DEADLINE_US); - // KGSL's lowest level for a background context (gpu-priority=1) at a still screen, unless other - // work is queued, another process reads its surfaces, or its own oldest fence has waited past - // the bound (lowest_for). - let oldest = (0..STAT_RINGS).filter_map(|r| c.oldest(r)).map(|p| p.at).min().unwrap_or(0); - let lowest = c.cls == Class::Background - && s.priority_on - && s.pol.lowest_for(now, s.fg_pending, c.shared, oldest * 1000); + let display_off = OFF_LEVEL.load(Ordering::Relaxed) && !onebridges::brightness::display_on(); + let (action, next, lowest) = if display_off { + let action = if s.pol.level == policy::Level::Top { + s.pol.level = policy::Level::Governor; + Action::Governor + } else { + Action::None + }; + (action, Frame::default(), s.priority_on) + } else { + let (action, next) = + s.pol.frame_start(c.cls, now, c.hint[2] as u32 * policy::HINT_DEADLINE_US); + // KGSL's lowest level for a background context (gpu-priority=1) at a still screen, unless other + // work is queued, another process reads its surfaces, or its own oldest fence has waited past + // the bound (lowest_for). + let oldest = (0..STAT_RINGS).filter_map(|r| c.oldest(r)).map(|p| p.at).min().unwrap_or(0); + let lowest = c.cls == Class::Background + && s.priority_on + && s.pol.lowest_for(now, s.fg_pending, c.shared, oldest * 1000); + (action, next, lowest) + }; if lowest { s.lowest_n += 1; } @@ -934,8 +951,10 @@ fn level_start(s: &mut St) { s.pol.ratio_x16 % 16 * 100 / 16, if off { "off (gpu-priority=0)" - } else { + } else if UI_RB.load(Ordering::Relaxed) { "on (render server and front 4, default and background 8; background at the lowest level at a still screen)" + } else { + "on (all classes 8, out of Android UI ringbuffer; lowest level on idle background or display off)" }, s.background.as_deref().unwrap_or(policy::DEFAULT_BACKGROUND) ); diff --git a/runtime/xnuhost/src/gpu3d_kgsl/policy.rs b/runtime/xnuhost/src/gpu3d_kgsl/policy.rs index fa48fd0c..17c0801c 100644 --- a/runtime/xnuhost/src/gpu3d_kgsl/policy.rs +++ b/runtime/xnuhost/src/gpu3d_kgsl/policy.rs @@ -172,13 +172,21 @@ pub fn class_of(name: &[u8], hint: u8, qos: u8, shown: bool, background: Option< /// empty, so its fences had no bound, and the class a queue was made with (by name or by role at the context's /// creation) stays its priority for good. None takes the first ringbuffer (0-3, Android's compositor's). Every class /// gets an explicit one, so the order holds whatever the kernel's default for KGSL_CONTEXT_PRIORITY_UNDEF is. -pub fn kgsl_priority(c: Class) -> u32 { +/// The KGSL priority (0 highest, 15 lowest; four to a ringbuffer, KGSL_CONTEXT_PRIORITY_SHIFT 12) of a class's queues. +/// With `ui_rb = false` (`gpu-kgsl-ui-rb=0`, default), every class gets 8 (third ringbuffer), keeping iOS's render server +/// and front app out of Android's UI ringbuffer (4-7). With `ui_rb = true` (`gpu-kgsl-ui-rb=1`), render server and front +/// app get 4 (second ringbuffer), everything else 8. +pub fn kgsl_priority_for(c: Class, ui_rb: bool) -> u32 { match c { - Class::Render | Class::Front => 4, + Class::Render | Class::Front if ui_rb => 4, _ => 8, } } +pub fn kgsl_priority(c: Class) -> u32 { + kgsl_priority_for(c, true) +} + // ---- whose surfaces another process reads ------------------------------------------------------------------------------ // A blob over guest pages (an IOSurface the process draws into, or one it imports) is known by its first guest page: // two contexts with blobs over the same first page share that surface (the guest's oneios-gpu-pixels "pages of another diff --git a/runtime/xnuhost/src/gpu3d_kgsl/policy/tests.rs b/runtime/xnuhost/src/gpu3d_kgsl/policy/tests.rs index 51b8ba66..50b351b4 100644 --- a/runtime/xnuhost/src/gpu3d_kgsl/policy/tests.rs +++ b/runtime/xnuhost/src/gpu3d_kgsl/policy/tests.rs @@ -81,6 +81,7 @@ fn classes() { assert!(kgsl_priority(Class::Default) == 8 && kgsl_priority(Class::Background) == 8); for c in [Class::Default, Class::Render, Class::Front, Class::Background] { assert!((4..=11).contains(&kgsl_priority(c))); + assert_eq!(kgsl_priority_for(c, false), 8); } } diff --git a/runtime/xnuhost/src/session.rs b/runtime/xnuhost/src/session.rs index 9203956f..83cfb680 100644 --- a/runtime/xnuhost/src/session.rs +++ b/runtime/xnuhost/src/session.rs @@ -590,6 +590,8 @@ fn set_switches(config: &Config) { crate::cpu::UCLAMP_ALL.store(config.uclamp_rule == crate::config::UclampRule::All, Ordering::Relaxed); crate::cpu::TIMER_COALESCE.store(config.timer_coalesce, Ordering::Relaxed); crate::gpu3d_kgsl::DOWN_AT_BOTTOM.store(config.gpu_down == GpuDown::Bottom, Ordering::Relaxed); + crate::gpu3d_kgsl::UI_RB.store(config.gpu_kgsl_ui_rb, Ordering::Relaxed); + crate::gpu3d_kgsl::OFF_LEVEL.store(config.gpu_off_level, Ordering::Relaxed); } fn hostcalls_vector() -> u64 { diff --git a/runtime/xnuhost/src/session/board.rs b/runtime/xnuhost/src/session/board.rs index 190a5462..e16816e2 100644 --- a/runtime/xnuhost/src/session/board.rs +++ b/runtime/xnuhost/src/session/board.rs @@ -581,6 +581,7 @@ impl Session { if pool_bytes != 0 { // The GPU's level and priorities (gpu3d_kgsl, drm2kgsl patch 0008; docs/gpu.md 2.2b) read these. std::env::set_var("ONEIOS_GPU_LEVEL", config.gpu_level.as_str()); + std::env::set_var("ONEIOS_GPU_KGSL_UI_RB", if config.gpu_kgsl_ui_rb { "1" } else { "0" }); if !config.gpu_priority { std::env::set_var("ONEIOS_GPU_PRIORITY", "off"); }