From 4108d84724854ebd3ac7f67a5af57f712840592a Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 09:40:52 +0000 Subject: [PATCH 1/3] perf(mtlvk,jetsam,simfb): disable Lavapipe timestamps, reuse broker root textures, and tune dense multi-device jetsam/simfb --- external/metal2vulkan | 2 +- host/simfb/simfb.c | 23 ++++++-- linux/mtlvk/src/conn.rs | 65 ++++++++++++++++++++-- linux/mtlvk/src/main.rs | 31 +++++++++++ tools/launcher/core/src/services/jetsam.rs | 41 +++++++++++++- 5 files changed, 147 insertions(+), 15 deletions(-) diff --git a/external/metal2vulkan b/external/metal2vulkan index 5e617ade..286cb860 160000 --- a/external/metal2vulkan +++ b/external/metal2vulkan @@ -1 +1 @@ -Subproject commit 5e617ade6c91d976ba399635b1709707561fa6e1 +Subproject commit 286cb860153f92410b380ba66866c146456cf8b6 diff --git a/host/simfb/simfb.c b/host/simfb/simfb.c index 003b4ef8..80316c3e 100644 --- a/host/simfb/simfb.c +++ b/host/simfb/simfb.c @@ -562,8 +562,17 @@ static void file_write(const void* px, uint32_t w, uint32_t h, uint32_t stride, } file_last_ns = now_ns(); } +static int file_write_enabled(void) { + static int cached = -1; + if (cached < 0) { + const char* env = getenv("SIMFB_FILE_WRITE"); + cached = (env && env[0] == '0' && env[1] == '\0') ? 0 : 1; + } + return cached; +} static uint64_t file_seq; // ring frame last written to the file static void file_from_ring(void) { // on dump_q: the ring's latest slot (only dump_q writes slots); display 1 only + if (!file_write_enabled()) return; struct ring_hdr* ring = disps[0].ring; size_t ring_slot_bytes = disps[0].ring_slot_bytes; if (!ring) return; @@ -683,12 +692,14 @@ static void dump(SFBSwapchainRef sc, IOSurfaceRef s, uint64_t submit_ns) { // ring_woke(ring_wake((void*)&ring->seq)); IOSurfaceUnlock(s, kIOSurfaceLockReadOnly, NULL); // the file (display 1 only): at most every 2 s, from the ring; the timer writes a newer last frame later - if (D == &disps[0] && now_ns() - file_last_ns >= 2000000000ull) file_from_ring(); - if (D == &disps[0] && !file_timer) { - file_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dump_q); - dispatch_source_set_timer(file_timer, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC); - dispatch_source_set_event_handler(file_timer, ^{ if (now_ns() - file_last_ns >= 1900000000ull) file_from_ring(); }); - dispatch_resume(file_timer); + if (D == &disps[0] && file_write_enabled()) { + if (now_ns() - file_last_ns >= 2000000000ull) file_from_ring(); + if (!file_timer) { + file_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dump_q); + dispatch_source_set_timer(file_timer, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC); + dispatch_source_set_event_handler(file_timer, ^{ if (now_ns() - file_last_ns >= 1900000000ull) file_from_ring(); }); + dispatch_resume(file_timer); + } } } else { // no ring: every frame to the file, as before (display 1) if (D == &disps[0]) file_write(IOSurfaceGetBaseAddress(s), w, h, stride, seq); diff --git a/linux/mtlvk/src/conn.rs b/linux/mtlvk/src/conn.rs index b790e3b8..ef4a62cd 100644 --- a/linux/mtlvk/src/conn.rs +++ b/linux/mtlvk/src/conn.rs @@ -1171,10 +1171,26 @@ fn timing_add(enc: f64, done: f64, gpu: f64) { t.clear(); } +fn vram_targets_for(is_cpu: bool, env_val: Option<&str>) -> bool { + env_val.map(|v| v != "0").unwrap_or(!is_cpu) +} + +fn should_reuse_broker_root(root: &TextureDescriptor, desc: &TextureDescriptor) -> bool { + desc.pixel_format == root.pixel_format + && desc.texture_type == root.texture_type + && desc.swizzle == root.swizzle + && root.mipmap_level_count == 1 + && root.array_length == 1 +} + impl State { pub fn new(device: Device, out: Sink) -> Res { + Self::new_for_gpu(device, out, false) + } + + pub fn new_for_gpu(device: Device, out: Sink, is_cpu: bool) -> Res { let helper = device.new_command_queue(64).map_err(err("helper queue"))?; - let vram_targets = std::env::var("MTLVK_VRAM_TARGETS").map(|v| v != "0").unwrap_or(true); + let vram_targets = vram_targets_for(is_cpu, std::env::var("MTLVK_VRAM_TARGETS").ok().as_deref()); if vram_targets { eprintln!("mtlvk: render targets over IOSurfaces are drawn in VRAM (MTLVK_VRAM_TARGETS)"); } @@ -1984,10 +2000,14 @@ impl State { if let Some(plane) = self.broker_planes.get(&buf).cloned() { if offset == 0 && r.rest() == 1u32.to_le_bytes() { if let Some(root) = plane.view_source(desc, bpr) { - let view = self.indexed(id, desc.pixel_format, root.descriptor().usage, |_, index| { - root.new_texture_view_with_swizzle(desc.pixel_format, desc.texture_type, 0..1, 0..1, desc.swizzle, index) - .map_err(err("broker surface view")) - }); + let view = if should_reuse_broker_root(root.descriptor(), &desc) { + Ok(root.clone()) + } else { + self.indexed(id, desc.pixel_format, root.descriptor().usage, |_, index| { + root.new_texture_view_with_swizzle(desc.pixel_format, desc.texture_type, 0..1, 0..1, desc.swizzle, index) + .map_err(err("broker surface view")) + }) + }; if let Ok(t) = view { let rid = t.gpu_resource_id().to_bits(); self.objs.insert(id, Obj::Tex(t)); @@ -3381,6 +3401,7 @@ fn write_frame(writer: &mut impl Write, op: u32, seq: u64, payload: &[u8]) -> io pub fn serve( n: usize, device: Device, + is_cpu: bool, stream: UnixStream, #[cfg(feature = "surface-diag")] surface_diag: bool, ) { @@ -3389,7 +3410,7 @@ pub fn serve( let out: Sink = Arc::new(move |op, seq, payload: Vec| { let _ = write_frame(&mut *event_writer.lock().unwrap(), op, seq, &payload); }); - let mut state = match State::new(device, out.clone()) { + let mut state = match State::new_for_gpu(device, out.clone(), is_cpu) { Ok(s) => s, Err(e) => { eprintln!("mtlvk: conn{n}: {e}"); @@ -4608,4 +4629,36 @@ mod tests { assert!(!is_storage_mode_private(0x30)); // Memoryless assert_eq!(BUF_ADDR_EXPOSED, 24); } + + #[test] + fn vram_targets_defaults_off_for_cpu_and_honors_env_override() { + assert!(!vram_targets_for(true, None)); + assert!(vram_targets_for(false, None)); + assert!(vram_targets_for(true, Some("1"))); + assert!(!vram_targets_for(false, Some("0"))); + } + + #[test] + fn broker_root_reuse_requires_exact_format_type_swizzle_and_single_slice() { + let root = TextureDescriptor::new(TextureType::Type2D, PixelFormat::BGRA8Unorm, 1206, 2622); + let exact = TextureDescriptor::new(TextureType::Type2D, PixelFormat::BGRA8Unorm, 1206, 2622); + assert!(should_reuse_broker_root(&root, &exact)); + + let mut srgb = exact; + srgb.pixel_format = PixelFormat::BGRA8UnormSRGB; + assert!(!should_reuse_broker_root(&root, &srgb)); + + let mut swizzled = exact; + swizzled.swizzle = TextureSwizzleChannels::new( + TextureSwizzle::Blue, + TextureSwizzle::Green, + TextureSwizzle::Red, + TextureSwizzle::Alpha, + ); + assert!(!should_reuse_broker_root(&root, &swizzled)); + + let mut mipped = root; + mipped.mipmap_level_count = 2; + assert!(!should_reuse_broker_root(&mipped, &exact)); + } } diff --git a/linux/mtlvk/src/main.rs b/linux/mtlvk/src/main.rs index da49bb15..1a8ff449 100644 --- a/linux/mtlvk/src/main.rs +++ b/linux/mtlvk/src/main.rs @@ -51,6 +51,14 @@ pub fn open_device() -> Result<(Device, gpus::Gpu), String> { /// - The in-memory memo (MTLVK_MEMO_MB): the new runtime keeps the last 1,024 compiled contents by its own rule, and /// its lowerings on disk in `pipeline_cache_dir` (MTLVK_PIPELINE_CACHE, default $XDG_CACHE_HOME/metal2vulkan-rt; /// MTLVK_PIPELINE_CACHE_MB caps the lowerings, default the runtime's 128). +fn disable_timestamps_for(gpu_kind: &str, env_val: Option<&str>) -> bool { + match env_val { + Some("0") => true, + Some("1") => false, + _ => gpu_kind == "cpu", + } +} + fn open_device_with(#[cfg(feature = "surface-diag")] surface_diag: bool) -> Result<(Device, gpus::Gpu), String> { use metal2vulkan_runtime::{DeviceOptions, Instance}; gpus::prepare_loader(false); @@ -84,6 +92,13 @@ fn open_device_with(#[cfg(feature = "surface-diag")] surface_diag: bool) -> Resu o.pipeline_cache_dir = dir; } o.pipeline_cache_cap = std::env::var("MTLVK_PIPELINE_CACHE_MB").ok().and_then(|v| v.parse::().ok()).map(|mb| mb << 20); + o.disable_timestamps = disable_timestamps_for( + gpu.kind, + std::env::var("MTLVK_TIMESTAMPS").ok().as_deref(), + ); + if o.disable_timestamps { + eprintln!("mtlvk: GPU timestamps disabled (MTLVK_TIMESTAMPS=0 or CPU device)"); + } let device = Device::new(&physical, o).map_err(|e| format!("device: {e}"))?; conn::grant_indices(&device)?; Ok((device, gpu)) @@ -316,6 +331,7 @@ fn main() { #[cfg(feature = "surface-diag")] surface_diag.then(|| device.clone()), ); + let is_cpu = gpu.kind == "cpu"; for (n, stream) in listener.incoming().enumerate() { match stream { Ok(s) => { @@ -329,6 +345,7 @@ fn main() { conn::serve( n, device, + is_cpu, s, #[cfg(feature = "surface-diag")] surface_diag, @@ -340,3 +357,17 @@ fn main() { } } } + +#[cfg(test)] +mod main_tests { + use super::disable_timestamps_for; + + #[test] + fn disable_timestamps_defaults_on_for_cpu_and_honors_env_override() { + assert!(disable_timestamps_for("cpu", None)); + assert!(!disable_timestamps_for("discrete", None)); + assert!(!disable_timestamps_for("integrated", None)); + assert!(!disable_timestamps_for("cpu", Some("1"))); + assert!(disable_timestamps_for("discrete", Some("0"))); + } +} diff --git a/tools/launcher/core/src/services/jetsam.rs b/tools/launcher/core/src/services/jetsam.rs index 735ddd7f..18926da4 100644 --- a/tools/launcher/core/src/services/jetsam.rs +++ b/tools/launcher/core/src/services/jetsam.rs @@ -57,6 +57,7 @@ const BACKGROUND_CPU: &[&str] = &[ "assetsubscriptiond", "assetsubscripti", "localspeechrecognition", "assistant_cdmd", "siriknowledged", "siriactionsd", "siriinferenced", "sirittsd", "corespeechd", "biomed", "passd", "financed", "assetsd", "medialibraryd", "itunescloudd", + "diagnosticd", "kbd", "mediaremoted", "iconservicesagent", "cloudd", ]; /// pure streaming-decompression XPC helpers (per-PID private XPC services owned by mobileassetd, never serving app /// MachServices): paused via SIGSTOP while a foreground app runs and resumed via SIGCONT once idle, because SCHED_IDLE @@ -135,9 +136,10 @@ pub trait World { /// X86SIM_JETSAM_ and its default #[rustfmt::skip] -const KNOBS: [(&str, f64); 12] = [ +const KNOBS: [(&str, f64); 13] = [ ("EXT", 10.0), ("APP", 30.0), ("LAST", 90.0), ("KEEP", 1.0), ("IDLE", 30.0), ("IDLE_HOT", 600.0), ("MAX", 1800.0), ("DIRTY_IDLE", 300.0), ("INPUT", 60.0), ("WARN_EVERY", 10.0), ("UISVC", 60.0), ("INSTANT", 5.0), + ("SCENE_SETTLE", SCENE_SETTLE), ]; fn env(k: &str) -> Option { @@ -590,7 +592,7 @@ impl Jetsam { // FrontBoard's per-scene visibility tells an app left at the home screen from one on screen match (scenes, vis) { (s, _) if s > 0 => fore.push("scene visible".into()), - (0, 1) if now - start > SCENE_SETTLE => back.push("no visible scene".into()), + (0, 1) if now - start > self.cfg.k("SCENE_SETTLE") => back.push("no visible scene".into()), (0, 1) => fore.push("launching".into()), (_, 1) => fore.push("visible".into()), (_, 0) => back.push("not visible".into()), @@ -1211,4 +1213,39 @@ mod tests { j.sweep(&mut w, false, true); assert!(w.paused.is_empty() && w.resumed.is_empty()); } + + #[test] + fn scene_settle_knob_and_housekeeping_daemons_protect_dense_launches() { + let mut knobs: HashMap<&'static str, f64> = KNOBS.into_iter().collect(); + knobs.insert("SCENE_SETTLE", 60.0); + let cfg = Config { knobs, bg_cpu: true, bg_pause: true, ..Default::default() }; + let mut j = Jetsam::new(cfg, 100.0); + + // Launching app with (scenes=0, vis=1) at 35s age stays foreground when SCENE_SETTLE=60s, + // then becomes "no visible scene" once age exceeds 60s. + let mut front = Front::default(); + front.pids.insert(42, (1, 0, 0)); + let row = Row { + dpid: 42, + lpid: 4200, + exe: "/var/containers/Bundle/Application/X/Qualification.app/Qualification".into(), + start: 100.0, + key: (42, 1000), + sm: None, + jm: None, + idle: false, + }; + let (back_35, fore_35) = j.app_view(&row, false, None, Some(&front), 100.0, 135.0); + assert!(back_35.is_empty(), "expected launching protection at 35s, got {back_35:?}"); + assert!(fore_35.iter().any(|s| s == "launching")); + + let (back_65, _) = j.app_view(&row, false, None, Some(&front), 100.0, 165.0); + assert!(back_65.iter().any(|s| s == "no visible scene")); + + // diagnosticd and kbd are demoted to SCHED_IDLE (bg_cpu) but never SIGSTOP-paused. + assert!(is_background_cpu("/usr/libexec/diagnosticd")); + assert!(is_background_cpu("/System/Library/TextInput/kbd")); + assert!(!is_extraction_helper("/usr/libexec/diagnosticd")); + assert!(!is_extraction_helper("/System/Library/TextInput/kbd")); + } } From 45f66ccec86db8e7a6078324a1c049efd0b18c69 Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 09:45:10 +0000 Subject: [PATCH 2/3] fix(mtlvk): pass is_cpu=false to conn::serve in unit test --- linux/mtlvk/src/conn.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/linux/mtlvk/src/conn.rs b/linux/mtlvk/src/conn.rs index ef4a62cd..fc37d1a7 100644 --- a/linux/mtlvk/src/conn.rs +++ b/linux/mtlvk/src/conn.rs @@ -4031,6 +4031,7 @@ mod tests { serve( 0, device, + false, server, #[cfg(feature = "surface-diag")] false, From 75db73765868e3d60756be065a406544cf6ac7bc Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 09:46:46 +0000 Subject: [PATCH 3/3] fix(mksimdevice): forward SIMFB_FILE_WRITE into guest sim.env --- tools/launcher/core/src/mksimdevice.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/launcher/core/src/mksimdevice.rs b/tools/launcher/core/src/mksimdevice.rs index e923a9c2..76ccfa86 100644 --- a/tools/launcher/core/src/mksimdevice.rs +++ b/tools/launcher/core/src/mksimdevice.rs @@ -996,7 +996,7 @@ pub fn make(dev: &Path, jobs: &[String], env: &Env) -> Result { sim.put("X86SIM_A64_DEBUG_DIR", env.val("X86SIM_A64_DEBUG_DIR").map(String::from).unwrap_or_else(|| crate::rundir::run_dir().display().to_string())); // launchd jobs only see Bootstrap.Child: the JIT's flags and its scratch dir go through it for (k, v) in &env.0 { - if (k.starts_with("X86SIM_A64_") && k != "X86SIM_A64_EXE" && k != "X86SIM_A64_LOG") || ["SIMFB_HZ", "X86SIM_SCRATCH", "X86SIM_OSLOG", "X86SIM_OSLOG_DIR"].contains(&k.as_str()) { + if (k.starts_with("X86SIM_A64_") && k != "X86SIM_A64_EXE" && k != "X86SIM_A64_LOG") || ["SIMFB_HZ", "SIMFB_FILE_WRITE", "X86SIM_SCRATCH", "X86SIM_OSLOG", "X86SIM_OSLOG_DIR"].contains(&k.as_str()) { sim.put(k, v.clone()); } }