"""Run the Windows probe under Wine, sampling each quiescent phase in its cgroup.""" import argparse from concurrent.futures import ThreadPoolExecutor import json import os from pathlib import Path import stat import subprocess import time import xml.etree.ElementTree as ET MIB = 1 << 20 CACHE_PRIME = 96 * MIB CACHE_PER_WAVE = 32 * MIB WAVES = 4 TIMING_FIELDS = ( "allocation", "upload", "record_upload", "submit_upload", "fence_upload", "record_readback", "submit_readback", "fence_readback", "verify", ) def counters(path): return {key: int(value) for key, value in (line.split() for line in path.read_text().splitlines())} def memory(group): start = time.monotonic_ns() service_bytes = int((group / "memory.current").read_text()) peak = int((group / "memory.peak").read_text()) swap = int((group / "memory.swap.current").read_text()) stat_values = counters(group / "memory.stat") events = counters(group / "memory.events") pressure = (group / "memory.pressure").read_text().splitlines() return dict(counters_start_ns=start, monotonic_ns=time.monotonic_ns(), service_bytes=service_bytes, service_peak_bytes=peak, swap_bytes=swap, stat={k: stat_values.get(k) for k in ("anon", "file", "shmem", "pgscan_direct", "pgsteal_direct", "workingset_refault_anon", "workingset_refault_file")}, events=events, psi_us={row[0]: int(row[-1].split("=")[1]) for line in pressure if (row := line.split())}) def snapshot(group, gpu, pid): root = ET.fromstring(subprocess.check_output(["nvidia-smi", "-i", gpu, "-q", "-x"], timeout=3)) adapter = root.find("gpu") if adapter is None or adapter.findtext("uuid") != gpu: raise ValueError("expected the selected NVIDIA GPU UUID") clients = adapter.findall("./processes/process_info") service_pids = set((group / "cgroup.procs").read_text().split()) def mib(value): if value is None or value == "N/A": return None amount, unit = value.split() if unit != "MiB": raise ValueError(value) return int(amount) service_clients = {c.findtext("pid"): mib(c.findtext("used_memory")) for c in clients if c.findtext("pid") in service_pids} return dict(wine_launcher_pid=pid, client_vram_MiB=service_clients, device_vram_MiB=mib(adapter.findtext("fb_memory_usage/used")), **memory(group)) def read_cache(cache, destination, size): start = time.monotonic_ns() for _ in range(size // MIB): if cache.readinto(destination) != len(destination): raise ValueError("short read from the pressure fixture") return dict(start_ns=start, end_ns=time.monotonic_ns(), bytes=size) def run(wine, exe, mode, gpu, output, small, cache_file, destination): path = next(s[3:] for s in Path("/proc/self/cgroup").read_text().splitlines() if s.startswith("0::")) group = Path("/sys/fs/cgroup") / path.lstrip("/") # The soft and hard limits and a fresh private prefix belong to the calling service. if (group / "memory.max").read_text().strip() == "max" or not os.environ.get("WINEPREFIX"): raise RuntimeError("run in a bounded service with a private WINEPREFIX") phases = [("device", 0), *((p, w) for w in range(1, WAVES + 1) for p in ("verified", "between")), ("released", WAVES), ("idle", WAVES), ("device_dropped", WAVES)] size = 64 << 10 if small else 4 << 20 slots = (32 << 20) // size with output.open("x", buffering=1) as log, ThreadPoolExecutor(max_workers=1) as reader, subprocess.Popen( [wine, str(exe.resolve()), mode, "--sync", *(["--small"] if small else [])], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1, ) as child: seen = 0 timed_waves = 0 result = None active = None try: for line in child.stdout: received_ns = time.monotonic_ns() print(line, end="", flush=True) if line.startswith("TIMING "): finished = memory(group) _, wave, *times = line.split() timed_waves += 1 if int(wave) != timed_waves or len(times) != len(TIMING_FIELDS) or active is None: raise ValueError(f"unexpected timing record for wave {wave}") before, cache_read, ack_ns = active timing = dict(zip(TIMING_FIELDS, map(int, times), strict=True)) print(json.dumps(dict(phase="timing", wave=int(wave), timing_us=timing, before=before, ack_ns=ack_ns, timing_received_ns=received_ns, after=finished, cache=cache_read.result(timeout=3) if cache_read else None)), file=log) active = None if line.startswith("SAMPLE "): _, phase, wave, live, fixed, local, shared = line.split() if seen >= len(phases) or phases[seen] != (phase, int(wave)): raise ValueError(f"unexpected phase {phase}/{wave}") row = snapshot(group, gpu, child.pid) row.update(phase=phase, wave=int(wave), transient_bytes=int(live), transfer_bytes=int(fixed), dxgi_local=None if local == "NA" else int(local), dxgi_nonlocal=None if shared == "NA" else int(shared)) print(json.dumps(row), file=log) if phase == "device" and cache_file: prime = read_cache(cache_file, destination, CACHE_PRIME) print(json.dumps(dict(phase="cache_primed", cache=prime, **memory(group))), file=log) if phase == "device" or (phase == "between" and int(wave) < WAVES): before = memory(group) cache_read = reader.submit(read_cache, cache_file, destination, CACHE_PER_WAVE) if cache_file else None active = (before, cache_read, time.monotonic_ns()) if phase == "verified" and (active is not None or timed_waves != int(wave)): raise ValueError(f"missing timing record for wave {wave}") child.stdin.write("next\n") child.stdin.flush() seen += 1 if line.startswith("RESULT "): _, actual_mode, creates, fences, checked, micros = line.split() if (actual_mode, int(creates), int(fences), int(checked)) != ( mode, slots if mode == "reuse" else WAVES * slots, 2 * WAVES, 128 * MIB): raise ValueError("workload totals differ") result = dict(mode=mode, buffer_bytes=size, creates=int(creates), fences=int(fences), checked_bytes=int(checked), workload_us=int(micros)) if child.wait(timeout=3) or result is None or seen != len(phases): raise RuntimeError("incomplete workload") print(json.dumps(dict(phase="exit", **result, **snapshot(group, gpu, child.pid))), file=log) finally: if child.poll() is None: child.kill() def main(args): cache_file = args.pop("cache_file") if cache_file is None: run(**args, cache_file=None, destination=None) return with cache_file.open("rb", buffering=0) as cache: info = os.fstat(cache.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_size != CACHE_PRIME + CACHE_PER_WAVE * WAVES: raise ValueError("use a regular 224 MiB private disk-backed pressure fixture") os.posix_fadvise(cache.fileno(), 0, 0, os.POSIX_FADV_RANDOM) run(**args, cache_file=cache, destination=bytearray(MIB)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("wine") parser.add_argument("exe", type=Path) parser.add_argument("mode", choices=("release", "reuse", "hold")) parser.add_argument("gpu", help="NVIDIA GPU UUID selected by the D3D12 probe") parser.add_argument("output", type=Path) parser.add_argument("--small", action="store_true", help="use 64 KiB transient buffers") parser.add_argument("--cache-file", type=Path, help="read a cold 224 MiB private disk-backed file during the workload") main(vars(parser.parse_args()))