feat(display): edid_lock policy axis — pin AMD connector EDID emulation while streaming
windows / build (x86_64-pc-windows-msvc) (pull_request) Successful in 2m45s
apple / swift (pull_request) Successful in 1m45s
apple / screenshots (pull_request) Skipped
windows / build (aarch64-pc-windows-msvc) (pull_request) Successful in 1m14s
ci / web (pull_request) Successful in 1m27s
ci / bun-nix (pull_request) Successful in 34s
android / android (pull_request) Successful in 5m52s
ci / rust (pull_request) Failing after 7m55s
ci / docs-site (pull_request) Successful in 7m54s
ci / rust-arm64 (pull_request) Successful in 9m13s
nix / flake (pull_request) Successful in 14m26s

Productizes the adl-emul probe (the prior commit) as the display-policy axis its
PR promised: the ADL FFI moves to pf_win_display::adl_emul (one surface shared by
the probe tool and the host, so a reporter's probe and the console's toggle
exercise byte-identical driver calls), and an EXPERIMENTAL edid_lock axis joins
ddc_power_off/pnp_disable_monitors — orthogonal to presets, off by default.

At the first Exclusive isolate the host pins each occupied AMD connector's live
EDID + ADL_EMUL_MODE_ALWAYS (the software HPD dummy) BEFORE the physicals
deactivate; last-member teardown unlocks. Pinned emulation outlives the process,
so a crash journal (edid-lock-active.json) unlocks on the next host start,
mirroring the pnp_disable_monitors recovery. Inert without an AMD driver.

