Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions host/simfb/simfb.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
66 changes: 60 additions & 6 deletions linux/mtlvk/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<State> {
Self::new_for_gpu(device, out, false)
}

pub fn new_for_gpu(device: Device, out: Sink, is_cpu: bool) -> Res<State> {
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)");
}
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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,
) {
Expand All @@ -3389,7 +3410,7 @@ pub fn serve(
let out: Sink = Arc::new(move |op, seq, payload: Vec<u8>| {
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}");
Expand Down Expand Up @@ -4010,6 +4031,7 @@ mod tests {
serve(
0,
device,
false,
server,
#[cfg(feature = "surface-diag")]
false,
Expand Down Expand Up @@ -4608,4 +4630,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));
}
}
31 changes: 31 additions & 0 deletions linux/mtlvk/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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::<u64>().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))
Expand Down Expand Up @@ -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) => {
Expand All @@ -329,6 +345,7 @@ fn main() {
conn::serve(
n,
device,
is_cpu,
s,
#[cfg(feature = "surface-diag")]
surface_diag,
Expand All @@ -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")));
}
}
2 changes: 1 addition & 1 deletion tools/launcher/core/src/mksimdevice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -996,7 +996,7 @@ pub fn make(dev: &Path, jobs: &[String], env: &Env) -> Result<String> {
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());
}
}
Expand Down
41 changes: 39 additions & 2 deletions tools/launcher/core/src/services/jetsam.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -135,9 +136,10 @@ pub trait World {

/// X86SIM_JETSAM_<knob> 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<String> {
Expand Down Expand Up @@ -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()),
Expand Down Expand Up @@ -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"));
}
}
Loading