Skip to content
Open
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
78 changes: 71 additions & 7 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

#![allow(non_snake_case)]

use std::collections::{BTreeSet, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
Expand Down Expand Up @@ -92,6 +92,15 @@ pub struct ClassStat {
pub internal_slots: usize,
}

/// one debug layer message id and how often the debug layer reported it
#[derive(Debug, Default, Clone, Serialize, serde::Deserialize)]
pub struct DebugMsgStat {
pub id: i32,
pub count: u64,
/// its first message, cut to 200 characters – the log prints only the first few per id
pub first: String,
}

#[derive(Debug, Default, Clone, Serialize, serde::Deserialize)]
pub struct D3d12Stats {
pub backend: String,
Expand Down Expand Up @@ -130,6 +139,9 @@ pub struct D3d12Stats {
/// DXIL cache and compiler statistics.
#[serde(default)]
pub dxil_cache: crate::gpu::recomp::dxc::CacheStats,
/// debug layer messages seen, by message id – counted in full, past the log's per-id cap
#[serde(default)]
pub debug_layer: Vec<DebugMsgStat>,
}

static ADAPTER: Mutex<String> = Mutex::new(String::new());
Expand All @@ -139,6 +151,30 @@ static FAILED_PSO: AtomicU64 = AtomicU64::new(0);
static FALLBACK_RS: AtomicU64 = AtomicU64::new(0);
static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0);
static TRANSLATE_ERRORS: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// debug layer messages per message id, counted in full (the log prints only the first few)
static DEBUG_MSGS: Mutex<BTreeMap<i32, (u32, String)>> = Mutex::new(BTreeMap::new());

/// Counts a debug layer message id, keeps its first text and says whether it is still under the
/// log's per-id cap: the count grows after the printing stops, so the report shows what hides.
fn note_debug_message(msgs: &mut BTreeMap<i32, (u32, String)>, id: i32, text: &str) -> bool {
let e = msgs.entry(id).or_default();
e.0 += 1;
if e.0 == 1 {
e.1 = text.chars().take(200).collect();
}
e.0 <= DEBUG_MSG_LOG_LIMIT
}
const DEBUG_MSG_LOG_LIMIT: u32 = 8;

/// The report form of a per-id map: ids in order, each with its count and first text.
fn debug_layer_counts_from(msgs: &BTreeMap<i32, (u32, String)>) -> Vec<DebugMsgStat> {
msgs.iter().map(|(id, (n, first))| DebugMsgStat { id: *id, count: *n as u64, first: first.clone() }).collect()
}

/// debug layer messages seen, by message id, for the report
pub fn debug_layer_counts() -> Vec<DebugMsgStat> {
DEBUG_MSGS.lock().map(|g| debug_layer_counts_from(&g)).unwrap_or_default()
}
/// XCL shader ABI root signature on the backend device (raw, kept for the process lifetime)
static ABI_RS: AtomicUsize = AtomicUsize::new(0);

Expand Down Expand Up @@ -410,6 +446,7 @@ pub fn stats() -> D3d12Stats {
translation_errors: TRANSLATE_ERRORS.lock().map(|e| e.clone()).unwrap_or_default(),
background_pipelines: super::pso_async::counts(),
dxil_cache: crate::gpu::recomp::dxc::cache_stats(),
debug_layer: debug_layer_counts(),
}
}

Expand Down Expand Up @@ -561,22 +598,19 @@ pub fn init() -> Result<String, String> {
/// errors of a retail game, long before the message that came with its device removal.
unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, severity: D3D12_MESSAGE_SEVERITY, id: D3D12_MESSAGE_ID, text: windows::core::PCSTR, _context: *mut c_void) {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
static PER_ID: Mutex<Option<HashMap<i32, u32>>> = Mutex::new(None);
if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 {
return;
}
let t = if text.is_null() { String::new() } else { String::from_utf8_lossy(text.as_bytes()).into_owned() };
{
let mut g = PER_ID.lock().unwrap();
let n = g.get_or_insert_with(HashMap::new).entry(id.0).or_insert(0);
*n += 1;
if *n > 8 {
let mut g = DEBUG_MSGS.lock().unwrap();
if !note_debug_message(&mut g, id.0, &t) {
return;
}
}
if N.fetch_add(1, Ordering::Relaxed) >= 3000 {
return;
}
let t = if text.is_null() { String::new() } else { String::from_utf8_lossy(text.as_bytes()).into_owned() };
crate::xlog_warn!("D3D12 debug layer ({}, id {}): {t}", if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { "error" } else { "warning" }, id.0);
}

Expand Down Expand Up @@ -7165,3 +7199,33 @@ mod map_tests {
assert!(!parse(Some(40), Some(false)).DepthStencilState.DepthEnable.as_bool());
}
}

