Skip to content
Draft
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
1 change: 1 addition & 0 deletions docs/ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ The launcher sets these for a Proton or Wine launch. A value you set yourself is
| `TUXBOX_SHADER_PREP_UI` | on for ProjectScarlett | `1` shows a desktop progress window |
| `TUXBOX_SCARLETT_SEED_PACK` | off | `1` prepares every shader in `shaders.rpf` |
| `TUXBOX_LARGE_COMPILES` | `4` | Large compute pipelines compiling at once; `0` removes the limit |
| `TUXBOX_TRACE_PIPELINE_REQUESTS` | `0` | With diagnostic logging enabled, also log start and completion of short slot-62 compute pipeline attempts, including the selected shader cache request key and byte size |
| `TUXBOX_PIPELINE_DEADLINE` | `20` | Seconds before a large compile gets an empty stand-in; `0` waits |
| `TUXBOX_NULL_PIPELINES` | on | `0` fails unsupported pipelines instead of giving empty stand-ins |
| `TUXBOX_PROGRESS_OVERLAY` | `auto` | `always` or `0` for the progress panel |
Expand Down
31 changes: 31 additions & 0 deletions docs/PROJECTSCARLETT.md
Original file line number Diff line number Diff line change
Expand Up @@ -831,3 +831,34 @@ The issue #39 log contains 262 failed driver allocation attempts and
131 host import failure messages, not a confirmed VRAM exhaustion or
a proven fault in these provider call sites. The opt-in trace is intended
to distinguish those possibilities in a subsequent authorized run.


### Identify a slow slot-62 compute pipeline request

With diagnostic logging enabled, slow `CreatePipelineState #N CS ...`
messages include `request=<key> bytes=<size>`. The short CS hash still
identifies the original guest program, while the full request key names
the actual selected translation (`<key>.cso` in the shader cache), including
a root-specific request or its `_w32` variant. `request=original` means the
original bytecode was passed to the host, not a translated cache entry.
Set `TUXBOX_TRACE_PIPELINE_REQUESTS=1` to also record starts and finishes of
short attempts. The identifier after `#` is local to the process.
Times include any compile-slot wait and the host pipeline call; they do not
isolate the driver. This currently covers the Xbox slot-62 compute factory,
not all graphics or pipeline-stream paths. Share keys and sizes only, not
title shader files or private raw logs.


To test the memory-pressure hypothesis in issue #231, sample the actual
guest process (not the UMU parent) during the cold launch:

```sh
python tools/sample_process_cpu.py PID --seconds 300 --interval 1 --output cold-memory.jsonl
```