The console shows the toggle ONLY when the GPU inventory lists an AMD adapter —
the lever exists nowhere else, and a toggle that can never act is the 'saved and
then did nothing' trap the enforced-axes list exists to prevent.
This commit is contained in:
2026-08-12 08:47:42 +02:00
parent a0577cb86e
commit f4e39a442b
14 changed files with 819 additions and 518 deletions
Generated
+1
View File
@@ -1116,6 +1116,7 @@ dependencies = [
name = "display-disturb"
version = "0.27.0"
dependencies = [
"pf-win-display",
"windows 0.62.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
+4
View File
@@ -4753,6 +4753,10 @@
"type": "boolean",
"description": "EXPERIMENTAL (Windows): command physical monitors' panels off over DDC/CI (VCP 0xD6 →\nDPMS off) right before an `Exclusive` isolate deactivates them, and back on at restore.\nTargets the \"connected-but-dark head\" periodic-stutter class (monitor standby\nauto-input-scan / DP link churn while the virtual display is the sole active display) at\nthe monitor-firmware level. Best-effort — monitors without DDC/CI (or with it disabled in\nthe OSD) are skipped. Orthogonal to `preset` (like `game_session`): preserved across\npreset changes; `#[serde(default)]` = off so existing `display-settings.json` files are\nuntouched."
},
"edid_lock": {
"type": "boolean",
"description": "**EXPERIMENTAL, AMD-only in effect: pin connector EDID emulation while streaming** — the\nsoftware equivalent of an HPD-holding dummy plug (`pf_win_display::adl_emul`). Locked at\nthe first Exclusive isolate BEFORE the physicals deactivate (an awake sink answers its\nlive-EDID read), unlocked at last-member teardown, crash-journaled so a dead host unlocks\non its next start. Targets the standby-sink stall class at its SOURCE: with emulation\npinned the KMD stops servicing the sleeping sink's HPD/DDC/link. Inert without an AMD\ndriver (`atiadlxx.dll` absent) and on non-Windows. Orthogonal to `preset` (like\n`game_session`); `#[serde(default)]` = off."
},
"game_session": {
"$ref": "#/components/schemas/GameSession",
"description": "How a game-launching session is served (`design/gamemode-and-dedicated-sessions.md` §5.2).\nOrthogonal to `preset`/lifecycle — preserved across preset changes; `#[serde(default)]` = `Auto`\nso existing `display-settings.json` files are untouched."
+26 -3
View File
@@ -267,6 +267,16 @@ pub struct DisplayPolicy {
/// startup. Orthogonal to `preset` (like `game_session`); `#[serde(default)]` = off.
#[serde(default)]
pub pnp_disable_monitors: bool,
/// **EXPERIMENTAL, AMD-only in effect: pin connector EDID emulation while streaming** — the
/// software equivalent of an HPD-holding dummy plug (`pf_win_display::adl_emul`). Locked at
/// the first Exclusive isolate BEFORE the physicals deactivate (an awake sink answers its
/// live-EDID read), unlocked at last-member teardown, crash-journaled so a dead host unlocks
/// on its next start. Targets the standby-sink stall class at its SOURCE: with emulation
/// pinned the KMD stops servicing the sleeping sink's HPD/DDC/link. Inert without an AMD
/// driver (`atiadlxx.dll` absent) and on non-Windows. Orthogonal to `preset` (like
/// `game_session`); `#[serde(default)]` = off.
#[serde(default)]
pub edid_lock: bool,
/// **Mirror a physical monitor instead of creating a virtual display**: the connector name
/// (`DP-1`, `HDMI-A-2`) sessions should stream, or `None` for the normal virtual-display path.
///
@@ -318,6 +328,7 @@ impl Default for DisplayPolicy {
game_session: GameSession::default(),
ddc_power_off: false,
pnp_disable_monitors: false,
edid_lock: false,
capture_monitor: None,
}
}
@@ -454,6 +465,7 @@ impl EffectivePolicy {
game_session: GameSession,
ddc_power_off: bool,
pnp_disable_monitors: bool,
edid_lock: bool,
capture_monitor: Option<String>,
) -> DisplayPolicy {
DisplayPolicy {
@@ -474,6 +486,7 @@ impl EffectivePolicy {
game_session,
ddc_power_off,
pnp_disable_monitors,
edid_lock,
capture_monitor,
}
}
@@ -739,6 +752,13 @@ impl DisplayPolicyStore {
self.get().pnp_disable_monitors
}
/// The experimental AMD connector-EDID-emulation axis — orthogonal to the preset (like
/// [`Self::game_session`]), read directly off the stored policy (default off when
/// unconfigured).
pub fn edid_lock(&self) -> bool {
self.get().edid_lock
}
/// Persist + adopt a new policy (sanitized first). The in-memory value changes only if the disk
/// write succeeds, so a full disk can't leave memory and file disagreeing — and the whole
/// transaction runs under [`Self::write`], so neither can two concurrent PUTs.
@@ -1318,13 +1338,16 @@ mod tests {
GameSession::Dedicated,
true,
true,
true,
Some("DP-2".into()),
);
// The orthogonal axes (game-session, DDC power-off, PnP disable, capture-monitor pin) are
// preserved through the transform — arranging displays must not clear an unrelated setting.
// The orthogonal axes (game-session, DDC power-off, PnP disable, EDID lock,
// capture-monitor pin) are preserved through the transform — arranging displays must not
// clear an unrelated setting.
assert_eq!(p.game_session, GameSession::Dedicated);
assert!(p.ddc_power_off);
assert!(p.pnp_disable_monitors);
assert!(p.edid_lock);
assert_eq!(p.capture_monitor.as_deref(), Some("DP-2"));
// Preset drops to Custom so the explicit fields (incl. the layout) rule…
assert_eq!(p.preset, Preset::Custom);
@@ -1405,7 +1428,7 @@ mod tests {
let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
assert_eq!(
keys.len(),
12,
13,
"a display-policy axis was added or removed: {keys:?} — wire it into the mgmt PUT's \
per-axis merge (and into `EffectivePolicy` if it is a behavior axis) before bumping this"
);
@@ -178,6 +178,10 @@ struct GroupState {
/// PnP instance ids of monitor devnodes the EXPERIMENTAL `pnp_disable_monitors` axis disabled at
/// the group's first isolate — last-member teardown re-enables them BEFORE the CCD restore.
pnp_disabled: Vec<String>,
/// Whether the EXPERIMENTAL `edid_lock` axis pinned AMD connector emulation at the group's
/// first isolate (`pf_win_display::adl_emul::lock_for_stream`) — last-member teardown owes the
/// unlock (pinned emulation outlives the process, so a crash journal backs this flag up).
edid_locked: bool,
/// Whether `ccd_saved` was captured by an EXCLUSIVE isolate (vs `Primary`, which also
/// snapshots but deliberately keeps the physical displays active) — gates the re-assert
/// watchdog, which must never "fix" a Primary group's lit panels. Cleared with the restore.
@@ -1400,6 +1404,18 @@ impl VirtualDisplayManager {
if crate::policy::prefs().ddc_power_off() {
inner.group.ddc_panels_off = crate::ddc::panel_off_except(n);
}
// EXPERIMENTAL `edid_lock` policy axis (AMD only): pin connector EDID
// emulation BEFORE the isolate deactivates the physicals — an awake
// sink still answers the live-EDID read the lock pins (asleep sinks
// fall back to the driver's stored emulation data). With emulation at
// ADL_EMUL_MODE_ALWAYS the KMD stops servicing the sleeping sink's
// HPD/DDC/link — the standby-sink stall class at its source
// (rationale + crash journal in `pf_win_display::adl_emul`). First
// member only, like the DDC leg: the connectors are host-wide.
if crate::policy::prefs().edid_lock() {
inner.group.edid_locked =
pf_win_display::adl_emul::lock_for_stream();
}
inner.group.ccd_saved = isolate_displays_ccd_seam(&keep);
// EXPERIMENTAL `pnp_disable_monitors` policy axis: AFTER the isolate took,
// additionally disable the deactivated monitors' PnP devnodes (persistent
@@ -1958,6 +1974,15 @@ impl VirtualDisplayManager {
);
inner.group.ddc_panels_off = 0;
}
// EXPERIMENTAL `edid_lock` unlock. AFTER the CCD restore + DDC wake: the re-activated
// physical paths do not depend on it (the pinned emulation IS the real monitor's
// EDID), and unlocking last keeps the driver from re-probing the sinks mid-restore.
// OUTSIDE the `ccd_saved` gate for the same reason as the DDC wake above — the lock
// was applied BEFORE the isolate, whose snapshot capture can have failed.
if inner.group.edid_locked {
pf_win_display::adl_emul::unlock_after_stream();
inner.group.edid_locked = false;
}
} else {
match shrink_action(inner.group.ccd_exclusive, inner.group.ccd_saved.is_some()) {
// Re-issue the isolate over the shrunk set (defensive — the departing monitor's
+689
View File
@@ -0,0 +1,689 @@
//! AMD ADL connector/EDID emulation — the shared implementation behind the `display-disturb
//! adl-emul` probe AND the `edid_lock` display-policy axis (the software equivalent of an
//! HPD-holding dummy plug).
//!
//! Three field cases (ASUS VG32VQ1B/DP, Odyssey G60SD/DP, LG UltraGear 32GS95UE/HDMI — all
//! RX 9070 XT hosts) share one mechanism: a connected-but-asleep sink whose standby HPD/DDC/link
//! servicing the KMD performs below every OS lever (CCD deactivation, devnode disable and CRU
//! EDID overrides are confirmed no-ops — `design/vdisplay-disturbance-immunity.md` §2a/§3). The
//! one software lever that can stop the servicing at its SOURCE is the driver's own connector
//! emulation: pin the live EDID with `ADL2_Adapter_ConnectionData_Set`, then
//! `ADL2_Adapter_EmulationMode_Set(ADL_EMUL_MODE_ALWAYS)` so the driver stops caring what the
//! physical pins report.
//!
//! [`run`] performs one action across every AMD adapter's connectors and returns the per-op
//! [`OpRecord`]s — the probe tool prints them as bench lines, the host tracing-logs them. The
//! `edid_lock` axis drives [`lock_for_stream`]/[`unlock_after_stream`] at the Exclusive isolate
//! (`pf-vdisplay`'s Windows manager), with a crash journal ([`startup_recover`]) because pinned
//! emulation persists across host restarts — and can persist across REBOOTS, so every lock ships
//! with its unlock (driver reinstall = the escape hatch of last resort).
//!
//! Everything is best-effort by design: no AMD driver (`atiadlxx.dll` absent) means the axis is
//! inert, and each rc is preserved so a field log answers the consumer-vs-Pro gating question
//! (`ADL_ERR_NOT_SUPPORTED(-8)` vs `ADL_OK`).
// FFI mirrors of ADL's C structs — keep AMD's field names verbatim so the header diff is
// mechanical.
#![allow(non_snake_case)]
use std::ffi::c_void;
use std::time::Instant;
use windows::core::{s, PCSTR};
use windows::Win32::Foundation::HMODULE;
use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
// ---- ADL constants (adl_defines.h, GPUOpen display-library) ----
const ADL_OK: i32 = 0;
const ADL_MAX_PATH: usize = 256;
const ADL_MAX_DISPLAY_EDID_DATA_SIZE: usize = 1024;
const ADL_MAX_RAD_LINK_COUNT: usize = 15;
const ADL_EMUL_MODE_OFF: i32 = 0;
const ADL_EMUL_MODE_ALWAYS: i32 = 3;
const ADL_QUERY_REAL_DATA: i32 = 0;
const ADL_QUERY_EMULATED_DATA: i32 = 1;
const ADL_EMUL_STATUS_REAL_DEVICE_CONNECTED: i32 = 0x1;
const ADL_EMUL_STATUS_EMULATED_DEVICE_PRESENT: i32 = 0x2;
const ADL_EMUL_STATUS_EMULATED_DEVICE_USED: i32 = 0x4;
const AMD_VENDOR_ID: i32 = 1002;
/// Decode the rc values a field log will actually contain (adl_defines.h) — `-8` vs `-1` is the
/// whole consumer-vs-Pro question, so spell them out.
pub fn rc_str(rc: i32) -> &'static str {
match rc {
0 => "ADL_OK",
1..=4 => "ADL_OK_(warning-class)",
-1 => "ADL_ERR",
-2 => "ADL_ERR_NOT_INIT",
-3 => "ADL_ERR_INVALID_PARAM",
-5 => "ADL_ERR_INVALID_ADL_IDX",
-8 => "ADL_ERR_NOT_SUPPORTED",
-9 => "ADL_ERR_NULL_POINTER",
-10 => "ADL_ERR_DISABLED_ADAPTER",
-22 => "ADL_ERR_CALL_TO_INCOMPATIABLE_DRIVER",
-23 => "ADL_ERR_NO_ADMINISTRATOR_PRIVILEGES",
_ => "?",
}
}
fn connector_type_str(t: i32) -> &'static str {
match t {
1 => "VGA",
2 => "DVI-D",
3 => "DVI-I",
8 => "HDMI-A",
9 => "HDMI-B",
10 => "DP",
11 => "eDP",
12 => "miniDP",
13 => "VIRTUAL",
14 => "USB-C",
_ => "unknown",
}
}
// ---- ADL structs (adl_structures.h, verbatim layouts) ----
#[repr(C)]
struct AdapterInfo {
iSize: i32,
iAdapterIndex: i32,
strUDID: [u8; ADL_MAX_PATH],
iBusNumber: i32,
iDeviceNumber: i32,
iFunctionNumber: i32,
iVendorID: i32,
strAdapterName: [u8; ADL_MAX_PATH],
strDisplayName: [u8; ADL_MAX_PATH],
iPresent: i32,
// _WIN32 tail — this tool only builds for Windows.
iExist: i32,
strDriverPath: [u8; ADL_MAX_PATH],
strDriverPathExt: [u8; ADL_MAX_PATH],
strPNPString: [u8; ADL_MAX_PATH],
iOSDisplayIndex: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLMSTRad {
iLinkNumber: i32,
rad: [u8; ADL_MAX_RAD_LINK_COUNT],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLDevicePort {
iConnectorIndex: i32,
aMSTRad: ADLMSTRad,
}
impl ADLDevicePort {
/// A non-MST port at `connector` (MST RAD all-zero = "DP root / non-DP ignored" per header).
fn root(connector: i32) -> Self {
Self {
iConnectorIndex: connector,
aMSTRad: ADLMSTRad {
iLinkNumber: 0,
rad: [0; ADL_MAX_RAD_LINK_COUNT],
},
}
}
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectionProperties {
iValidProperties: i32,
iBitrate: i32,
iNumberOfLanes: i32,
iColorDepth: i32,
iStereo3DCaps: i32,
iOutputBandwidth: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectionData {
iConnectionType: i32,
aConnectionProperties: ADLConnectionProperties,
iNumberofPorts: i32,
iActiveConnections: i32,
iDataSize: i32,
EdidData: [u8; ADL_MAX_DISPLAY_EDID_DATA_SIZE],
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ADLConnectionState {
iEmulationStatus: i32,
iEmulationMode: i32,
iDisplayIndex: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectorInfo {
iConnectorIndex: i32,
iConnectorId: i32,
iSlotIndex: i32,
iType: i32,
iOffset: i32,
iLength: i32,
}
// ---- dynamic binding (atiadlxx.dll ships with every AMD driver; absent elsewhere) ----
type AdlContext = *mut c_void;
type MallocCb = unsafe extern "C" fn(i32) -> *mut c_void;
type FnMainCreate = unsafe extern "C" fn(MallocCb, i32, *mut AdlContext) -> i32;
type FnMainDestroy = unsafe extern "C" fn(AdlContext) -> i32;
type FnNumAdapters = unsafe extern "C" fn(AdlContext, *mut i32) -> i32;
type FnAdapterInfoGet = unsafe extern "C" fn(AdlContext, *mut AdapterInfo, i32) -> i32;
type FnEdidMgmtCaps = unsafe extern "C" fn(AdlContext, i32, *mut i32) -> i32;
type FnBoardLayoutGet = unsafe extern "C" fn(
AdlContext,
i32,
*mut i32,
*mut i32,
*mut *mut c_void,
*mut i32,
*mut *mut ADLConnectorInfo,
) -> i32;
type FnConnStateGet =
unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, *mut ADLConnectionState) -> i32;
type FnConnDataGet =
unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, i32, *mut ADLConnectionData) -> i32;
type FnConnDataSet = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, ADLConnectionData) -> i32;
type FnConnDataRemove = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort) -> i32;
type FnEmulModeSet = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, i32) -> i32;
struct Adl {
create: FnMainCreate,
destroy: FnMainDestroy,
num_adapters: FnNumAdapters,
adapter_info: FnAdapterInfoGet,
edid_caps: FnEdidMgmtCaps,
board_layout: FnBoardLayoutGet,
conn_state: FnConnStateGet,
conn_data_get: FnConnDataGet,
conn_data_set: FnConnDataSet,
conn_data_remove: FnConnDataRemove,
emul_mode_set: FnEmulModeSet,
}
/// ADL's application-provided allocator: it hands buffers (board-layout arrays) back through
/// out-pointers and expects the app to own them.
unsafe extern "C" fn adl_malloc(size: i32) -> *mut c_void {
let size = size.max(1) as usize;
// SAFETY: non-zero size with a fixed valid alignment; the resulting buffers are deliberately
// never freed — ADL's contract wants an ADL_Main_Memory_Free symmetry, and leaking the <1 KiB
// of board-layout arrays in a one-shot probe is simpler than proving allocator parity.
unsafe {
std::alloc::alloc(std::alloc::Layout::from_size_align(size, 16).expect("tiny ADL alloc"))
as *mut c_void
}
}
impl Adl {
fn load() -> Option<Self> {
// SAFETY: plain LoadLibrary of the AMD-driver-installed ADL runtime by its well-known
// name; a foreign-DLL search-path attack would require writing to System32.
let lib: HMODULE = unsafe { LoadLibraryA(s!("atiadlxx.dll")) }.ok()?;
// One unsafe helper: resolve `name` or bail. Every Fn* type above matches the ADL
// header's C signature (x64 has a single calling convention, so `extern "C"` is exact).
unsafe fn sym<T: Copy>(lib: HMODULE, name: PCSTR) -> Option<T> {
debug_assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<usize>());
// SAFETY: caller passes a fn-pointer type T of pointer size (asserted above);
// GetProcAddress yields the export's address or None.
let f = unsafe { GetProcAddress(lib, name) }?;
// SAFETY: reinterpreting one non-null fn pointer as the export's true C signature.
Some(unsafe { std::mem::transmute_copy::<_, T>(&f) })
}
// SAFETY: `lib` is the live module handle from the successful load above.
unsafe {
Some(Self {
create: sym(lib, s!("ADL2_Main_Control_Create"))?,
destroy: sym(lib, s!("ADL2_Main_Control_Destroy"))?,
num_adapters: sym(lib, s!("ADL2_Adapter_NumberOfAdapters_Get"))?,
adapter_info: sym(lib, s!("ADL2_Adapter_AdapterInfo_Get"))?,
edid_caps: sym(lib, s!("ADL2_Adapter_EDIDManagement_Caps"))?,
board_layout: sym(lib, s!("ADL2_Adapter_BoardLayout_Get"))?,
conn_state: sym(lib, s!("ADL2_Adapter_ConnectionState_Get"))?,
conn_data_get: sym(lib, s!("ADL2_Adapter_ConnectionData_Get"))?,
conn_data_set: sym(lib, s!("ADL2_Adapter_ConnectionData_Set"))?,
conn_data_remove: sym(lib, s!("ADL2_Adapter_ConnectionData_Remove"))?,
emul_mode_set: sym(lib, s!("ADL2_Adapter_EmulationMode_Set"))?,
})
}
}
}
// ---- the library surface ----
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EmulAction {
/// Read-only: caps + layout + per-connector state. Always safe.
Probe,
/// Pin live EDID + `ADL_EMUL_MODE_ALWAYS` on occupied (or named) connectors.
Lock,
/// `ADL_EMUL_MODE_OFF` + remove pinned EDID on all (or named) connectors.
Unlock,
}
/// One ADL call's outcome — op name, target, duration, rc (decoded via [`rc_str`]) and the
/// op-specific fields. The probe tool prints these as its bench correlation lines; the host
/// tracing-logs them. The rc IS the deliverable of a field run.
pub struct OpRecord {
pub op: &'static str,
pub target: String,
pub took_ms: u128,
pub rc: i32,
pub extra: String,
}
impl OpRecord {
pub fn ok(&self) -> bool {
self.rc == ADL_OK
}
}
impl std::fmt::Display for OpRecord {
/// The bench line minus the caller's epoch prefix: `op target took_ms ok rc=N(STR) extra`.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let sep = if self.extra.is_empty() { "" } else { " " };
write!(
f,
"{} {} took_ms={} ok={} rc={}({}){sep}{}",
self.op,
self.target,
self.took_ms,
self.ok(),
self.rc,
rc_str(self.rc),
self.extra
)
}
}
/// How a [`run`] ended: the AMD runtime was absent entirely, died at init (nothing was touched),
/// or walked the connectors (each op's rc in the records — a NOT_SUPPORTED driver still `Done`s).
pub enum RunOutcome {
/// `atiadlxx.dll` not loadable (or an export missing) — not an AMD driver install; the
/// emulation lever does not exist on this box.
NoAdl,
/// `ADL2_Main_Control_Create` / adapter enumeration failed — records hold the failing rc.
InitFailed(Vec<OpRecord>),
/// The connector walk ran; every op's outcome is in the records.
Done(Vec<OpRecord>),
}
impl RunOutcome {
pub fn records(&self) -> &[OpRecord] {
match self {
RunOutcome::NoAdl => &[],
RunOutcome::InitFailed(r) | RunOutcome::Done(r) => r,
}
}
}
fn c_str(buf: &[u8]) -> String {
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..len]).into_owned()
}
/// Perform `action` on every AMD adapter's connectors (or only `connector_filter`), returning the
/// per-op records. Read-only for [`EmulAction::Probe`]; [`EmulAction::Lock`] pins occupied
/// connectors only (unless the filter names one), matching an HPD dummy on the cables that exist.
pub fn run(action: EmulAction, connector_filter: Option<i32>) -> RunOutcome {
let mut recs: Vec<OpRecord> = Vec::new();
let mut rec = |op: &'static str, target: &str, took_ms: u128, rc: i32, extra: String| {
recs.push(OpRecord {
op,
target: target.to_owned(),
took_ms,
rc,
extra,
});
};
let Some(adl) = Adl::load() else {
return RunOutcome::NoAdl;
};
let mut ctx: AdlContext = std::ptr::null_mut();
let t = Instant::now();
// SAFETY: documented init call — our allocator callback, iEnumConnectedAdapters=0 (ALL
// adapters: an exclusively-isolated streaming host may report no "connected" display on the
// physical GPU), and a valid out-slot for the context.
let rc = unsafe { (adl.create)(adl_malloc, 0, &mut ctx) };
rec(
"adl-init",
"atiadlxx",
t.elapsed().as_millis(),
rc,
String::new(),
);
if rc != ADL_OK {
return RunOutcome::InitFailed(recs);
}
let mut count = 0i32;
// SAFETY: live context; valid out-param.
let rc = unsafe { (adl.num_adapters)(ctx, &mut count) };
if rc != ADL_OK || count <= 0 {
rec("adl-num-adapters", "all", 0, rc, format!("count={count}"));
// SAFETY: destroying the context created above; nothing ADL-owned is used past this point.
let _ = unsafe { (adl.destroy)(ctx) };
return RunOutcome::InitFailed(recs);
}
let mut infos: Vec<AdapterInfo> = (0..count)
.map(|_| {
// SAFETY: AdapterInfo is plain ints + byte arrays — the all-zero pattern is valid,
// and ADL fills the array in place.
let mut a: AdapterInfo = unsafe { std::mem::zeroed() };
a.iSize = std::mem::size_of::<AdapterInfo>() as i32;
a
})
.collect();
let bytes = std::mem::size_of_val(infos.as_slice()) as i32;
// SAFETY: caller-allocated array of exactly `count` stamped entries, byte size passed as the
// API's iInputSize contract requires.
let rc = unsafe { (adl.adapter_info)(ctx, infos.as_mut_ptr(), bytes) };
rec("adl-adapters", "all", 0, rc, format!("count={count}"));
if rc != ADL_OK {
// SAFETY: as above — context teardown, nothing ADL-owned used afterwards.
let _ = unsafe { (adl.destroy)(ctx) };
return RunOutcome::InitFailed(recs);
}
// One GPU surfaces as many logical adapters — probe each bus once, AMD-present only.
let mut seen_buses: Vec<i32> = Vec::new();
for info in &infos {
if info.iPresent == 0
|| info.iVendorID != AMD_VENDOR_ID
|| seen_buses.contains(&info.iBusNumber)
{
continue;
}
seen_buses.push(info.iBusNumber);
let idx = info.iAdapterIndex;
let name = c_str(&info.strAdapterName);
let target = format!("adapter{idx}[{}]", name.trim());
let mut supported = 0i32;
let t = Instant::now();
// SAFETY: live context, adapter index from this enumeration, valid out-param.
let rc = unsafe { (adl.edid_caps)(ctx, idx, &mut supported) };
rec(
"adl-edid-caps",
&target,
t.elapsed().as_millis(),
rc,
format!("supported={supported}"),
);
let (mut valid, mut n_slots, mut n_conn) = (0i32, 0i32, 0i32);
let mut slots: *mut c_void = std::ptr::null_mut();
let mut connectors: *mut ADLConnectorInfo = std::ptr::null_mut();
let t = Instant::now();
// SAFETY: live context + adapter index; out-pointers valid; ADL allocates the two arrays
// through `adl_malloc` (deliberately leaked, see there).
let rc = unsafe {
(adl.board_layout)(
ctx,
idx,
&mut valid,
&mut n_slots,
&mut slots,
&mut n_conn,
&mut connectors,
)
};
rec(
"adl-board-layout",
&target,
t.elapsed().as_millis(),
rc,
format!("connectors={n_conn} valid_flags={valid:#x}"),
);
let connector_list: &[ADLConnectorInfo] =
if rc == ADL_OK && !connectors.is_null() && n_conn > 0 {
// SAFETY: ADL just filled `connectors` with `n_conn` entries via our allocator; the
// (leaked) buffer outlives this borrow.
unsafe { std::slice::from_raw_parts(connectors, n_conn as usize) }
} else {
&[]
};
for c in connector_list {
if connector_filter.is_some_and(|want| want != c.iConnectorIndex) {
continue;
}
let port = ADLDevicePort::root(c.iConnectorIndex);
let ctarget = format!(
"adapter{idx}.connector{}[{}]",
c.iConnectorIndex,
connector_type_str(c.iType)
);
let mut state = ADLConnectionState::default();
let t = Instant::now();
// SAFETY: live context; port is a by-value POD naming a connector this adapter just
// enumerated; valid out-param.
let rc = unsafe { (adl.conn_state)(ctx, idx, port, &mut state) };
let real = state.iEmulationStatus & ADL_EMUL_STATUS_REAL_DEVICE_CONNECTED != 0;
rec(
"adl-conn-state",
&ctarget,
t.elapsed().as_millis(),
rc,
format!(
"status={:#x} real_connected={} emulated_present={} emulated_used={} mode={} display={}",
state.iEmulationStatus,
real,
state.iEmulationStatus & ADL_EMUL_STATUS_EMULATED_DEVICE_PRESENT != 0,
state.iEmulationStatus & ADL_EMUL_STATUS_EMULATED_DEVICE_USED != 0,
state.iEmulationMode,
state.iDisplayIndex,
),
);
if rc != ADL_OK {
continue;
}
match action {
EmulAction::Probe => {
// SAFETY: ADLConnectionData is plain ints + a byte array; all-zero is valid
// and ADL overwrites it.
let mut data: ADLConnectionData = unsafe { std::mem::zeroed() };
let t = Instant::now();
// SAFETY: live context/port as above; REAL query fills `data` in place.
let rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_REAL_DATA, &mut data)
};
rec(
"adl-conn-data",
&ctarget,
t.elapsed().as_millis(),
rc,
format!(
"type={} edid_bytes={}",
data.iConnectionType, data.iDataSize
),
);
}
EmulAction::Lock => {
if !real && connector_filter.is_none() {
continue; // nothing to pin — and pinning an EMPTY connector is a different experiment
}
// SAFETY: as in Probe — zeroed then driver-filled.
let mut data: ADLConnectionData = unsafe { std::mem::zeroed() };
let t = Instant::now();
// SAFETY: live context/port; REAL query first — we pin exactly what the
// sink reports today, so the emulated display IS the user's monitor.
let mut rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_REAL_DATA, &mut data)
};
if rc != ADL_OK {
// Asleep sinks can refuse a live EDID read — fall back to whatever the
// driver already has as emulation data (Radeon-Pro-UI parity).
// SAFETY: same contract, emulated-data query.
rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_EMULATED_DATA, &mut data)
};
}
rec(
"adl-lock-read",
&ctarget,
t.elapsed().as_millis(),
rc,
format!(
"type={} edid_bytes={}",
data.iConnectionType, data.iDataSize
),
);
if rc != ADL_OK || data.iDataSize <= 0 {
continue;
}
let t = Instant::now();
// SAFETY: live context/port; `data` passed by value per the ADL signature.
let rc = unsafe { (adl.conn_data_set)(ctx, idx, port, data) };
rec(
"adl-lock-set",
&ctarget,
t.elapsed().as_millis(),
rc,
String::new(),
);
let t = Instant::now();
// SAFETY: live context/port; mode constant from the header.
let rc = unsafe { (adl.emul_mode_set)(ctx, idx, port, ADL_EMUL_MODE_ALWAYS) };
rec(
"adl-lock-mode-always",
&ctarget,
t.elapsed().as_millis(),
rc,
String::new(),
);
}
EmulAction::Unlock => {
let t = Instant::now();
// SAFETY: live context/port; mode constant from the header.
let rc = unsafe { (adl.emul_mode_set)(ctx, idx, port, ADL_EMUL_MODE_OFF) };
rec(
"adl-unlock-mode-off",
&ctarget,
t.elapsed().as_millis(),
rc,
String::new(),
);
let t = Instant::now();
// SAFETY: live context/port; removes emulation data set earlier (harmless
// where none exists — the rc says so).
let rc = unsafe { (adl.conn_data_remove)(ctx, idx, port) };
rec(
"adl-unlock-remove",
&ctarget,
t.elapsed().as_millis(),
rc,
String::new(),
);
}
}
}
}
// SAFETY: destroying the context created above; nothing ADL-owned is used past this point.
let _ = unsafe { (adl.destroy)(ctx) };
RunOutcome::Done(recs)
}
// ---- the `edid_lock` display-policy axis (host-side) ----
/// The crash-recovery journal: a marker that a lock was applied and not yet unlocked. Pinned
/// emulation outlives the process (and can outlive a reboot), so a host that died mid-stream
/// must unlock on its next start ([`startup_recover`]).
fn journal_path() -> std::path::PathBuf {
pf_paths::config_dir().join("edid-lock-active.json")
}
fn tracing_log(prefix: &str, outcome: &RunOutcome) {
match outcome {
RunOutcome::NoAdl => tracing::info!(
"{prefix}: atiadlxx.dll not loadable — not an AMD driver install; the ADL \
emulation lever does not exist on this box"
),
RunOutcome::InitFailed(recs) | RunOutcome::Done(recs) => {
for r in recs {
if r.ok() {
tracing::info!("{prefix}: {r}");
} else {
tracing::warn!("{prefix}: {r}");
}
}
}
}
}
/// Apply the `edid_lock` axis at stream bring-up: pin the live EDID + `ADL_EMUL_MODE_ALWAYS` on
/// every occupied AMD connector (the software HPD dummy), journaling first so a crash still
/// unlocks on the next host start. Returns whether a later [`unlock_after_stream`] is owed —
/// true whenever the ADL runtime exists, because even a partially-failed lock may have pinned
/// some connectors (each rc is in the log).
pub fn lock_for_stream() -> bool {
// Journal BEFORE touching the driver: a crash between the first `ConnectionData_Set` and the
// journal write would otherwise leave pinned connectors with no startup unlock owed.
if let Err(e) = std::fs::write(journal_path(), b"{\"locked\":true}") {
tracing::warn!(
error = %format!("{e:#}"),
"edid_lock: crash journal write failed — continuing (the feature degrades to \
no-crash-journal)"
);
}
let outcome = run(EmulAction::Lock, None);
tracing_log("edid_lock", &outcome);
if matches!(outcome, RunOutcome::NoAdl) {
tracing::info!("edid_lock: enabled but this is not an AMD driver install — axis inert");
let _ = std::fs::remove_file(journal_path());
return false;
}
let locked = outcome
.records()
.iter()
.filter(|r| r.op == "adl-lock-mode-always" && r.ok())
.count();
tracing::info!(
connectors = locked,
"edid_lock: connector emulation pinned (software HPD dummy) — unlocked at stream teardown"
);
true
}
/// Undo [`lock_for_stream`] at teardown: `ADL_EMUL_MODE_OFF` + remove the pinned EDID on every
/// AMD connector, then clear the crash journal. Idempotent and harmless where nothing is pinned.
pub fn unlock_after_stream() {
let outcome = run(EmulAction::Unlock, None);
tracing_log("edid_lock", &outcome);
let _ = std::fs::remove_file(journal_path());
}
/// Host-startup crash recovery: a previous host that died holding the lock left connector
/// emulation pinned (it persists past the process — and can persist past a reboot). If the
/// journal marker exists, unlock everything and clear it — before any new session touches the
/// topology, mirroring `monitor_devnode::startup_recover`.
pub fn startup_recover() {
if !journal_path().exists() {
return;
}
tracing::warn!(
"edid_lock: a previous host left connector emulation pinned (crash/kill) — unlocking"
);
unlock_after_stream();
}
+2
View File
@@ -13,6 +13,8 @@
// hoist that to the crate root so the smaller modules (`input_desktop`, `monitor_devnode`,
// `display_events`) and any future one are covered by default rather than by remembering to opt in.
#[cfg(target_os = "windows")]
pub mod adl_emul;
#[cfg(target_os = "windows")]
pub mod display_events;
/// Bind display-config writes to the input desktop so a UAC / lock screen can't refuse them.
+6
View File
@@ -396,6 +396,12 @@ fn real_main() -> Result<()> {
// restored (crash/kill/power loss) — before any new session touches the topology.
#[cfg(target_os = "windows")]
monitor_devnode::startup_recover();
// The same recovery for the experimental `edid_lock` axis: unpin AMD connector
// emulation a previous host locked and never unlocked — pinned emulation outlives
// the process (and can outlive a reboot), so this is the only thing standing between
// a crash and a permanently-emulated connector.
#[cfg(target_os = "windows")]
pf_win_display::adl_emul::startup_recover();
// The same recovery for the DEFAULT Exclusive path: a previous host that died holding a
// CCD isolate left the operator's panels deactivated with nothing to put them back (the
// restore snapshot was process memory). Runs AFTER the devnode leg so re-enabled
@@ -82,6 +82,10 @@ pub(crate) fn display_settings_state() -> DisplaySettingsState {
// (`vdisplay/windows/manager.rs`); stored-but-inert elsewhere.
"ddc_power_off".into(),
"pnp_disable_monitors".into(),
// EXPERIMENTAL, Windows + AMD-driver-only in effect (the ADL connector-emulation lever;
// inert wherever `atiadlxx.dll` is absent). The console additionally gates the toggle's
// VISIBILITY on an AMD GPU being present, so only the hosts it can act on ever see it.
"edid_lock".into(),
];
// `capture_monitor` routes every session to the MIRROR backend, and that backend exists only on
// Linux — `vdisplay::open`'s mirror arm is `#[cfg(target_os = "linux")]`, because `pf-capture`
@@ -464,6 +468,7 @@ pub(crate) async fn set_display_layout(ApiJson(req): ApiJson<DisplayLayoutReques
store.game_session(),
store.ddc_power_off(),
store.pnp_disable_monitors(),
store.edid_lock(),
store.get().capture_monitor,
);
if let Err(e) = store.set(policy) {
+3 -1
View File
@@ -1542,9 +1542,11 @@ async fn display_settings_surface() {
assert!(enforced.contains(&"mode_conflict"));
assert!(enforced.contains(&"identity"));
assert!(enforced.contains(&"layout"));
// The experimental DDC/CI + PnP-disable axes are acted on (Windows exclusive-isolate path).
// The experimental DDC/CI + PnP-disable + EDID-lock axes are acted on (Windows
// exclusive-isolate path; edid_lock additionally needs an AMD driver to do anything).
assert!(enforced.contains(&"ddc_power_off"));
assert!(enforced.contains(&"pnp_disable_monitors"));
assert!(enforced.contains(&"edid_lock"));
}
/// The display state/release endpoints are wired + auth-gated. On the test host no backend has
+4
View File
@@ -9,6 +9,10 @@ authors.workspace = true
repository.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
# The `adl-emul` subcommand is a printer around `pf_win_display::adl_emul` — one ADL FFI surface
# shared with the host's `edid_lock` display-policy axis, so the probe a reporter runs and the
# toggle the console flips exercise byte-identical driver calls.
pf-win-display = { path = "../../crates/pf-win-display" }
windows = { version = "0.62", features = [
"Win32_Devices_Display",
"Win32_Graphics_Gdi",
+18 -514
View File
@@ -1,16 +1,10 @@
//! `adl-emul` — the AMD ADL EDID-emulation probe (immunity design doc §3's "probe once, log rc",
//! promoted to a field A/B after the third RX 9070 XT standby-sink case).
//!
//! Three field cases (ASUS VG32VQ1B/DP, Odyssey G60SD/DP, LG UltraGear 32GS95UE/HDMI — all
//! RX 9070 XT hosts) share one mechanism: a connected-but-asleep sink whose standby HPD/DDC/link
//! servicing the KMD performs below every OS lever (CCD deactivation, devnode disable and CRU
//! EDID overrides are confirmed no-ops — design doc §2a/§3). The one software lever that could
//! stop the servicing at its SOURCE is the driver's own connector emulation — the software
//! equivalent of an HPD-holding dummy plug: pin the live EDID with
//! `ADL2_Adapter_ConnectionData_Set`, then `ADL2_Adapter_EmulationMode_Set(ADL_EMUL_MODE_ALWAYS)`
//! so the driver stops caring what the physical pins report. The design doc marked the API
//! "likely Pro-gated" on hearsay; nobody — here or in the community record — ever probed consumer
//! Adrenalin. This subcommand is that probe:
//! The implementation lives in `pf_win_display::adl_emul` — one FFI surface shared with the
//! host's `edid_lock` display-policy axis, so the probe a reporter runs and the toggle the
//! console flips exercise byte-identical driver calls. This subcommand is the bench-line
//! printer + exit-code contract around it:
//!
//! * `adl-emul` — read-only: caps, board layout, per-connector state.
//! * `adl-emul --lock [--connector N]` — pin the live EDID + `ADL_EMUL_MODE_ALWAYS` (occupied
@@ -24,260 +18,10 @@
//! stall. `--unlock` (or a driver reinstall) restores; emulation state can persist across
//! reboots, so a `--lock` run must always be paired with a later `--unlock`.
// FFI mirrors of ADL's C structs — keep AMD's field names verbatim so the header diff is
// mechanical.
#![allow(non_snake_case)]
use std::time::{SystemTime, UNIX_EPOCH};
use std::ffi::c_void;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use windows::core::{s, PCSTR};
use windows::Win32::Foundation::HMODULE;
use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
// ---- ADL constants (adl_defines.h, GPUOpen display-library) ----
const ADL_OK: i32 = 0;
const ADL_MAX_PATH: usize = 256;
const ADL_MAX_DISPLAY_EDID_DATA_SIZE: usize = 1024;
const ADL_MAX_RAD_LINK_COUNT: usize = 15;
const ADL_EMUL_MODE_OFF: i32 = 0;
const ADL_EMUL_MODE_ALWAYS: i32 = 3;
const ADL_QUERY_REAL_DATA: i32 = 0;
const ADL_QUERY_EMULATED_DATA: i32 = 1;
const ADL_EMUL_STATUS_REAL_DEVICE_CONNECTED: i32 = 0x1;
const ADL_EMUL_STATUS_EMULATED_DEVICE_PRESENT: i32 = 0x2;
const ADL_EMUL_STATUS_EMULATED_DEVICE_USED: i32 = 0x4;
const AMD_VENDOR_ID: i32 = 1002;
/// Decode the rc values a field log will actually contain (adl_defines.h) — `-8` vs `-1` is the
/// whole consumer-vs-Pro question, so spell them out.
fn rc_str(rc: i32) -> &'static str {
match rc {
0 => "ADL_OK",
1..=4 => "ADL_OK_(warning-class)",
-1 => "ADL_ERR",
-2 => "ADL_ERR_NOT_INIT",
-3 => "ADL_ERR_INVALID_PARAM",
-5 => "ADL_ERR_INVALID_ADL_IDX",
-8 => "ADL_ERR_NOT_SUPPORTED",
-9 => "ADL_ERR_NULL_POINTER",
-10 => "ADL_ERR_DISABLED_ADAPTER",
-22 => "ADL_ERR_CALL_TO_INCOMPATIABLE_DRIVER",
-23 => "ADL_ERR_NO_ADMINISTRATOR_PRIVILEGES",
_ => "?",
}
}
fn connector_type_str(t: i32) -> &'static str {
match t {
1 => "VGA",
2 => "DVI-D",
3 => "DVI-I",
8 => "HDMI-A",
9 => "HDMI-B",
10 => "DP",
11 => "eDP",
12 => "miniDP",
13 => "VIRTUAL",
14 => "USB-C",
_ => "unknown",
}
}
// ---- ADL structs (adl_structures.h, verbatim layouts) ----
#[repr(C)]
struct AdapterInfo {
iSize: i32,
iAdapterIndex: i32,
strUDID: [u8; ADL_MAX_PATH],
iBusNumber: i32,
iDeviceNumber: i32,
iFunctionNumber: i32,
iVendorID: i32,
strAdapterName: [u8; ADL_MAX_PATH],
strDisplayName: [u8; ADL_MAX_PATH],
iPresent: i32,
// _WIN32 tail — this tool only builds for Windows.
iExist: i32,
strDriverPath: [u8; ADL_MAX_PATH],
strDriverPathExt: [u8; ADL_MAX_PATH],
strPNPString: [u8; ADL_MAX_PATH],
iOSDisplayIndex: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLMSTRad {
iLinkNumber: i32,
rad: [u8; ADL_MAX_RAD_LINK_COUNT],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLDevicePort {
iConnectorIndex: i32,
aMSTRad: ADLMSTRad,
}
impl ADLDevicePort {
/// A non-MST port at `connector` (MST RAD all-zero = "DP root / non-DP ignored" per header).
fn root(connector: i32) -> Self {
Self {
iConnectorIndex: connector,
aMSTRad: ADLMSTRad {
iLinkNumber: 0,
rad: [0; ADL_MAX_RAD_LINK_COUNT],
},
}
}
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectionProperties {
iValidProperties: i32,
iBitrate: i32,
iNumberOfLanes: i32,
iColorDepth: i32,
iStereo3DCaps: i32,
iOutputBandwidth: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectionData {
iConnectionType: i32,
aConnectionProperties: ADLConnectionProperties,
iNumberofPorts: i32,
iActiveConnections: i32,
iDataSize: i32,
EdidData: [u8; ADL_MAX_DISPLAY_EDID_DATA_SIZE],
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ADLConnectionState {
iEmulationStatus: i32,
iEmulationMode: i32,
iDisplayIndex: i32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ADLConnectorInfo {
iConnectorIndex: i32,
iConnectorId: i32,
iSlotIndex: i32,
iType: i32,
iOffset: i32,
iLength: i32,
}
// ---- dynamic binding (atiadlxx.dll ships with every AMD driver; absent elsewhere) ----
type AdlContext = *mut c_void;
type MallocCb = unsafe extern "C" fn(i32) -> *mut c_void;
type FnMainCreate = unsafe extern "C" fn(MallocCb, i32, *mut AdlContext) -> i32;
type FnMainDestroy = unsafe extern "C" fn(AdlContext) -> i32;
type FnNumAdapters = unsafe extern "C" fn(AdlContext, *mut i32) -> i32;
type FnAdapterInfoGet = unsafe extern "C" fn(AdlContext, *mut AdapterInfo, i32) -> i32;
type FnEdidMgmtCaps = unsafe extern "C" fn(AdlContext, i32, *mut i32) -> i32;
type FnBoardLayoutGet = unsafe extern "C" fn(
AdlContext,
i32,
*mut i32,
*mut i32,
*mut *mut c_void,
*mut i32,
*mut *mut ADLConnectorInfo,
) -> i32;
type FnConnStateGet =
unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, *mut ADLConnectionState) -> i32;
type FnConnDataGet =
unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, i32, *mut ADLConnectionData) -> i32;
type FnConnDataSet = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, ADLConnectionData) -> i32;
type FnConnDataRemove = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort) -> i32;
type FnEmulModeSet = unsafe extern "C" fn(AdlContext, i32, ADLDevicePort, i32) -> i32;
struct Adl {
create: FnMainCreate,
destroy: FnMainDestroy,
num_adapters: FnNumAdapters,
adapter_info: FnAdapterInfoGet,
edid_caps: FnEdidMgmtCaps,
board_layout: FnBoardLayoutGet,
conn_state: FnConnStateGet,
conn_data_get: FnConnDataGet,
conn_data_set: FnConnDataSet,
conn_data_remove: FnConnDataRemove,
emul_mode_set: FnEmulModeSet,
}
/// ADL's application-provided allocator: it hands buffers (board-layout arrays) back through
/// out-pointers and expects the app to own them.
unsafe extern "C" fn adl_malloc(size: i32) -> *mut c_void {
let size = size.max(1) as usize;
// SAFETY: non-zero size with a fixed valid alignment; the resulting buffers are deliberately
// never freed — ADL's contract wants an ADL_Main_Memory_Free symmetry, and leaking the <1 KiB
// of board-layout arrays in a one-shot probe is simpler than proving allocator parity.
unsafe {
std::alloc::alloc(std::alloc::Layout::from_size_align(size, 16).expect("tiny ADL alloc"))
as *mut c_void
}
}
impl Adl {
fn load() -> Option<Self> {
// SAFETY: plain LoadLibrary of the AMD-driver-installed ADL runtime by its well-known
// name; a foreign-DLL search-path attack would require writing to System32.
let lib: HMODULE = unsafe { LoadLibraryA(s!("atiadlxx.dll")) }.ok()?;
// One unsafe helper: resolve `name` or bail. Every Fn* type above matches the ADL
// header's C signature (x64 has a single calling convention, so `extern "C"` is exact).
unsafe fn sym<T: Copy>(lib: HMODULE, name: PCSTR) -> Option<T> {
debug_assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<usize>());
// SAFETY: caller passes a fn-pointer type T of pointer size (asserted above);
// GetProcAddress yields the export's address or None.
let f = unsafe { GetProcAddress(lib, name) }?;
// SAFETY: reinterpreting one non-null fn pointer as the export's true C signature.
Some(unsafe { std::mem::transmute_copy::<_, T>(&f) })
}
// SAFETY: `lib` is the live module handle from the successful load above.
unsafe {
Some(Self {
create: sym(lib, s!("ADL2_Main_Control_Create"))?,
destroy: sym(lib, s!("ADL2_Main_Control_Destroy"))?,
num_adapters: sym(lib, s!("ADL2_Adapter_NumberOfAdapters_Get"))?,
adapter_info: sym(lib, s!("ADL2_Adapter_AdapterInfo_Get"))?,
edid_caps: sym(lib, s!("ADL2_Adapter_EDIDManagement_Caps"))?,
board_layout: sym(lib, s!("ADL2_Adapter_BoardLayout_Get"))?,
conn_state: sym(lib, s!("ADL2_Adapter_ConnectionState_Get"))?,
conn_data_get: sym(lib, s!("ADL2_Adapter_ConnectionData_Get"))?,
conn_data_set: sym(lib, s!("ADL2_Adapter_ConnectionData_Set"))?,
conn_data_remove: sym(lib, s!("ADL2_Adapter_ConnectionData_Remove"))?,
emul_mode_set: sym(lib, s!("ADL2_Adapter_EmulationMode_Set"))?,
})
}
}
}
// ---- the probe ----
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EmulAction {
/// Read-only: caps + layout + per-connector state. Always safe.
Probe,
/// Pin live EDID + `ADL_EMUL_MODE_ALWAYS` on occupied (or named) connectors.
Lock,
/// `ADL_EMUL_MODE_OFF` + remove pinned EDID on all (or named) connectors.
Unlock,
}
pub use pf_win_display::adl_emul::EmulAction;
use pf_win_display::adl_emul::{run as adl_run, RunOutcome};
fn epoch_ms() -> u128 {
SystemTime::now()
@@ -286,260 +30,20 @@ fn epoch_ms() -> u128 {
.unwrap_or(0)
}
/// The bench's correlation-line convention (`epoch_ms op target took_ms ok`), plus the decoded
/// rc and any op-specific fields — the rc is what a field report gets read for.
fn line(op: &str, target: &str, took_ms: u128, rc: i32, extra: &str) {
let sep = if extra.is_empty() { "" } else { " " };
println!(
"{} {op} {target} took_ms={took_ms} ok={} rc={rc}({}){sep}{extra}",
epoch_ms(),
rc == ADL_OK,
rc_str(rc),
);
}
fn c_str(buf: &[u8]) -> String {
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..len]).into_owned()
}
pub fn run(action: EmulAction, connector_filter: Option<i32>) -> ! {
let Some(adl) = Adl::load() else {
eprintln!(
"atiadlxx.dll not loadable (or an export is missing) — not an AMD driver install; \
the ADL emulation lever does not exist on this box"
);
std::process::exit(2);
};
let mut ctx: AdlContext = std::ptr::null_mut();
let t = Instant::now();
// SAFETY: documented init call — our allocator callback, iEnumConnectedAdapters=0 (ALL
// adapters: an exclusively-isolated streaming host may report no "connected" display on the
// physical GPU), and a valid out-slot for the context.
let rc = unsafe { (adl.create)(adl_malloc, 0, &mut ctx) };
line("adl-init", "atiadlxx", t.elapsed().as_millis(), rc, "");
if rc != ADL_OK {
std::process::exit(1);
let outcome = adl_run(action, connector_filter);
for r in outcome.records() {
println!("{} {r}", epoch_ms());
}
let mut count = 0i32;
// SAFETY: live context; valid out-param.
let rc = unsafe { (adl.num_adapters)(ctx, &mut count) };
if rc != ADL_OK || count <= 0 {
line("adl-num-adapters", "all", 0, rc, &format!("count={count}"));
std::process::exit(1);
}
let mut infos: Vec<AdapterInfo> = (0..count)
.map(|_| {
// SAFETY: AdapterInfo is plain ints + byte arrays — the all-zero pattern is valid,
// and ADL fills the array in place.
let mut a: AdapterInfo = unsafe { std::mem::zeroed() };
a.iSize = std::mem::size_of::<AdapterInfo>() as i32;
a
})
.collect();
let bytes = std::mem::size_of_val(infos.as_slice()) as i32;
// SAFETY: caller-allocated array of exactly `count` stamped entries, byte size passed as the
// API's iInputSize contract requires.
let rc = unsafe { (adl.adapter_info)(ctx, infos.as_mut_ptr(), bytes) };
line("adl-adapters", "all", 0, rc, &format!("count={count}"));
if rc != ADL_OK {
std::process::exit(1);
}
// One GPU surfaces as many logical adapters — probe each bus once, AMD-present only.
let mut seen_buses: Vec<i32> = Vec::new();
for info in &infos {
if info.iPresent == 0
|| info.iVendorID != AMD_VENDOR_ID
|| seen_buses.contains(&info.iBusNumber)
{
continue;
}
seen_buses.push(info.iBusNumber);
let idx = info.iAdapterIndex;
let name = c_str(&info.strAdapterName);
let target = format!("adapter{idx}[{}]", name.trim());
let mut supported = 0i32;
let t = Instant::now();
// SAFETY: live context, adapter index from this enumeration, valid out-param.
let rc = unsafe { (adl.edid_caps)(ctx, idx, &mut supported) };
line(
"adl-edid-caps",
&target,
t.elapsed().as_millis(),
rc,
&format!("supported={supported}"),
);
let (mut valid, mut n_slots, mut n_conn) = (0i32, 0i32, 0i32);
let mut slots: *mut c_void = std::ptr::null_mut();
let mut connectors: *mut ADLConnectorInfo = std::ptr::null_mut();
let t = Instant::now();
// SAFETY: live context + adapter index; out-pointers valid; ADL allocates the two arrays
// through `adl_malloc` (deliberately leaked, see there).
let rc = unsafe {
(adl.board_layout)(
ctx,
idx,
&mut valid,
&mut n_slots,
&mut slots,
&mut n_conn,
&mut connectors,
)
};
line(
"adl-board-layout",
&target,
t.elapsed().as_millis(),
rc,
&format!("connectors={n_conn} valid_flags={valid:#x}"),
);
let connector_list: &[ADLConnectorInfo] =
if rc == ADL_OK && !connectors.is_null() && n_conn > 0 {
// SAFETY: ADL just filled `connectors` with `n_conn` entries via our allocator; the
// (leaked) buffer outlives this borrow.
unsafe { std::slice::from_raw_parts(connectors, n_conn as usize) }
} else {
&[]
};
for c in connector_list {
if connector_filter.is_some_and(|want| want != c.iConnectorIndex) {
continue;
}
let port = ADLDevicePort::root(c.iConnectorIndex);
let ctarget = format!(
"adapter{idx}.connector{}[{}]",
c.iConnectorIndex,
connector_type_str(c.iType)
match outcome {
RunOutcome::NoAdl => {
eprintln!(
"atiadlxx.dll not loadable (or an export is missing) — not an AMD driver \
install; the ADL emulation lever does not exist on this box"
);
let mut state = ADLConnectionState::default();
let t = Instant::now();
// SAFETY: live context; port is a by-value POD naming a connector this adapter just
// enumerated; valid out-param.
let rc = unsafe { (adl.conn_state)(ctx, idx, port, &mut state) };
let real = state.iEmulationStatus & ADL_EMUL_STATUS_REAL_DEVICE_CONNECTED != 0;
line(
"adl-conn-state",
&ctarget,
t.elapsed().as_millis(),
rc,
&format!(
"status={:#x} real_connected={} emulated_present={} emulated_used={} mode={} display={}",
state.iEmulationStatus,
real,
state.iEmulationStatus & ADL_EMUL_STATUS_EMULATED_DEVICE_PRESENT != 0,
state.iEmulationStatus & ADL_EMUL_STATUS_EMULATED_DEVICE_USED != 0,
state.iEmulationMode,
state.iDisplayIndex,
),
);
if rc != ADL_OK {
continue;
}
match action {
EmulAction::Probe => {
// SAFETY: ADLConnectionData is plain ints + a byte array; all-zero is valid
// and ADL overwrites it.
let mut data: ADLConnectionData = unsafe { std::mem::zeroed() };
let t = Instant::now();
// SAFETY: live context/port as above; REAL query fills `data` in place.
let rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_REAL_DATA, &mut data)
};
line(
"adl-conn-data",
&ctarget,
t.elapsed().as_millis(),
rc,
&format!(
"type={} edid_bytes={}",
data.iConnectionType, data.iDataSize
),
);
}
EmulAction::Lock => {
if !real && connector_filter.is_none() {
continue; // nothing to pin — and pinning an EMPTY connector is a different experiment
}
// SAFETY: as in Probe — zeroed then driver-filled.
let mut data: ADLConnectionData = unsafe { std::mem::zeroed() };
let t = Instant::now();
// SAFETY: live context/port; REAL query first — we pin exactly what the
// sink reports today, so the emulated display IS the user's monitor.
let mut rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_REAL_DATA, &mut data)
};
if rc != ADL_OK {
// Asleep sinks can refuse a live EDID read — fall back to whatever the
// driver already has as emulation data (Radeon-Pro-UI parity).
// SAFETY: same contract, emulated-data query.
rc = unsafe {
(adl.conn_data_get)(ctx, idx, port, ADL_QUERY_EMULATED_DATA, &mut data)
};
}
line(
"adl-lock-read",
&ctarget,
t.elapsed().as_millis(),
rc,
&format!(
"type={} edid_bytes={}",
data.iConnectionType, data.iDataSize
),
);
if rc != ADL_OK || data.iDataSize <= 0 {
continue;
}
let t = Instant::now();
// SAFETY: live context/port; `data` passed by value per the ADL signature.
let rc = unsafe { (adl.conn_data_set)(ctx, idx, port, data) };
line("adl-lock-set", &ctarget, t.elapsed().as_millis(), rc, "");
let t = Instant::now();
// SAFETY: live context/port; mode constant from the header.
let rc = unsafe { (adl.emul_mode_set)(ctx, idx, port, ADL_EMUL_MODE_ALWAYS) };
line(
"adl-lock-mode-always",
&ctarget,
t.elapsed().as_millis(),
rc,
"",
);
}
EmulAction::Unlock => {
let t = Instant::now();
// SAFETY: live context/port; mode constant from the header.
let rc = unsafe { (adl.emul_mode_set)(ctx, idx, port, ADL_EMUL_MODE_OFF) };
line(
"adl-unlock-mode-off",
&ctarget,
t.elapsed().as_millis(),
rc,
"",
);
let t = Instant::now();
// SAFETY: live context/port; removes emulation data set earlier (harmless
// where none exists — the rc says so).
let rc = unsafe { (adl.conn_data_remove)(ctx, idx, port) };
line(
"adl-unlock-remove",
&ctarget,
t.elapsed().as_millis(),
rc,
"",
);
}
}
std::process::exit(2);
}
RunOutcome::InitFailed(_) => std::process::exit(1),
RunOutcome::Done(_) => std::process::exit(0),
}
// SAFETY: destroying the context created above; nothing ADL-owned is used past this point.
let _ = unsafe { (adl.destroy)(ctx) };
std::process::exit(0);
}
+5
View File
@@ -217,6 +217,11 @@
"display_pnp_disabled": "Aus",
"display_pnp_enabled": "Ein",
"display_pnp_badge": "Monitor-Geräte deaktiviert (PnP)",
"display_edid": "Monitor-Identität beim Streamen festhalten (EDID)",
"display_edid_help": "Nur AMD-Grafikkarten unter Windows, wirkt bei Topologie Exklusiv. Während des Streams weist der Host den AMD-Treiber an, jeden angeschlossenen Monitor mit seiner aktuellen Identität (EDID) weiterhin als vorhanden zu behandeln — auch wenn der Monitor schläft; das Software-Äquivalent eines Dummy-Steckers. Das verhindert, dass der Treiber die Verbindung eines schlafenden Monitors periodisch abfragt, was auf manchen Systemen ein rhythmisches Stottern im Sekundentakt verursacht, solange nur das virtuelle Display aktiv ist. Beim Stream-Ende wird die Fixierung entfernt; stürzt der Host mitten im Stream ab, geschieht das beim nächsten Start. Verhält sich ein Monitor danach seltsam, diese Option ausschalten und den Monitor kurz ab- und wieder anstecken (im schlimmsten Fall den Grafiktreiber neu installieren).",
"display_edid_disabled": "Aus",
"display_edid_enabled": "Ein",
"display_edid_badge": "Monitor-Identität fixiert (EDID)",
"display_identity_shared": "Geteilt",
"display_identity_per_client": "Pro Client",
"display_identity_per_client_mode": "Pro Client + Auflösung",
+5
View File
@@ -217,6 +217,11 @@
"display_pnp_disabled": "Off",
"display_pnp_enabled": "On",
"display_pnp_badge": "Monitor devices disabled (PnP)",
"display_edid": "Pin monitor identity while streaming (EDID)",
"display_edid_help": "AMD graphics cards on Windows only, takes effect with Exclusive topology. While streaming, the host tells the AMD driver to keep treating each connected monitor as present with its current identity (EDID), even while the monitor sleeps — the software equivalent of a dummy plug. This stops the driver from periodically probing a sleeping monitor's connection, which on some setups causes a rhythmic stutter every couple of seconds while the virtual display is the only active one. The pin is removed when the stream ends; if the host crashes mid-stream, it is removed the next time the host starts. If a monitor misbehaves afterwards, turn this off and unplug/replug the monitor (or reinstall the graphics driver in the worst case).",
"display_edid_disabled": "Off",
"display_edid_enabled": "On",
"display_edid_badge": "Monitor identity pinned (EDID)",
"display_identity_shared": "Shared",
"display_identity_per_client": "Per client",
"display_identity_per_client_mode": "Per client + resolution",
+26
View File
@@ -23,6 +23,7 @@ import {
useSetDisplaySettings,
useUpdateCustomPreset,
} from "@/api/gen/display/display";
import { useListGpus } from "@/api/gen/gpu/gpu";
import type {
ApiDisplayInfo,
CustomPreset,
@@ -341,6 +342,11 @@ export const DisplayForm: FC<{
}) => {
const qc = useQueryClient();
const { confirm, promptText } = useDialogs();
// The EDID-lock toggle is gated on an AMD GPU being present — the axis is the AMD driver's
// ADL connector-emulation lever and exists nowhere else. GPUs don't hot-swap; one fetch with
// the section's lifetime is plenty (no refetch interval).
const gpus = useListGpus();
const amdHost = (gpus.data?.gpus ?? []).some((g) => g.vendor === "amd");
const createPreset = useCreateCustomPreset();
const updatePreset = useUpdateCustomPreset();
const deletePreset = useDeleteCustomPreset();
@@ -393,6 +399,7 @@ export const DisplayForm: FC<{
game_session: draft.game_session ?? "auto",
ddc_power_off: draft.ddc_power_off ?? false,
pnp_disable_monitors: draft.pnp_disable_monitors ?? false,
edid_lock: draft.edid_lock ?? false,
// Which screen we stream is not a display-behavior axis at all — swapping the
// streamed screen out from under the operator because they changed a preset would be
// the worst kind of surprise. From the SERVER, not the draft (see serverCaptureMonitor).
@@ -415,6 +422,7 @@ export const DisplayForm: FC<{
// The experimental axes aren't part of a preset — keep the current settings.
ddc_power_off: draft.ddc_power_off ?? false,
pnp_disable_monitors: draft.pnp_disable_monitors ?? false,
edid_lock: draft.edid_lock ?? false,
// Nor is the streamed screen: this builds a FRESH policy object rather than spreading
// the draft, so anything not named here is silently dropped — which is exactly how
// applying a saved preset used to switch a mirroring host back to a virtual display
@@ -839,6 +847,21 @@ export const DisplayForm: FC<{
busy={busy}
onSet={(on) => applyAxis({ pnp_disable_monitors: on })}
/>
{/* AMD hosts only: the axis is the driver's ADL connector-emulation lever, which
exists nowhere else a toggle NVIDIA/Intel operators could flip but that can
never do anything would be the "saved and then did nothing" trap the enforced
list exists to prevent. */}
{amdHost && (
<ExperimentalToggle
label={m.display_edid()}
help={m.display_edid_help()}
value={draft.edid_lock ?? false}
offLabel={m.display_edid_disabled()}
onLabel={m.display_edid_enabled()}
busy={busy}
onSet={(on) => applyAxis({ edid_lock: on })}
/>
)}
{/* What's in force right now read from the API's `effective`, not from the local draft.
Deriving it from the draft meant the row restated the operator's unsaved edits back to
@@ -874,6 +897,9 @@ export const DisplayForm: FC<{
{(draft.pnp_disable_monitors ?? false) && (
<Badge variant="outline">{m.display_pnp_badge()}</Badge>
)}
{(draft.edid_lock ?? false) && (
<Badge variant="outline">{m.display_edid_badge()}</Badge>
)}
</div>
<p className="max-w-prose text-xs text-muted-foreground">