#[cfg(test)]
mod debug_layer_report_tests {
use super::*;

#[test]
fn counts_every_message_and_caps_only_the_printing() {
let mut msgs = BTreeMap::new();
let printed: Vec<bool> = (0..12).map(|_| note_debug_message(&mut msgs, 541, "state error")).collect();
assert_eq!(printed.iter().filter(|p| **p).count(), DEBUG_MSG_LOG_LIMIT as usize);
assert_eq!(msgs.get(&541).map(|m| m.0), Some(12), "the count grows after the printing stops");
assert_eq!(msgs.get(&541).map(|m| m.1.as_str()), Some("state error"), "the first text stays");
note_debug_message(&mut msgs, 725, &"x".repeat(400));
assert_eq!(msgs.get(&725).map(|m| m.1.chars().count()), Some(200), "the text is cut");
assert!(note_debug_message(&mut msgs, 999, "new"), "a new id prints");
}

#[test]
fn the_report_lists_ids_in_order_with_full_counts() {
// a local map: a concurrent GPU test with the layer on would feed the global one
let mut msgs = BTreeMap::new();
for _ in 0..3 {
note_debug_message(&mut msgs, 725, "simultaneous access");
}
note_debug_message(&mut msgs, 541, "state error");
let got = debug_layer_counts_from(&msgs);
assert_eq!(got.iter().map(|d| (d.id, d.count)).collect::<Vec<_>>(), vec![(541, 1), (725, 3)]);
assert_eq!(got[1].first, "simultaneous access");
}
}
12 changes: 12 additions & 0 deletions scripts/pr_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ def number(s):
return int(m.group(1)) if m else None


def smoke_ids(s):
"""The debug layer message ids of a `debug layer messages` line (`541x38 725x4`); None when
the line is absent or the run did not report them (`n/a`)."""
if not s or s.strip() in ("n/a", "none"):
return None
return {int(m.group(1)) for m in re.finditer(r"(\d+)x\d+", s)}


def field_problems(block, run):
"""What `block` (the smoke block of `run`) lacks for the comparison: a missing line or a
number that is not one."""
Expand Down Expand Up @@ -160,6 +168,10 @@ def check(body, head, files, is_main_ancestor, *, test_only=False):
pc, mc = number(pr.get("peak commit")), number(m.get("peak commit"))
if pc and mc and pc > COMMIT_GROWTH * mc:
problems.append(f"the PR's run commits much more memory than main's ({pc} MB against {mc} MB)")
pi, mi = smoke_ids(pr.get("debug layer messages")), smoke_ids(m.get("debug layer messages"))
if pi is not None and mi is not None and pi - mi:
problems.append("the PR's regression run reports debug layer message ids main's run did not ("
+ ", ".join(str(i) for i in sorted(pi - mi)) + "): new validation errors")
return problems