The samples share the existing UTC nanosecond timestamp and include host
available RAM, total/free/used swap, guest RSS, peak RSS and guest swap in
KiB. Missing fields are null. Compare timestamps with the pipeline log;
neither a large swap value nor a slow pipeline alone establishes causation.
The sampler does not attribute host memory to individual driver threads.
Keep detailed samples local; share aggregate memory observations.
13 changes: 12 additions & 1 deletion runtime/d3d12/src/big_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,9 @@ impl PipelineWatch {
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let started = std::time::Instant::now();
flights().push(Flight { id, label: label.to_string(), started, next_due: 5 });
if request_trace(label) {
crate::diagnostics::log(&format!("CreatePipelineState #{id} {label} started"));
}
Self { id: Some(id), label: label.to_string(), started }
}
}
Expand All @@ -365,7 +368,7 @@ impl Drop for PipelineWatch {
let Some(id) = self.id else { return };
let elapsed = self.started.elapsed().as_secs();
flights().retain(|flight| flight.id != id);
if elapsed >= 5 {
if elapsed >= 5 || request_trace(&self.label) {
crate::diagnostics::log(&format!(
"CreatePipelineState #{id} {} finished in {elapsed}s",
self.label
Expand All @@ -374,6 +377,14 @@ impl Drop for PipelineWatch {
}
}

// Opt-in for short, successful pipeline calls too. Ordinary diagnostics
// continue to report only slow calls, now with exact request attribution.
fn request_trace(label: &str) -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
label.starts_with("CS ") && label.contains(" request=")
&& *ENABLED.get_or_init(|| std::env::var("TUXBOX_TRACE_PIPELINE_REQUESTS").as_deref() == Ok("1"))
}

fn flights() -> std::sync::MutexGuard<'static, Vec<Flight>> {
static FLIGHTS: std::sync::Mutex<Vec<Flight>> = std::sync::Mutex::new(Vec::new());
FLIGHTS.lock().unwrap_or_else(|error| error.into_inner())
Expand Down
57 changes: 39 additions & 18 deletions runtime/d3d12/src/device/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ unsafe fn create_pipeline_x_inner(
// root and fills only the slots the appended signature adds.
let mut table = table;
let mut code = super::shader_cache::compute_with_root(bytes, table.layout.payload())
.or_else(|| super::shader_cache::prepared(bytes));
.or_else(|| super::shader_cache::prepared_compute(bytes));
// A heap-indexed IDXEN access needs each slot's buffer stride: retry
// on the same root with the arena's stride table appended.
if code.is_none() && super::shader_cache::refused_for_heap_strides(bytes, table.layout.payload())
Expand Down Expand Up @@ -277,18 +277,24 @@ unsafe fn create_pipeline_x_inner(
sampler_root = Some(native);
(Some(code), None)
}
None => (super::shader_cache::prepared(bytes).or_else(|| {
None => (super::shader_cache::prepared_compute(bytes).or_else(|| {
super::shader_cache::compute_with_root(bytes, root?.state.payload())
}), None),
}
}
};
let compute_threads = guest_threads
.or_else(|| translation.as_deref().and_then(tuxbox_dxbc::shader_compute_threads));
.or_else(|| translation.as_ref().and_then(|t| tuxbox_dxbc::shader_compute_threads(&t.code)));
// The group size above is the console's. A narrow-wave translation runs the
// same group on half as many host threads, so it is chosen only now.
let translation = translation.map(|code| fitting_translation(this, code));
let code = translation.as_deref().unwrap_or(bytes);
let translation = translation.map(|mut translated| {
if let Some((code, request)) = narrow_translation(this, &translated.code) {
translated.code = code;
translated.request = request;
}
translated
});
let code = translation.as_ref().map_or(bytes, |t| t.code.as_slice());
if let Some(refusal) = unsupported_wave_size(this, code) {
crate::diagnostics::compute_wave_failure(bytes, &refusal.detail);
crate::failures::refusal("CS", &refusal.tag);
Expand All @@ -299,7 +305,7 @@ unsafe fn create_pipeline_x_inner(
match super::compute_scene::private_root(
&this.native,
bytes,
translated,
&translated.code,
root.map(|p| &p.state),
desc.NodeMask,
) {
Expand All @@ -309,9 +315,9 @@ unsafe fn create_pipeline_x_inner(
} else {
None
};
let label = super::shader_cache::source_digest(bytes)
.map(|hash| format!("CS {}", &hash[..8]))
.unwrap_or_else(|| "CS".to_string());
let source = super::shader_cache::source_digest(bytes);
let label = compute_compile_label(source.as_deref(), translation.as_ref().map(|t| t.request.as_str()), code.len());
let original_label = compute_compile_label(source.as_deref(), None, bytes.len());
let mut host = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: ManuallyDrop::new(
scene_root
Expand All @@ -333,14 +339,14 @@ unsafe fn create_pipeline_x_inner(
// The driver compile must own its device, root signature, and shader bytes:
// a deadline can return while that compile is still writing the GPU cache.
let signature = core::mem::ManuallyDrop::into_inner(host.pRootSignature.clone());
let compile = |shader: &[u8]| {
let compile = |shader: &[u8], label: &str| {
let device = this.native.clone();
let signature = signature.clone();
let shader = shader.to_vec();
let node_mask = desc.NodeMask;
let flags = desc.Flags;
let name = label.clone();
crate::big_stack::run_deadline(&label, move || {
let name = label.to_owned();
crate::big_stack::run_deadline(label, move || {
// Large programs queue here so the driver does not compile them
// all at once. The queue is on the detached compile thread, so the
// title's own thread still returns at the deadline.
Expand Down Expand Up @@ -369,7 +375,7 @@ unsafe fn create_pipeline_x_inner(
owned_compile(device, signature, shader, node_mask, flags)
})
} else {
match compile(code) {
match compile(code, &label) {
crate::big_stack::PipelineWait::Ready(result) => result,
crate::big_stack::PipelineWait::Deferred => {
// The original guest shader would be a second long driver compile.
Expand All @@ -382,7 +388,7 @@ unsafe fn create_pipeline_x_inner(
if translation.is_some() && reflected.is_none() && scene_root.is_none() && native.is_err() {
// Structural checks cannot validate DXIL instructions or root bindings.
// Let the adapter handle the original guest shader if it rejects the cache.
native = match compile(bytes) {
native = match compile(bytes, &original_label) {
crate::big_stack::PipelineWait::Ready(result) => result,
crate::big_stack::PipelineWait::Deferred => {
crate::failures::refusal("CS", "driver compile deadline");
Expand Down Expand Up @@ -536,11 +542,26 @@ pub(super) fn check_wave_range(required: (u32, u32), host: (u32, u32)) -> Option
/// `translation`, or the narrow-wave translation of the same program when this
/// host cannot run it and the compiler can produce one.
pub(super) fn fitting_translation(device: &Device, translation: Vec<u8>) -> Vec<u8> {
let Some(host) = super::host_profile::wave_range(device) else { return translation };
if !needs_narrow_waves(super::shader_cache::portable_wave_range(&translation), host) {
return translation;
narrow_translation(device, &translation).map(|(code, _)| code).unwrap_or(translation)
}

fn narrow_translation(device: &Device, translation: &[u8]) -> Option<(Vec<u8>, String)> {
let host = super::host_profile::wave_range(device)?;
if !needs_narrow_waves(super::shader_cache::portable_wave_range(translation), host) {
return None;
}
super::shader_cache::narrow_wave_variant(translation)
}

/// Keep the familiar short guest hash, but identify the exact compiler
/// request selected for this attempt, including rooted and narrow variants.
/// A retry with original guest bytes must never name a translated cache file.
fn compute_compile_label(source: Option<&str>, request: Option<&str>, bytes: usize) -> String {
let short = source.and_then(|s| s.get(..8)).unwrap_or("unknown");
match request {
Some(key) => format!("CS {short} request={key} bytes={bytes}"),
None => format!("CS {short} request=original bytes={bytes}"),
}
super::shader_cache::narrow_wave_variant(&translation).unwrap_or(translation)
}

/// Whether a program that needs exactly 64 lanes meets a host that has fewer.
Expand Down
36 changes: 28 additions & 8 deletions runtime/d3d12/src/device/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,9 +308,25 @@ pub(super) fn prepared(shader: &[u8]) -> Option<Vec<u8>> {

/// A shader may receive its root signature only at pipeline creation. Include
/// the actual signature in the compiler request and cache key for that variant.
pub(super) fn compute_with_root(shader: &[u8], root: &[u8]) -> Option<Vec<u8>> {
pub(super) struct ComputeTranslation {
pub code: Vec<u8>,
pub request: String,
}

pub(super) fn prepared_compute(shader: &[u8]) -> Option<ComputeTranslation> {
let (Stage::Compute, ShaderCode::Xbox) = shader_code(shader)? else { return None };
translate(&with_root(shader, root)?, Stage::Compute)
translate_compute(shader)
}

fn translate_compute(shader: &[u8]) -> Option<ComputeTranslation> {
let request = source_digest(shader)?;
let code = translate_keyed(shader, Stage::Compute, &request)?;
Some(ComputeTranslation { code, request })
}

pub(super) fn compute_with_root(shader: &[u8], root: &[u8]) -> Option<ComputeTranslation> {
let (Stage::Compute, ShaderCode::Xbox) = shader_code(shader)? else { return None };
translate_compute(&with_root(shader, root)?)
}

/// Whether the translator refused this program on this root only for want of
Expand All @@ -326,11 +342,11 @@ pub(super) fn refused_for_heap_strides(shader: &[u8], root: &[u8]) -> bool {
/// embedded root is the pipeline root needs the ordinary prepared translation;
/// any other program must use the actual pipeline root (never silently fall
/// back to a rootless variant or to a different embedded root).
pub(super) fn compute_for_original_root(shader: &[u8], root: &[u8]) -> Option<Vec<u8>> {
pub(super) fn compute_for_original_root(shader: &[u8], root: &[u8]) -> Option<ComputeTranslation> {
let dxbc = tuxbox_dxbc::Dxbc::parse(shader).ok()?;
let embedded = dxbc.chunk(b"RTS0").and_then(|c| shader.get(c.offset..c.offset + c.size));
if embedded == Some(root) {
prepared(shader)
prepared_compute(shader)
} else {
compute_with_root(shader, root)
}
Expand Down Expand Up @@ -526,10 +542,14 @@ pub(super) fn mesh_stage(

fn translate(shader: &[u8], stage: Stage) -> Option<Vec<u8>> {
let source = source_digest(shader)?;
let translation = read_portable("by_source", &source, stage)
.or_else(|| compile::on_demand(shader, &source, stage));
stage.report(&source, translation.is_some());
crate::failures::lookup(stage.short(), &source, translation.is_some());
translate_keyed(shader, stage, &source)
}

fn translate_keyed(shader: &[u8], stage: Stage, source: &str) -> Option<Vec<u8>> {
let translation = read_portable("by_source", source, stage)
.or_else(|| compile::on_demand(shader, source, stage));
stage.report(source, translation.is_some());
crate::failures::lookup(stage.short(), source, translation.is_some());
if stage == Stage::Compute && let Some(code) = translation.as_deref() {
narrow_waves::remember(code, shader);
}
Expand Down
4 changes: 2 additions & 2 deletions runtime/d3d12/src/device/shader_cache/narrow_waves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub(super) fn remember(translation: &[u8], shader: &[u8]) {

/// Ask the compiler to translate the program behind `translation` for 32-lane
/// waves. `None` leaves the caller to refuse the ordinary translation as before.
pub(crate) fn narrow_wave_variant(translation: &[u8]) -> Option<Vec<u8>> {
pub(crate) fn narrow_wave_variant(translation: &[u8]) -> Option<(Vec<u8>, String)> {
let shader = sources().get(&source_digest(translation)?)?.clone();
let source = source_digest(&shader)?;
let variant = compile::narrow_wave(&shader, &source)?;
Expand All @@ -33,5 +33,5 @@ pub(crate) fn narrow_wave_variant(translation: &[u8]) -> Option<Vec<u8>> {
if LOADED.lock().unwrap_or_else(|error| error.into_inner()).insert(source.clone()) {
crate::diagnostics::log(&format!("narrow-wave compute shader loaded, source SHA-256 {source}"));
}
Some(variant)
Some((variant, format!("{source}_w32")))
}
13 changes: 13 additions & 0 deletions runtime/d3d12/src/tests/device/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,16 @@ fn only_a_64_lane_program_on_a_32_lane_host_is_translated_again() {
// The translation runs waves of 32, so a host limited below that cannot use it.
assert!(!needs_narrow_waves(Some((64, 64)), (16, 16)));
}

#[test]
fn compute_compile_labels_distinguish_rooted_narrow_and_original_attempts() {
let guest = "a".repeat(64);
let rooted = "b".repeat(64);
let narrow = format!("{rooted}_w32");
assert_eq!(compute_compile_label(Some(&guest), Some(&rooted), 123),
format!("CS aaaaaaaa request={rooted} bytes=123"));
assert_eq!(compute_compile_label(Some(&guest), Some(&narrow), 456),
format!("CS aaaaaaaa request={narrow} bytes=456"));
assert_eq!(compute_compile_label(Some(&guest), None, 789),
"CS aaaaaaaa request=original bytes=789");
}
34 changes: 34 additions & 0 deletions tests/test_sample_process_cpu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Memory sampling keeps missing data separate from actual zero use."""
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from tools.sample_process_cpu import memory_sample


class ProcessMemoryTests(unittest.TestCase):
def test_reads_real_units_and_calculates_used_swap(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
meminfo = root / "meminfo"
meminfo.write_text("MemTotal: 98304 kB\nMemAvailable: 8192 kB\nSwapTotal: 32768 kB\nSwapFree: 128 kB\n")
(root / "status").write_text("VmRSS: 5120 kB\nVmHWM: 8192 kB\nVmSwap: 0 kB\n")
self.assertEqual(memory_sample(root, meminfo), {
"host_available_kib": 8192, "host_total_kib": 98304,
"host_swap_total_kib": 32768, "host_swap_free_kib": 128,
"host_swap_used_kib": 32640, "process_rss_kib": 5120,
"process_peak_rss_kib": 8192, "process_swap_kib": 0,
})

def test_partial_or_malformed_data_is_not_zero(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
meminfo = root / "meminfo"
meminfo.write_text("MemTotal: bad kB\nMemAvailable: -1 kB\nSwapTotal: 10 kB\nSwapFree: 20 kB\n")
(root / "status").write_text("VmRSS: 2 MB\nVmSwap: 4 kB\n")
result = memory_sample(root, meminfo)
for key in ("host_total_kib", "host_available_kib", "host_swap_used_kib",
"process_rss_kib", "process_peak_rss_kib"):
self.assertIsNone(result[key])
self.assertEqual(result["process_swap_kib"], 4)
self.assertTrue(all(v is None for v in memory_sample(root / "absent", root / "absent").values()))
40 changes: 39 additions & 1 deletion tools/sample_process_cpu.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Sample a running Linux game's process and thread CPU usage independently of graphics presents."""
"""Sample Linux game CPU and memory pressure independently of graphics presents."""
import argparse
import json
import os
Expand All @@ -15,6 +15,43 @@ def stat(path):
return name, int(fields[19]), int(fields[11]) + int(fields[12])


def memory_fields(path, wanted):
"""Read selected procfs KiB fields; missing or invalid values stay unknown."""
values = dict.fromkeys(wanted)
try:
for line in path.read_text().splitlines():
name, sep, body = line.partition(":")
if not sep or name not in wanted:
continue
fields = body.split()
if len(fields) == 2 and fields[1] == "kB":
try:
value = int(fields[0])
except ValueError:
continue
if value >= 0:
values[name] = value
except OSError:
pass
return values


def memory_sample(proc, meminfo=Path("/proc/meminfo")):
host = memory_fields(meminfo, ("MemTotal", "MemAvailable", "SwapTotal", "SwapFree"))
task = memory_fields(proc / "status", ("VmRSS", "VmHWM", "VmSwap"))
total, free = host["SwapTotal"], host["SwapFree"]
return {
"host_available_kib": host["MemAvailable"],
"host_total_kib": host["MemTotal"],
"host_swap_total_kib": total,
"host_swap_free_kib": free,
"host_swap_used_kib": total - free if total is not None and free is not None and total >= free else None,
"process_rss_kib": task["VmRSS"],
"process_peak_rss_kib": task["VmHWM"],
"process_swap_kib": task["VmSwap"],
}


def snapshot(proc):
_, birth, ticks = stat(proc / "stat")
threads = {}
Expand Down Expand Up @@ -59,6 +96,7 @@ def sample(pid, seconds, interval, output):
"host_busy_percent": (round(100 * (1 - (idle - previous[4]) / host_ticks), 2)
if host_ticks > 0 else None),
"threads": sorted(active, key=lambda thread: thread["cpu_ticks"], reverse=True),
"memory": memory_sample(proc),
}
output.write(json.dumps(row, separators=(",", ":")) + "\n")
output.flush()
Expand Down
Loading