Files
desktop/modules/hdmi-relink/src/main.zig
T
illustris df78533bcd port hdmi-relink to Zig 0.16
DebugAllocator, Init.Minimal args, manual opaque xcb extension externs
(libxcb 1.17), nanosleep-based sleepMs, raw-fd flock lock.
2026-08-24 08:16:25 +05:30

579 lines
22 KiB
Zig

//! Re-initialise a wedged TMDS link without replugging the cable.
//!
//! A DPMS off/on cycle can leave the panel's link untrained: the CRTC stays
//! programmed and the panel keeps HPD asserted, so the driver never retries and
//! the panel sits at "no signal". Nothing queryable distinguishes that from a
//! healthy link, so the link is re-initialised unconditionally on wake.
//!
//! Re-enabling at the target clock does not recover it -- 4K60 is 594MHz TMDS
//! against a 600MHz port maximum and will not re-train from the wedged state.
//! Bringing the link up at 1920x1080 (148.5MHz) first re-inits the transmitter,
//! after which the target mode trains normally.
//!
//! Wake is detected from the X screensaver idle counter, NOT the DPMS power
//! level: user input resets the idle counter but leaves the DPMS level at Off
//! until something forces it on, so an Off->On edge never occurs on a real
//! wake. The level is still read, as confirmation that the panels had slept.
//!
//! Speaks X11 directly over the existing socket so the poll loop spawns no
//! processes at all -- the whole daemon is a single execve at startup.
const std = @import("std");
const c = @cImport({
@cInclude("xcb/xcb.h");
@cInclude("xcb/randr.h");
@cInclude("xcb/dpms.h");
@cInclude("xcb/screensaver.h");
});
// libxcb 1.17 made xcb_extension_t opaque and Zig 0.16's translate-c refuses
// opaque-typed globals, so declare the extension key symbols by hand.
extern var xcb_randr_id: c.xcb_extension_t;
extern var xcb_dpms_id: c.xcb_extension_t;
extern var xcb_screensaver_id: c.xcb_extension_t;
const Config = struct {
output: []const u8 = "HDMI-0",
low_w: u16 = 1920,
low_h: u16 = 1080,
settle_ms: u64 = 3000,
interval_ms: u64 = 2000,
hold_ms: u64 = 1000,
/// Fallback for deciding the panels slept, when the DPMS level was never
/// caught off. Matches powerdevil's [AC][DPMSControl] idleTime.
idle_threshold_ms: u32 = 600_000,
watch: bool = false,
trace: bool = false,
};
const Conn = struct {
xc: *c.xcb_connection_t,
root: c.xcb_window_t,
};
/// std.Thread.sleep moved behind the Io interface in Zig 0.16; this daemon
/// only ever needs a plain blocking sleep.
fn sleepMs(ms: u64) void {
const ns = ms * std.time.ns_per_ms;
var req: std.os.linux.timespec = .{
.sec = @intCast(ns / std.time.ns_per_s),
.nsec = @intCast(ns % std.time.ns_per_s),
};
var rem: std.os.linux.timespec = undefined;
while (std.os.linux.errno(std.os.linux.nanosleep(&req, &rem)) == .INTR) req = rem;
}
fn logMsg(comptime fmt: []const u8, args: anytype) void {
// stderr goes straight to the journal under systemd; no logger(1) exec
std.debug.print("hdmi-relink: " ++ fmt ++ "\n", args);
}
fn connect() !Conn {
var screen_num: c_int = 0;
const xc = c.xcb_connect(null, &screen_num) orelse return error.ConnectFailed;
if (c.xcb_connection_has_error(xc) != 0) return error.ConnectFailed;
var iter = c.xcb_setup_roots_iterator(c.xcb_get_setup(xc));
var i: c_int = 0;
while (i < screen_num) : (i += 1) c.xcb_screen_next(&iter);
return .{ .xc = xc, .root = iter.data.*.root };
}
fn requireExt(xc: *c.xcb_connection_t, ext: *c.xcb_extension_t, name: []const u8) !void {
const reply = c.xcb_get_extension_data(xc, ext);
if (reply == null or reply.*.present == 0) {
logMsg("required X extension {s} is not available", .{name});
return error.MissingExtension;
}
}
/// Negotiate versions. Some servers reject extension requests until you have.
fn negotiate(xc: *c.xcb_connection_t) void {
if (c.xcb_randr_query_version_reply(xc, c.xcb_randr_query_version(xc, 1, 6), null)) |r|
std.c.free(r);
if (c.xcb_dpms_get_version_reply(xc, c.xcb_dpms_get_version(xc, 1, 2), null)) |r|
std.c.free(r);
if (c.xcb_screensaver_query_version_reply(xc, c.xcb_screensaver_query_version(xc, 1, 1), null)) |r|
std.c.free(r);
}
fn dpmsLevel(xc: *c.xcb_connection_t) !u16 {
const rep = c.xcb_dpms_info_reply(xc, c.xcb_dpms_info(xc), null) orelse
return error.DpmsQueryFailed;
defer std.c.free(rep);
return rep.*.power_level;
}
fn dpmsForceOn(xc: *c.xcb_connection_t) void {
// realign the server's bookkeeping with reality; a wake leaves it at Off
_ = c.xcb_dpms_force_level(xc, c.XCB_DPMS_DPMS_MODE_ON);
_ = c.xcb_flush(xc);
}
fn idleMs(xc: *c.xcb_connection_t, root: c.xcb_window_t) !u32 {
const rep = c.xcb_screensaver_query_info_reply(
xc,
c.xcb_screensaver_query_info(xc, root),
null,
) orelse return error.IdleQueryFailed;
defer std.c.free(rep);
return rep.*.ms_since_user_input;
}
fn configTimestamp(xc: *c.xcb_connection_t, root: c.xcb_window_t) !c.xcb_timestamp_t {
const res = c.xcb_randr_get_screen_resources_current_reply(
xc,
c.xcb_randr_get_screen_resources_current(xc, root),
null,
) orelse return error.NoScreenResources;
defer std.c.free(res);
return res.*.config_timestamp;
}
fn setCrtc(
xc: *c.xcb_connection_t,
crtc: c.xcb_randr_crtc_t,
cfg_ts: c.xcb_timestamp_t,
x: i16,
y: i16,
mode: c.xcb_randr_mode_t,
rotation: u16,
outs: []const c.xcb_randr_output_t,
) !void {
const rep = c.xcb_randr_set_crtc_config_reply(
xc,
c.xcb_randr_set_crtc_config(
xc,
crtc,
c.XCB_CURRENT_TIME,
cfg_ts,
x,
y,
mode,
rotation,
@intCast(outs.len),
if (outs.len == 0) null else outs.ptr,
),
null,
) orelse return error.SetCrtcFailed;
defer std.c.free(rep);
if (rep.*.status != c.XCB_RANDR_SET_CONFIG_SUCCESS) {
logMsg("SetCrtcConfig rejected: status={d}", .{rep.*.status});
return error.SetCrtcRejected;
}
}
fn findMode(list: [*c]c.xcb_randr_mode_info_t, n: c_int, id: c.xcb_randr_mode_t) ?c.xcb_randr_mode_info_t {
for (0..@intCast(n)) |k| if (list[k].id == id) return list[k];
return null;
}
/// On-screen footprint of a mode, which swaps axes under a quarter turn.
fn footprint(mi: c.xcb_randr_mode_info_t, rotation: u16) struct { w: u32, h: u32 } {
const quarter = c.XCB_RANDR_ROTATION_ROTATE_90 | c.XCB_RANDR_ROTATION_ROTATE_270;
return if (rotation & quarter != 0)
.{ .w = mi.height, .h = mi.width }
else
.{ .w = mi.width, .h = mi.height };
}
/// Grow the framebuffer if a placement would fall outside it.
///
/// SetCrtcConfig is rejected outright when the CRTC would extend past the
/// screen. We never shrink it ourselves, but xrandr(1) and kscreen both resize
/// the framebuffer to fit whatever they just set, so the screen can already be
/// too small for the mode we are restoring. Only ever grows.
fn growScreen(conn: Conn, need_w: u32, need_h: u32) void {
const geo = c.xcb_get_geometry_reply(conn.xc, c.xcb_get_geometry(conn.xc, conn.root), null) orelse return;
defer std.c.free(geo);
const cur_w: u32 = geo.*.width;
const cur_h: u32 = geo.*.height;
if (need_w <= cur_w and need_h <= cur_h) return;
const new_w: u32 = @max(cur_w, need_w);
const new_h: u32 = @max(cur_h, need_h);
// hold the original pixel density so DPI-derived sizing does not jump
const it = c.xcb_setup_roots_iterator(c.xcb_get_setup(conn.xc));
const px_w: u32 = it.data.*.width_in_pixels;
const px_h: u32 = it.data.*.height_in_pixels;
const mm_w: u32 = it.data.*.width_in_millimeters;
const mm_h: u32 = it.data.*.height_in_millimeters;
const nmm_w: u32 = if (px_w > 0) mm_w * new_w / px_w else mm_w;
const nmm_h: u32 = if (px_h > 0) mm_h * new_h / px_h else mm_h;
logMsg("growing framebuffer {d}x{d} -> {d}x{d}", .{ cur_w, cur_h, new_w, new_h });
_ = c.xcb_randr_set_screen_size(
conn.xc,
conn.root,
@intCast(new_w),
@intCast(new_h),
@intCast(nmm_w),
@intCast(nmm_h),
);
_ = c.xcb_flush(conn.xc);
}
/// Serialise re-inits across processes.
///
/// Running `hdmi-relink` by hand while the watcher is resident would otherwise
/// interleave the two SetCrtcConfig sequences, and whichever finishes last
/// restores the mode the other left behind -- permanently, since the restore
/// target is read from the CRTC.
///
/// Returns the locked file on success, null if no lock could be established at
/// all (in which case carry on unprotected), or error.Busy if another instance
/// holds it. The lock is released when the file is closed, including on crash.
fn acquireLock() !?std.posix.fd_t {
const dir: []const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.mem.span(v) else "/tmp";
var buf: [256]u8 = undefined;
const path = std.fmt.bufPrint(&buf, "{s}/hdmi-relink.lock", .{dir}) catch return null;
// std.fs.File moved behind the Io interface in Zig 0.16; a bare fd is all
// this advisory lock needs.
const fd = std.posix.openat(
std.posix.AT.FDCWD,
path,
.{ .ACCMODE = .RDWR, .CREAT = true },
0o600,
) catch return null;
const rc = std.os.linux.flock(fd, std.posix.LOCK.EX | std.posix.LOCK.NB);
const err = std.os.linux.errno(rc);
if (err != .SUCCESS) {
_ = std.os.linux.close(fd);
if (err == .AGAIN) return error.Busy;
return null;
}
return fd;
}
/// Re-initialise the named output's link.
///
/// Only this output's CRTC is touched, and the screen size is never changed:
/// the intermediate low mode is strictly smaller than the target, so it always
/// fits the existing framebuffer. That makes it impossible to disturb the other
/// outputs' positions or refresh rates -- which is exactly what a shell
/// implementation driving xrandr(1) cannot avoid, because xrandr resizes the
/// framebuffer and renormalises every output when one is switched off.
fn reinit(conn: Conn, cfg: Config) !void {
const xc = conn.xc;
const lock = acquireLock() catch {
logMsg("another instance is re-initialising {s}; skipping", .{cfg.output});
return;
};
defer if (lock) |fd| {
_ = std.os.linux.close(fd);
};
const res = c.xcb_randr_get_screen_resources_current_reply(
xc,
c.xcb_randr_get_screen_resources_current(xc, conn.root),
null,
) orelse return error.NoScreenResources;
defer std.c.free(res);
var cfg_ts = res.*.config_timestamp;
const out_list = c.xcb_randr_get_screen_resources_current_outputs(res);
const n_out = c.xcb_randr_get_screen_resources_current_outputs_length(res);
const mode_list = c.xcb_randr_get_screen_resources_current_modes(res);
const n_modes = c.xcb_randr_get_screen_resources_current_modes_length(res);
// locate the output by name
var oi: ?*c.xcb_randr_get_output_info_reply_t = null;
var i: c_int = 0;
while (i < n_out) : (i += 1) {
const info = c.xcb_randr_get_output_info_reply(
xc,
c.xcb_randr_get_output_info(xc, out_list[@intCast(i)], cfg_ts),
null,
) orelse continue;
const name_ptr = c.xcb_randr_get_output_info_name(info);
const name_len: usize = @intCast(c.xcb_randr_get_output_info_name_length(info));
if (name_len == cfg.output.len and
std.mem.eql(u8, name_ptr[0..name_len], cfg.output))
{
oi = info;
break;
}
std.c.free(info);
}
const info = oi orelse {
logMsg("output {s} not found", .{cfg.output});
return error.OutputNotFound;
};
defer std.c.free(info);
if (info.*.connection != c.XCB_RANDR_CONNECTION_CONNECTED) {
logMsg("output {s} is not connected; nothing to do", .{cfg.output});
return;
}
if (info.*.crtc == 0) {
logMsg("output {s} is connected but disabled; nothing to do", .{cfg.output});
return;
}
// current geometry, kept verbatim so the restore is exact
const ci = c.xcb_randr_get_crtc_info_reply(
xc,
c.xcb_randr_get_crtc_info(xc, info.*.crtc, cfg_ts),
null,
) orelse return error.NoCrtcInfo;
defer std.c.free(ci);
const crtc = info.*.crtc;
const x = ci.*.x;
const y = ci.*.y;
const rotation = ci.*.rotation;
var target_mode = ci.*.mode;
if (target_mode == 0) {
logMsg("output {s} has no mode set; nothing to do", .{cfg.output});
return;
}
// Sitting at exactly the fallback resolution means a previous re-init was
// interrupted between steps 2 and 3 and never restored the real mode.
// Restoring "whatever is current" would then make the fallback permanent,
// so recover the EDID-preferred mode instead.
var target_w: u16 = 0;
var target_h: u16 = 0;
for (0..@intCast(n_modes)) |k| {
if (mode_list[k].id == target_mode) {
target_w = mode_list[k].width;
target_h = mode_list[k].height;
}
}
if (target_w == cfg.low_w and target_h == cfg.low_h) {
const n_pref: usize = @intCast(info.*.num_preferred);
const om_all = c.xcb_randr_get_output_info_modes(info);
if (n_pref > 0) {
const pref = om_all[0];
if (pref != target_mode) {
logMsg(
"{s} is stranded at the {d}x{d} fallback (a previous re-init did not finish); restoring preferred mode instead",
.{ cfg.output, cfg.low_w, cfg.low_h },
);
target_mode = pref;
}
}
}
// the CRTC's output list must be reproduced on restore (mirroring etc)
var outs_buf: [16]c.xcb_randr_output_t = undefined;
const co = c.xcb_randr_get_crtc_info_outputs(ci);
const n_co: usize = @intCast(c.xcb_randr_get_crtc_info_outputs_length(ci));
if (n_co > outs_buf.len) return error.TooManyOutputs;
for (0..n_co) |k| outs_buf[k] = co[k];
const outs = outs_buf[0..n_co];
// resolution and clock of the mode we have to end up on
target_w = 0;
target_h = 0;
var target_clock: u32 = 0;
if (findMode(mode_list, n_modes, target_mode)) |mi| {
target_w = mi.width;
target_h = mi.height;
target_clock = mi.dot_clock;
}
// Build an ascending pixel-clock ladder ending on the target.
//
// After a sleep the transmitter will not train straight to 594MHz -- the
// panel lights up and drops again -- but it will climb: 148.5MHz, then
// 297MHz, then 594MHz, each rung re-training one step closer. A single
// low-clock hop is not enough; the intermediate at the target resolution
// is what makes the last step succeed.
const om = c.xcb_randr_get_output_info_modes(info);
const n_om = c.xcb_randr_get_output_info_modes_length(info);
// fastest mode at the fallback resolution
var rung_low: c.xcb_randr_mode_t = 0;
var low_clock: u32 = 0;
// slowest mode at the target resolution -- the rung has to be a real step
// down (297MHz for a 594MHz target), not the 593.41MHz near-twin, or the
// climb is a no-op and the last hop fails exactly as a direct jump does
var rung_mid: c.xcb_randr_mode_t = 0;
var mid_clock: u32 = std.math.maxInt(u32);
for (0..@intCast(n_om)) |j| {
const mi = findMode(mode_list, n_modes, om[j]) orelse continue;
if (mi.id == target_mode) continue;
if (mi.width == cfg.low_w and mi.height == cfg.low_h and mi.dot_clock > low_clock) {
low_clock = mi.dot_clock;
rung_low = mi.id;
}
if (mi.width == target_w and mi.height == target_h and
mi.dot_clock < target_clock and mi.dot_clock < mid_clock)
{
mid_clock = mi.dot_clock;
rung_mid = mi.id;
}
}
var ladder: [3]c.xcb_randr_mode_t = undefined;
var n_rungs: usize = 0;
if (rung_low != 0) {
ladder[n_rungs] = rung_low;
n_rungs += 1;
}
if (rung_mid != 0) {
ladder[n_rungs] = rung_mid;
n_rungs += 1;
}
ladder[n_rungs] = target_mode;
n_rungs += 1;
logMsg("re-initialising {s}: climbing {d}kHz -> {d}kHz -> {d}kHz ({d} rungs)", .{
cfg.output,
low_clock / 1000,
if (rung_mid == 0) 0 else mid_clock / 1000,
target_clock / 1000,
n_rungs,
});
// tear the CRTC down so the transmitter is re-initialised
try setCrtc(xc, crtc, cfg_ts, 0, 0, c.XCB_NONE, c.XCB_RANDR_ROTATION_ROTATE_0, &.{});
for (ladder[0..n_rungs]) |mode| {
if (findMode(mode_list, n_modes, mode)) |mi| {
const fp = footprint(mi, rotation);
growScreen(conn, @as(u32, @intCast(x)) + fp.w, @as(u32, @intCast(y)) + fp.h);
}
// each SetCrtcConfig advances the config timestamp; a stale one is rejected
cfg_ts = try configTimestamp(xc, conn.root);
try setCrtc(xc, crtc, cfg_ts, x, y, mode, rotation, outs);
sleepMs(cfg.hold_ms);
}
_ = c.xcb_flush(xc);
// Leaving the panel on the fallback mode is the one failure that persists,
// so confirm the restore actually took rather than assuming success.
const check = c.xcb_randr_get_crtc_info_reply(
xc,
c.xcb_randr_get_crtc_info(xc, crtc, try configTimestamp(xc, conn.root)),
null,
) orelse return;
defer std.c.free(check);
if (check.*.mode != target_mode) {
logMsg("restore did not take: crtc is on mode {d}, expected {d}", .{ check.*.mode, target_mode });
return error.RestoreFailed;
}
}
fn watch(conn: Conn, cfg: Config) !void {
logMsg("watching for wake (output={s} interval={d}ms settle={d}ms idle-threshold={d}ms)", .{
cfg.output, cfg.interval_ms, cfg.settle_ms, cfg.idle_threshold_ms,
});
const on = c.XCB_DPMS_DPMS_MODE_ON;
var prev_idle = idleMs(conn.xc, conn.root) catch 0;
var prev_level = dpmsLevel(conn.xc) catch on;
// Latched, not sampled at the moment of the wake: whoever blanked the
// screen may restore the level before the next poll, and testing the level
// only on the idle edge then races with them and never matches.
var slept = prev_level != on;
while (true) {
sleepMs(cfg.interval_ms);
if (c.xcb_connection_has_error(conn.xc) != 0) {
logMsg("X connection lost; exiting for restart", .{});
return error.ConnectionLost;
}
const idle = idleMs(conn.xc, conn.root) catch |e| {
logMsg("idle query failed: {s}", .{@errorName(e)});
continue;
};
const level = dpmsLevel(conn.xc) catch |e| {
logMsg("dpms query failed: {s}", .{@errorName(e)});
continue;
};
defer prev_idle = idle;
if (level != on) slept = true;
if (cfg.trace) logMsg("trace idle={d} level={d} slept={}", .{ idle, level, slept });
if (level != prev_level) {
logMsg("dpms level {d} -> {d} (idle {d}ms, slept={})", .{ prev_level, level, idle, slept });
prev_level = level;
}
// A drop in the idle counter means input arrived.
if (idle >= prev_idle) continue;
// ...but only re-initialise if the panels actually powered down, either
// observed directly or inferred from an idle long enough to have
// tripped the DPMS timeout.
const long_idle = prev_idle >= cfg.idle_threshold_ms;
if (!slept and !long_idle) continue;
logMsg("wake detected (idle {d}ms -> {d}ms, level {d}, slept={}, long_idle={})", .{
prev_idle, idle, level, slept, long_idle,
});
slept = false;
dpmsForceOn(conn.xc);
sleepMs(cfg.settle_ms);
reinit(conn, cfg) catch |e| logMsg("re-init failed: {s}", .{@errorName(e)});
}
}
fn parseArgs(cfg: *Config, args: []const [:0]const u8) !void {
var i: usize = 1;
while (i < args.len) : (i += 1) {
const a = args[i];
if (std.mem.eql(u8, a, "--watch")) {
cfg.watch = true;
} else if (std.mem.eql(u8, a, "--output") and i + 1 < args.len) {
i += 1;
cfg.output = args[i];
} else if (std.mem.eql(u8, a, "--settle") and i + 1 < args.len) {
i += 1;
cfg.settle_ms = try std.fmt.parseInt(u64, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--interval") and i + 1 < args.len) {
i += 1;
cfg.interval_ms = try std.fmt.parseInt(u64, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--idle-threshold") and i + 1 < args.len) {
i += 1;
cfg.idle_threshold_ms = try std.fmt.parseInt(u32, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--trace")) {
cfg.trace = true;
} else if (std.mem.eql(u8, a, "--help") or std.mem.eql(u8, a, "-h")) {
std.debug.print(
\\usage: hdmi-relink [--watch] [--output NAME] [--settle SECS] [--interval SECS]
\\
\\ no args re-initialise the output once and exit
\\ --watch stay resident and re-initialise on every wake
\\
, .{});
std.process.exit(0);
} else {
logMsg("unknown argument: {s}", .{a});
return error.BadArgs;
}
}
}
pub fn main(init: std.process.Init.Minimal) !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
var args = std.ArrayList([:0]const u8).empty;
defer args.deinit(alloc);
var it = std.process.Args.Iterator.init(init.args);
while (it.next()) |a| try args.append(alloc, a);
var cfg = Config{};
try parseArgs(&cfg, args.items);
const conn = try connect();
defer c.xcb_disconnect(conn.xc);
try requireExt(conn.xc, &xcb_randr_id, "RANDR");
try requireExt(conn.xc, &xcb_dpms_id, "DPMS");
try requireExt(conn.xc, &xcb_screensaver_id, "MIT-SCREEN-SAVER");
if (cfg.watch) try watch(conn, cfg) else try reinit(conn, cfg);
}