Expand Down
24 changes: 21 additions & 3 deletions scripts/smoke.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@
# prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built
# from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged").
#
# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title <label>]
# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title <label>] [-DebugLayer]
#
# The block's `title:` line is the first 8 hex digits of the SHA-256 of the game folder's name
# (trimmed, UTF-8), not the name itself, so PR descriptions do not name anyone's copy of a game (#677);
# -Title prints the given label instead. Use the same one for the main and the PR run.
#
# -DebugLayer runs the title with the D3D12 debug layer on, so the block's `debug layer messages`
# line has ids in it; it needs the Graphics Tools optional feature, and both runs of a pair get it.
#
# Networking is off (XCL_NETWORK=0). Build first: cargo build --release -p xcl
param(
[Parameter(Mandatory = $true)][string]$Game,
[int]$Seconds = 60,
[string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe'),
[string]$Title
[string]$Title,
[switch]$DebugLayer
)
$ErrorActionPreference = 'Stop'

Expand Down Expand Up @@ -50,6 +54,8 @@ $p.StartInfo = $psi
$env:XCL_NETWORK = '0'
$env:XCL_RUN_SECONDS = "$Seconds"
$env:XCL_ACTIVITY = '1'
$debugWas = Get-Item Env:XCL_D3D12_DEBUG -ErrorAction SilentlyContinue
if ($DebugLayer) { $env:XCL_D3D12_DEBUG = '1' }
$null = $p.Start()
$stdoutTask = $p.StandardOutput.ReadToEndAsync()
$stderrTask = $p.StandardError.ReadToEndAsync()
Expand All @@ -61,6 +67,9 @@ $p.WaitForExit()
$stdout = $stdoutTask.Result
$null = $stderrTask.Result
Remove-Item Env:XCL_RUN_SECONDS, Env:XCL_ACTIVITY
if ($DebugLayer) {
if ($debugWas) { Set-Item Env:XCL_D3D12_DEBUG $debugWas.Value } else { Remove-Item Env:XCL_D3D12_DEBUG -ErrorAction SilentlyContinue }
}

$logLine = ($stdout -split "`n" | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1)
if (-not $logLine) { throw "XCL printed no log path; its output:`n$stdout" }
Expand All @@ -77,9 +86,17 @@ $crashes = ([regex]::Matches($text, 'unhandled exception|process ends with statu
# the adapter XCL ran on (report.json next to the log; XCL removes the last run's at start),
# not the first one Windows lists – on a machine with an iGPU that is often not the one used
$gpu = $null
$dl = 'n/a'
$report = Join-Path (Split-Path $log -Parent) 'report.json'
if (Test-Path $report) {
try { $gpu = ((Get-Content $report -Raw -Encoding utf8 | ConvertFrom-Json).d3d12.adapter -replace '\s*\([^()]*VRAM\)$', '') } catch { }
try {
$rep = Get-Content $report -Raw -Encoding utf8 | ConvertFrom-Json
$gpu = $rep.d3d12.adapter -replace '\s*\([^()]*VRAM\)$', ''
if ($null -ne $rep.d3d12.debug_layer) {
$dl = (@($rep.d3d12.debug_layer | ForEach-Object { "$($_.id)x$($_.count)" }) -join ' ')
if (-not $dl) { $dl = 'none' }
}
} catch { }
}
if (-not $gpu) { $gpu = (Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1).Name }
$code = if ($timedOut) { 'killed (no exit)' } else { '0x{0:x}' -f $p.ExitCode }
Expand All @@ -97,5 +114,6 @@ presents per 2 s (last 3): $lastPresents
device removals: $removals
crashes: $crashes
peak commit: $peak MB
debug layer messages: $dl
``````
"@
16 changes: 16 additions & 0 deletions scripts/test_pr_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,22 @@ def test_non_numeric_frames_shown_fails(self):
self.assertIn("the PR's regression run (`xcl-smoke` block of commit 1234567890) "
"has a non-numeric `frames shown`: many", problems)

def test_debug_layer_ids_new_in_the_pr_fail(self):
run = "title: G\nseconds: 60\nframes shown: 100\ndevice removals: 0\ncrashes: 0\n"
problems = self.smoke_problems(run + "debug layer messages: 541x38\n",
run + "debug layer messages: 541x38 725x4\n")
self.assertEqual(1, len(problems), problems)
self.assertIn("725", problems[0])

def test_same_or_fewer_debug_layer_ids_and_no_line_pass(self):
run = "title: G\nseconds: 60\nframes shown: 100\ndevice removals: 0\ncrashes: 0\n"
for main_line, pr_line in (("debug layer messages: 541x38 725x4\n", "debug layer messages: 541x2\n"),
("debug layer messages: 541x38\n", "debug layer messages: none\n"),
("debug layer messages: 541x38\n", "debug layer messages: n/a\n"),
("", "")):
with self.subTest(main=main_line, pr=pr_line):
self.assertEqual([], self.smoke_problems(run + main_line, run + pr_line))


class TemplatePlaceholderTests(unittest.TestCase):
def test_untouched_pr_template_fails_all_required_sections(self):
Expand Down
Loading