#!/usr/bin/env bash # inkbd — internal-keyboard diagnostic + repair tool # Target: PCSpecialist Valeon II 17 / TongFang GM7RGxM (Uniwill EC), Arch/Omarchy, Limine UKI. # # Usage: # inkbd status (no root) what the kernel currently thinks of the internal keyboard # inkbd watch [SECONDS] (no root) press keys on the INTERNAL keyboard; see if anything reaches the kernel # inkbd ledecho [N] (no root) send N LED commands to the EC and count IRQ 1 responses (is the EC alive?) # sudo inkbd diag (root) deep diagnosis + live re-init ladder; writes a log; prints a verdict # sudo inkbd apply STEP (root) run one live re-init step (reconnect|rebind|ps2reset|i8042) # sudo inkbd boot PRESET (root) install a kernel-cmdline quirk preset (reboot to test) # sudo inkbd boot revert (root) remove the quirk preset # inkbd boot list show presets / what is installed / what is live # sudo inkbd install-boot-fix STEP make a live step that worked run automatically at every boot # sudo inkbd uninstall-boot-fix # sudo inkbd suspend-cycle (root) suspend/resume (EC sleep cycle), then watch # inkbd report tar the logs for sharing # # NB: no pipefail — probes of the form `big-stream | grep -q` would SIGPIPE the # producer on early exit and pipefail would misreport the probe as failed. set -u INKBD_VERSION="1.0" SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")" SCRIPT_DIR="$(dirname "$SCRIPT_PATH")" LOGDIR="$SCRIPT_DIR/logs" DROPIN="/etc/limine-entry-tool.d/95-inkbd-i8042.conf" BOOTFIX_UNIT="/etc/systemd/system/inkbd-bootfix.service" KBD_NAME="AT Translated Set 2 keyboard" SERIO="/sys/bus/serio/devices/serio0" I8042_DRV="/sys/bus/platform/drivers/i8042" LOG="" # ---------- output helpers ---------- if [[ -t 1 ]]; then C0=$'\e[0m'; CB=$'\e[1m'; CG=$'\e[32m'; CY=$'\e[33m'; CR=$'\e[31m'; CC=$'\e[36m' else C0=""; CB=""; CG=""; CY=""; CR=""; CC="" fi say() { printf '%s\n' "$*" | tee -a "${LOG:-/dev/null}"; } hdr() { say ""; say "${CB}${CC}== $* ==${C0}"; } ok() { say "${CG}[ok]${C0} $*"; } warn() { say "${CY}[!!]${C0} $*"; } bad() { say "${CR}[XX]${C0} $*"; } note() { say " $*"; } logonly() { [[ -n "$LOG" ]] && printf '%s\n' "$*" >> "$LOG"; } need_root() { if [[ $EUID -ne 0 ]]; then echo "This subcommand needs root: sudo $(basename "$0") $*" >&2; exit 1; fi; } need_cmd() { command -v "$1" >/dev/null 2>&1 || { bad "missing command: $1"; return 1; }; } fix_owner() { # give log files back to the invoking user when run via sudo if [[ -n "${SUDO_USER:-}" && -d "$LOGDIR" ]]; then chown -R "$SUDO_USER":"$(id -gn "$SUDO_USER")" "$LOGDIR" 2>/dev/null || true; fi } open_log() { mkdir -p "$LOGDIR" LOG="$LOGDIR/$1-$(date +%Y%m%d-%H%M%S).log" : > "$LOG" say "inkbd $INKBD_VERSION — $(date -Is) — log: $LOG" } # ---------- low-level probes ---------- kbd_event_node() { # -> /dev/input/eventN for the AT keyboard, or empty awk -v name="$KBD_NAME" ' /^N: Name=/ { hit = index($0, name) > 0 } hit && /^H: Handlers=/ { for (i = 1; i <= NF; i++) if ($i ~ /^event[0-9]+$/) { print "/dev/input/" $i; exit } } ' /proc/bus/input/devices 2>/dev/null } irq1_count() { awk '$1=="1:" { s=0; for (i=2;i<=NF;i++) if ($i ~ /^[0-9]+$/) s+=$i; print s; exit }' /proc/interrupts; } kmsg_lines() { if [[ $EUID -eq 0 ]]; then dmesg 2>/dev/null; else journalctl -k -b 0 --no-pager -q -o short-monotonic 2>/dev/null; fi; } kbd_kmsg() { kmsg_lines | grep -iE 'i8042|atkbd|serio|psmouse|PNP0303|PS/2|kbd-data|kbd-io' ; } dmesg_mark() { dmesg 2>/dev/null | wc -l; } dmesg_since() { dmesg 2>/dev/null | tail -n +"$(( $1 + 1 ))"; } serio_driver() { basename "$(readlink -f "$SERIO/driver" 2>/dev/null)" 2>/dev/null; } i8042_bound() { [[ -e "$I8042_DRV/i8042" ]]; } cmdline_has_quirks() { tr ' ' '\n' < /proc/cmdline | grep -E '^(i8042|atkbd)\.' | tr '\n' ' '; } # ---------- watch: does ANYTHING reach the kernel when keys are pressed? ---------- # Prints live events; final line: RESULT irq= events= keys= node= watch_keys() { local secs="${1:-10}" node irq0 irq1 node="$(kbd_event_node)" irq0="$(irq1_count)" if [[ -z "$node" ]]; then say "no '$KBD_NAME' input node is registered right now (atkbd not bound?) — watching IRQ 1 only" fi say "${CB}>>> Press several keys on the INTERNAL laptop keyboard now — for the next ${secs}s (any key: letters, space, Fn, arrows)${C0}" say " (hands OFF the external keyboard: Caps/Num-lock toggles there get LED-mirrored to the internal EC and contaminate the IRQ count)" python3 - "$node" "$secs" <<'PY' 2>&1 | tee -a "${LOG:-/dev/null}" import os, sys, select, struct, time node, secs = sys.argv[1], float(sys.argv[2]) EV_KEY, EV_MSC = 1, 4 KEYNAMES = {1:'ESC',2:'1',3:'2',4:'3',5:'4',6:'5',7:'6',8:'7',9:'8',10:'9',11:'0',14:'BACKSPACE',15:'TAB',16:'Q',17:'W',18:'E',19:'R',20:'T',21:'Y',22:'U',23:'I',24:'O',25:'P',28:'ENTER',29:'LCTRL',30:'A',31:'S',32:'D',33:'F',34:'G',35:'H',36:'J',37:'K',38:'L',42:'LSHIFT',44:'Z',45:'X',46:'C',47:'V',48:'B',49:'N',50:'M',54:'RSHIFT',56:'LALT',57:'SPACE',58:'CAPS',59:'F1',60:'F2',61:'F3',62:'F4',63:'F5',64:'F6',65:'F7',66:'F8',67:'F9',68:'F10',87:'F11',88:'F12',103:'UP',105:'LEFT',106:'RIGHT',108:'DOWN',125:'SUPER'} events = keys = 0 fd = None if node: try: fd = os.open(node, os.O_RDONLY | os.O_NONBLOCK) except Exception as e: print(f"cannot open {node}: {e} (need to be in the 'input' group or root)") fmt = 'llHHi'; sz = struct.calcsize(fmt) end = time.time() + secs last = int(secs) while time.time() < end: remaining = end - time.time() if int(remaining) != last and fd is None: last = int(remaining) if fd is None: time.sleep(0.2); continue r, _, _ = select.select([fd], [], [], min(0.25, max(0, remaining))) if not r: continue try: data = os.read(fd, sz * 64) except BlockingIOError: continue for off in range(0, len(data) - sz + 1, sz): sec, usec, etype, code, value = struct.unpack_from(fmt, data, off) events += 1 if etype == EV_KEY: keys += 1 state = {0:'release',1:'press',2:'repeat'}.get(value, str(value)) print(f" EV_KEY code={code:<4} {KEYNAMES.get(code, '?'):<10} {state}") elif etype == EV_MSC: print(f" EV_MSC scancode=0x{value:02x}") if fd is not None: os.close(fd) print(f"RESULT events={events} keys={keys} node={node or '-'}") PY irq1="$(irq1_count)" say "RESULT irq1_delta=$(( irq1 - irq0 )) (IRQ 1 = i8042 keyboard interrupt; ${irq0} -> ${irq1})" } # ---------- ledecho: does the EC answer PS/2 traffic right now? (no root, no reboot) ---------- # Injecting an EV_LED event into the AT keyboard node makes atkbd send SETLEDS (0xED + arg) to the EC. # Every byte the EC answers raises IRQ 1. So: delta>0 = the EC's keyboard function is ALIVE on the wire, # even if atkbd's strict 200ms ACK timeout never sees the replies (the late-IRQ / wrong-edge signature). led_echo() { local n="${1:-3}" node node="$(kbd_event_node)" [[ -n "$node" ]] || { bad "no '$KBD_NAME' input node registered"; return 1; } say "LED-echo test: injecting $n CapsLock-LED toggles into $node — atkbd sends 0xED to the EC each time." say "${CB}Do not touch ANY keyboard during the test.${C0}" python3 - "$node" "$n" <<'PY' 2>&1 | tee -a "${LOG:-/dev/null}" import os, struct, sys, time node, n = sys.argv[1], int(sys.argv[2]) def irq1(): for line in open("/proc/interrupts"): if line.strip().startswith("1:"): return sum(int(x) for x in line.split()[1:] if x.isdigit()) fd = os.open(node, os.O_RDWR | os.O_NONBLOCK) base = irq1(); ondelta = offdelta = 0 for i in range(n): a = irq1() os.write(fd, struct.pack('llHHi', 0, 0, 0x11, 0x01, 1)); time.sleep(0.6) m = irq1() os.write(fd, struct.pack('llHHi', 0, 0, 0x11, 0x01, 0)); time.sleep(0.6) b = irq1() ondelta += m - a; offdelta += b - m print(f" toggle {i+1}: on-window +{m-a}, off-window +{b-m}") os.close(fd) total = irq1() - base print(f"LEDECHO commands={2*n} irq1_delta={total}") PY say "" say "How to read it:" say " irq1_delta ≈ 2 per toggle, promptly -> EC answers in time; the PS/2 link is healthy" say " irq1_delta ≥ 1 per toggle but LATE/lumpy -> EC ALIVE but IRQ delivery broken = the AMD-Zen IRQ1 trigger-type bug (see README)" say " irq1_delta = 0 -> EC not answering LED traffic now -> run: sudo inkbd diag" } # ---------- status ---------- cmd_status() { hdr "inkbd status ($(date '+%F %T'))" say "Machine : $(cat /sys/class/dmi/id/sys_vendor 2>/dev/null) $(cat /sys/class/dmi/id/product_name 2>/dev/null) | board $(cat /sys/class/dmi/id/board_name 2>/dev/null) | BIOS $(cat /sys/class/dmi/id/bios_version 2>/dev/null) ($(cat /sys/class/dmi/id/bios_date 2>/dev/null)) | EC fw $(cat /sys/class/dmi/id/ec_firmware_release 2>/dev/null)" say "Kernel : $(uname -r)" local q; q="$(cmdline_has_quirks)" say "i8042/atkbd params on live cmdline: ${q:-}" [[ -f "$DROPIN" ]] && say "inkbd boot preset file present: $DROPIN ($(grep -m1 -oE 'preset "[^"]*"' "$DROPIN"))" [[ -f "$BOOTFIX_UNIT" ]] && say "inkbd boot-fix service installed: $(systemctl is-enabled inkbd-bootfix.service 2>/dev/null) / $(systemctl is-active inkbd-bootfix.service 2>/dev/null)" say "serio0 : $( [[ -e $SERIO ]] && echo "present, driver=$(serio_driver), desc='$(cat $SERIO/description 2>/dev/null)', fw='$(cat $SERIO/firmware_id 2>/dev/null)'" || echo 'MISSING (i8042 found no keyboard port)')" say "i8042 : $( i8042_bound && echo bound || echo 'NOT bound' ); debug=$(cat /sys/module/i8042/parameters/debug 2>/dev/null || echo '?')" local node; node="$(kbd_event_node)" say "evdev : ${node:-}" say "IRQ 1 : $(irq1_count) interrupts since boot (a working keyboard adds 2 per keypress)" say "lid : $(cat /proc/acpi/button/lid/*/state 2>/dev/null | awk '{print $2}')" hdr "kernel messages about the PS/2 keyboard path (this boot)" kbd_kmsg | tail -n 25 | tee -a "${LOG:-/dev/null}" hdr "reading" if kbd_kmsg | grep -q 'Failed to deactivate keyboard'; then warn "atkbd got no (timely) ACK to 0xF5/0xF4 at boot. On this machine both the '8042 controller' and the 'keyboard' are functions of the same EC — this is an EC-communication/IRQ-delivery symptom, not evidence of a physically broken keyboard. Known cause on this barebone family: the AMD-Zen IRQ1 trigger-type bug (see README)." fi if kbd_kmsg | grep -q 'Failed to enable KBD port'; then bad "controller refused to enable the KBD port"; fi if kbd_kmsg | grep -qiE 'selftest failed|No controller found'; then bad "i8042 controller-level failure"; fi note "Next: 'inkbd watch' (press keys), then 'sudo inkbd diag' for the deep test." } # ---------- live steps ---------- step_reconnect() { # atkbd reconnect: re-sends 0xF5 / probe / 0xF4 on the live port [[ -e $SERIO/drvctl ]] || { bad "serio0 missing"; return 1; } printf 'reconnect' > "$SERIO/drvctl" 2>/dev/null && ok "serio0: reconnect requested" || { bad "reconnect write failed"; return 1; } sleep 1 } step_rebind() { # unbind/bind atkbd on serio0 (full atkbd_connect again) [[ -e $SERIO/drvctl ]] || { bad "serio0 missing"; return 1; } printf 'none' > "$SERIO/drvctl" 2>/dev/null; sleep 0.3 printf 'atkbd' > "$SERIO/drvctl" 2>/dev/null && ok "serio0: atkbd re-bound" || { printf 'rescan' > "$SERIO/drvctl" 2>/dev/null; warn "bind atkbd failed, asked for rescan"; } sleep 1 } ps2_raw_probe() { # talk PS/2 to the keyboard through serio_raw; prints byte-level results. Leaves atkbd bound afterwards. [[ -e $SERIO/drvctl ]] || { bad "serio0 missing"; return 1; } modprobe serio_raw 2>/dev/null || true local before; before="$(ls /dev/serio_raw* 2>/dev/null | tr '\n' ' ')" printf 'serio_raw' > "$SERIO/drvctl" 2>/dev/null || { bad "could not bind serio_raw to serio0"; printf 'atkbd' > "$SERIO/drvctl" 2>/dev/null; return 1; } sleep 0.5 local dev=""; for d in /dev/serio_raw*; do [[ " $before " == *" $d "* ]] || dev="$d"; done [[ -z "$dev" && -e /dev/serio_raw0 ]] && dev=/dev/serio_raw0 if [[ -z "$dev" ]]; then bad "no /dev/serio_rawN appeared"; printf 'atkbd' > "$SERIO/drvctl" 2>/dev/null; return 1; fi say "talking raw PS/2 to the keyboard via $dev (i8042 still handles the port; nothing bypassed)" python3 - "$dev" <<'PY' 2>&1 | tee -a "${LOG:-/dev/null}" import os, sys, select, time dev = sys.argv[1] fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK) def rd(timeout): got = [] end = time.time() + timeout while True: left = end - time.time() if left <= 0: break r, _, _ = select.select([fd], [], [], left) if not r: break try: got += list(os.read(fd, 64)) except BlockingIOError: pass # keep reading a little longer in case multi-byte reply is still coming end = min(end, time.time() + 0.15) if got else end return got def hx(bs): return ' '.join(f'{b:02x}' for b in bs) if bs else '(nothing)' def name(b): return {0xfa:'ACK',0xfe:'RESEND/NAK',0xfc:'BAT-FAIL',0xaa:'BAT-OK',0xee:'ECHO',0xab:'ID-hi',0x83:'ID-lo',0x41:'ID-lo(translated)'}.get(b, '') junk = rd(0.3) if junk: print(f" pending bytes before test: {hx(junk)}") tests = [ (0xee, 1.0, "ECHO -> expect EE"), (0xf2, 1.0, "GET ID -> expect FA AB 83 (or FA AB 41 on a translating i8042)"), (0xf5, 1.0, "DISABLE SCAN -> expect FA"), (0xff, 2.5, "RESET -> expect FA then AA (BAT ok) within ~1 s"), (0xf6, 1.0, "SET DEFAULTS -> expect FA"), (0xf4, 1.0, "ENABLE SCAN -> expect FA"), ] acks = 0; any_bytes = 0 for cmd, to, desc in tests: try: os.write(fd, bytes([cmd])) except OSError as e: print(f" {cmd:02x} {desc}: write failed: {e}"); continue got = rd(to) any_bytes += len(got) if 0xfa in got: acks += 1 tag = ' '.join(filter(None, (name(b) for b in got))) print(f" send {cmd:02x} {desc:<70} got: {hx(got)} {tag}") print(f"PS2RAW acks={acks} bytes={any_bytes}") os.close(fd) PY printf 'atkbd' > "$SERIO/drvctl" 2>/dev/null || printf 'rescan' > "$SERIO/drvctl" 2>/dev/null sleep 1 ok "serio0 handed back to atkbd" } step_ps2reset() { ps2_raw_probe; } raw_controller_probe() { # ONLY while i8042 is unbound: talk to the 8042 on ports 0x60/0x64 directly if i8042_bound; then bad "refusing raw port I/O while the i8042 driver is bound"; return 1; fi [[ -e /dev/port ]] || { warn "/dev/port missing"; return 1; } python3 - <<'PY' 2>&1 | tee -a "${LOG:-/dev/null}" import os, time try: fd = os.open('/dev/port', os.O_RDWR) except Exception as e: print(f" cannot open /dev/port: {e} (kernel lockdown?)"); raise SystemExit S, D = 0x64, 0x60 def inb(p): return os.pread(fd, 1, p)[0] def outb(p, v): os.pwrite(fd, bytes([v]), p) def stbits(s): n = [] for bit, nm in ((0,'OBF'),(1,'IBF'),(2,'SYS'),(3,'A2'),(4,'KEYLOCK-OPEN'),(5,'AUXOBF/TXTO'),(6,'TIMEOUT'),(7,'PARITY')): if s >> bit & 1: n.append(nm) return ','.join(n) or '-' def wait_ibf_clear(t=0.3): end = time.time() + t while time.time() < end: if not inb(S) & 2: return True time.sleep(0.001) return False def wait_obf(t=0.3): end = time.time() + t while time.time() < end: if inb(S) & 1: return True time.sleep(0.001) return False def flush(): n = 0 while inb(S) & 1 and n < 32: inb(D); n += 1; time.sleep(0.001) return n def ctl(cmd, want_resp=True, t=0.3): if not wait_ibf_clear(): return None outb(S, cmd) if not want_resp: return True return inb(D) if wait_obf(t) else None def dev(cmd, nresp=1, t=0.5): if not wait_ibf_clear(): return [] outb(D, cmd) got = [] end = time.time() + t while time.time() < end and len(got) < nresp: if wait_obf(max(0.001, end - time.time())): got.append(inb(D)) return got def hx(bs): return ' '.join(f'{b:02x}' for b in bs) if bs else '(nothing)' s = inb(S) print(f" status 0x64 = 0x{s:02x} [{stbits(s)}]") if s == 0xff: print(" status reads 0xFF: no 8042 present on the bus (EC not decoding 0x64?)") print(f" flushed {flush()} stale byte(s)") r = ctl(0xaa); print(f" 0xAA controller self-test -> {hx([r] if r is not None else [])} (expect 55)") r = ctl(0xab); print(f" 0xAB keyboard-line test -> {hx([r] if r is not None else [])} (00=ok 01=clk-low 02=clk-high 03=data-low 04=data-high)") ctr = ctl(0x20) if ctr is not None: bits = ' '.join(nm for bit, nm in ((0,'KBD-INT'),(1,'AUX-INT'),(2,'SYS'),(4,'KBD-DISABLED'),(5,'AUX-DISABLED'),(6,'XLATE')) if ctr >> bit & 1) print(f" 0x20 read CTR -> {ctr:02x} [{bits}]") else: print(" 0x20 read CTR -> (nothing)") ctl(0xae, want_resp=False); print(" 0xAE enable keyboard iface -> sent") if ctr is not None: newctr = (ctr & ~0x10) | 0x01 # KBD enabled, KBD IRQ on, keep XLATE if wait_ibf_clear(): outb(S, 0x60) if wait_ibf_clear(): outb(D, newctr) print(f" 0x60 write CTR -> {newctr:02x}") print(" --- now device-level commands straight to the keyboard ---") for cmd, n, t, desc in ((0xee,1,0.5,'ECHO -> EE'),(0xf2,3,0.8,'GET ID -> FA AB 83/41'),(0xff,2,2.5,'RESET -> FA AA'),(0xf4,1,0.5,'ENABLE -> FA')): got = dev(cmd, n, t); print(f" send {cmd:02x} {desc:<24} got: {hx(got)}") s = inb(S); print(f" status 0x64 = 0x{s:02x} [{stbits(s)}]") os.close(fd) PY } step_i8042() { # full controller re-init: unbind i8042 platform driver -> (raw probe) -> bind [[ -e $I8042_DRV/unbind ]] || { bad "i8042 driver has no unbind attribute on this kernel"; return 1; } if i8042_bound; then printf 'i8042' > "$I8042_DRV/unbind" 2>/dev/null && ok "i8042 driver unbound (controller reset by the kernel)" || { bad "unbind failed"; return 1; } sleep 0.5 else warn "i8042 was already unbound" fi if [[ "${1:-}" == "--raw" ]]; then hdr "raw 8042 controller probe (driver unbound, ports 0x60/0x64 directly)" raw_controller_probe fi local tries=0 until i8042_bound || (( tries >= 3 )); do printf 'i8042' > "$I8042_DRV/bind" 2>/dev/null sleep 1; tries=$((tries+1)) done if i8042_bound; then ok "i8042 driver re-bound (full controller init + atkbd connect re-ran)"; else bad "i8042 bind FAILED after $tries tries — check dmesg; reboot restores it"; return 1; fi sleep 1 } run_step() { case "$1" in reconnect) step_reconnect ;; rebind) step_rebind ;; ps2reset) step_ps2reset ;; i8042) step_i8042 ;; i8042-raw) step_i8042 --raw ;; *) bad "unknown step '$1' (reconnect|rebind|ps2reset|i8042|i8042-raw)"; return 2 ;; esac } # ---------- diag ---------- cmd_diag() { need_root diag open_log diag local secs="${1:-8}" cmd_status hdr "environment" say "cmdline: $(cat /proc/cmdline)" say "lockdown: $(cat /sys/kernel/security/lockdown 2>/dev/null)" say "uniwill-laptop: fn_lock=$(cat /sys/bus/platform/devices/INOU0000:00/fn_lock 2>/dev/null) super_key_enable=$(cat /sys/bus/platform/devices/INOU0000:00/super_key_enable 2>/dev/null) touchpad_toggle_enable=$(cat /sys/bus/platform/devices/INOU0000:00/touchpad_toggle_enable 2>/dev/null)" say "ITE 8291 (keyboard RGB controller) on USB: $(grep -l '048D:6008' /sys/class/hidraw/hidraw*/device/uevent 2>/dev/null | head -1 | xargs -r dirname | xargs -r basename)" say "PNP0303 resources: $(cat /sys/bus/pnp/devices/00:00/resources 2>/dev/null | tr '\n' ' ')" hdr "full i8042/atkbd kernel log since boot" kbd_kmsg | tee -a "$LOG" hdr "enable i8042 byte-level debug (runtime, reverts at reboot)" echo 1 > /sys/module/i8042/parameters/debug 2>/dev/null && ok "i8042.debug=1" || warn "could not enable i8042 debug" echo 1 > /sys/module/i8042/parameters/unmask_kbd_data 2>/dev/null && ok "i8042.unmask_kbd_data=1 (so real keyboard bytes are shown)" || true local m r hdr "step 1/4: atkbd reconnect on the live port (re-sends F5 / probe / F4)" m="$(dmesg_mark)"; step_reconnect; dmesg_since "$m" | grep -E 'i8042|atkbd' | tee -a "$LOG" classify_trace "$(dmesg_since "$m")" hdr "step 2/4: raw PS/2 conversation with the keyboard (serio_raw)" m="$(dmesg_mark)"; ps2_raw_probe; dmesg_since "$m" | grep -E 'i8042|atkbd|serio' | tee -a "$LOG" hdr "step 3/4: i8042 controller re-init + bare-metal 8042 probe" m="$(dmesg_mark)"; step_i8042 --raw; dmesg_since "$m" | grep -E 'i8042|atkbd|serio' | tee -a "$LOG" classify_trace "$(dmesg_since "$m")" hdr "step 4/4: does ANY byte arrive when you press keys? (${secs}s)" m="$(dmesg_mark)" watch_keys "$secs" say "--- i8042 bytes seen during the watch window:" dmesg_since "$m" | grep -E '<- i8042' | tee -a "$LOG" | tail -n 20 local bytes_in; bytes_in="$(dmesg_since "$m" | grep -c '<- i8042')" say "bytes from controller during watch: $bytes_in" hdr "IRQ 1 configuration (trigger type is the prime suspect on this barebone family)" say "--- live IOAPIC view (/sys/kernel/debug/irq/irqs/1):" cat /sys/kernel/debug/irq/irqs/1 2>/dev/null | tee -a "$LOG" || warn "debugfs irq info unavailable" say "--- MADT Interrupt Source Overrides (does the BIOS override IRQ 1 itself?):" python3 - <<'PY' 2>&1 | tee -a "$LOG" try: d = open('/sys/firmware/acpi/tables/APIC','rb').read() i, n = 44, 0 while i + 2 <= len(d): t, l = d[i], d[i+1] if l == 0: break if t == 2 and i + 10 <= len(d): src, gsi = d[i+3], int.from_bytes(d[i+4:i+8],'little') fl = int.from_bytes(d[i+8:i+10],'little') pol = {0:'default',1:'active-high',3:'active-low'}.get(fl & 3, '?') trg = {0:'default',1:'edge',3:'level'}.get((fl >> 2) & 3, '?') print(f" ISO: IRQ {src} -> GSI {gsi} polarity={pol} trigger={trg}") n += 1 i += l print(f" ({n} override entries total; NO entry for IRQ 1 means the kernel's Zen skip leaves the DSDT's falling-edge setting in place)") except Exception as e: print(f" could not parse MADT: {e}") PY hdr "firmware tables (for the record)" if [[ -r /sys/firmware/acpi/tables/DSDT ]]; then local td="$LOGDIR/acpi-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$td" cp /sys/firmware/acpi/tables/DSDT "$td/dsdt.aml" 2>/dev/null if command -v iasl >/dev/null 2>&1 && iasl -d "$td/dsdt.aml" >/dev/null 2>&1; then say "DSDT decompiled to $td/dsdt.dsl" say "--- PS2K device block:" awk '/Device \(PS2K\)/{p=1} p{print} p&&/^ {8}\}/{exit}' "$td/dsdt.dsl" | head -60 | tee -a "$LOG" say "--- IRQ descriptors in the DSDT (falling-edge/ActiveLow on IRQ 1 = the family bug):" grep -nE 'IRQ *\((Edge|Level), *(ActiveHigh|ActiveLow)' "$td/dsdt.dsl" | head -10 | tee -a "$LOG" || true say "--- EC field names that look keyboard-related:" grep -nE '^\s+(KB|KEY|KBD|KBC|PS2|SCAN)[A-Z0-9_]*,\s+[0-9]+,' "$td/dsdt.dsl" | head -20 | tee -a "$LOG" || true else warn "iasl not available / decompile failed (pacman -S acpica)" fi fi if modprobe ec_sys 2>/dev/null && [[ -r /sys/kernel/debug/ec/ec0/io ]]; then say "--- EC RAM (256 B window, read-only) :" od -An -tx1 -v /sys/kernel/debug/ec/ec0/io | tee -a "$LOG" fi echo 0 > /sys/module/i8042/parameters/unmask_kbd_data 2>/dev/null || true # leave debug on: harmless and lets later 'watch' runs be interpreted from dmesg; mention it hdr "VERDICT" verdict fix_owner say "" say "Log saved: $LOG (share it: inkbd report)" } classify_trace() { # look at an i8042.debug trace for device-command outcomes local t="$1" local sent acks naks sent="$(grep -cE '(f5|f4|f2|ff|ee|ed|f3) -> i8042 \(kbd-data\)' <<<"$t")" acks="$(grep -cE 'fa <- i8042' <<<"$t")" naks="$(grep -cE 'fe <- i8042' <<<"$t")" if (( sent == 0 )); then note "(no keyboard commands visible in trace — debug may be off)"; return; fi if (( acks > 0 )); then ok "keyboard ACKed $acks of $sent command bytes — the EC's keyboard function is ALIVE"; elif (( naks > 0 )); then warn "keyboard answered RESEND (0xFE) to commands ($naks) — EC sees no keyboard / rejects commands"; else bad "keyboard gave NO response to $sent command bytes (timeouts) — from the EC's point of view the keyboard is absent"; fi } verdict() { local t; t="$(dmesg 2>/dev/null | tail -n 800)" local acks naks bytes_total irqs acks="$(grep -cE 'fa <- i8042' <<<"$t")" naks="$(grep -cE 'fe <- i8042' <<<"$t")" irqs="$(irq1_count)" local ps2acks; ps2acks="$(grep -oE 'PS2RAW acks=[0-9]+' "$LOG" | tail -1 | grep -oE '[0-9]+$')"; ps2acks="${ps2acks:-0}" local ctl55; ctl55="$(grep -cE '0xAA controller self-test -> 55' "$LOG")" local evkeys; evkeys="$(grep -oE 'RESULT events=[0-9]+ keys=[0-9]+' "$LOG" | tail -1 | grep -oE 'keys=[0-9]+' | grep -oE '[0-9]+')"; evkeys="${evkeys:-0}" local irqd; irqd="$(grep -oE 'RESULT irq1_delta=[0-9]+' "$LOG" | tail -1 | grep -oE '[0-9]+$')"; irqd="${irqd:-0}" local bytes_watch; bytes_watch="$(grep -oE 'bytes from controller during watch: [0-9]+' "$LOG" | tail -1 | grep -oE '[0-9]+$')"; bytes_watch="${bytes_watch:-0}" say "controller self-test 0xAA->0x55: $([[ $ctl55 -gt 0 ]] && echo yes || echo no) | keyboard ACKs (any path): $(( acks + ps2acks )) | NAKs: $naks | watch window: irq_delta=$irqd bytes=$bytes_watch evdev_keys=$evkeys" say "(caveat: lock-key presses on the EXTERNAL keyboard during diag get LED-mirrored to serio0 and inflate ACK/IRQ counts)" say "" if (( evkeys > 0 )); then ok "KEYS REACH THE KERNEL NOW. diag ran all steps in sequence, so first identify the sufficient one: reboot, then run 'sudo inkbd apply ' for one step at a time until keys work again; make that one permanent with 'sudo inkbd install-boot-fix '." note "If keys reach the kernel but not your apps, the problem is in the desktop layer (Hyprland device rules / layout) — say so and I will chase that." elif (( irqd > 0 && bytes_watch == 0 )); then warn "IRQ 1 fired while you typed but the controller delivered NO bytes: empty interrupt pulses — the wrong-trigger-type signature (see README: AMD-Zen IRQ1 override bug, known on this barebone family)." note "Fix: 'sudo ./enable-keyboard' (installs the pnpacpi=off preset; 'enable-keyboard now' fixes without a reboot via the irq1fix module); durable fix = BIOS/EC update from PCSpecialist (see README)." elif (( irqd > 0 )); then warn "The controller delivered bytes while you typed, but atkbd produced no key events (swallowed or unparseable)." note "Run 'sudo ./enable-keyboard' (pnpacpi=off preset first; i8042.nopnp-style presets cannot fix the IRQ1 bug). Do NOT use 'direct' (see 'inkbd boot list')." elif (( acks + ps2acks > 0 )); then warn "The EC answers PS/2 commands (its keyboard function is ALIVE), but keypresses produce nothing." note "On this machine the 'keyboard' is emulated inside the EC and the flex cable carries raw matrix lines — so this is NOT evidence of a cable fault, and the same signature is produced by the family's IRQ1 trigger-type bug (late IRQs pass serio_raw's generous timeouts but scanning was never enabled because 0xF4 timed out)." note "Decisive gate: does it type in BIOS setup (F2/Del at power-on)? YES (confirmed 2026-08-24 on this machine) -> kernel/firmware class: run 'sudo ./enable-keyboard' (pnpacpi=off preset, or 'now' for the live irq1fix module); durable fix = BIOS/EC update (README). NO -> EC-level fault: EC reset by full power drain, then reseller EC re-flash (README). Do not open the chassis to 'reseat' anything — the keyboard is integral to the top case." elif (( ctl55 > 0 )); then if (( naks > 0 )); then warn "The 8042 front-end works and the keyboard function answers — but with NAK (0xFE) to everything: alive but rejecting commands." note "Try 'sudo inkbd boot dumb' (skips the command handshake entirely); if that types, keep it and pursue the BIOS/EC update (README)." else bad "The 8042 front-end in the EC works (self-test OK) but the keyboard function gave no answer at all (no ACK, no NAK)." fi note "Decisive gate: BIOS setup typing test. YES -> kernel/firmware class: run 'sudo ./enable-keyboard', and get the BIOS/EC update (README). NO -> EC reset (full power drain), then reseller EC re-flash — in that order; 'keyboard replacement' on this chassis means a whole top-case swap via the reseller (README)." else bad "Not even the 8042 controller front-end answered properly. The EC's keyboard-controller block is not responding." note "This is firmware: BIOS/EC update if obtainable, full EC reset (power drain), then reseller support. See README." fi } # ---------- apply one step (for experiments and for the boot-fix service) ---------- cmd_apply() { need_root apply local step="${1:-}"; [[ -n "$step" ]] || { echo "usage: sudo inkbd apply reconnect|rebind|ps2reset|i8042|i8042-raw"; exit 2; } open_log "apply-$step" run_step "$step"; local rc=$? fix_owner; return $rc } # ---------- boot presets (kernel cmdline via Limine drop-in) ---------- preset_params() { case "$1" in tongfang) echo "i8042.nopnp=1 i8042.nomux=1 i8042.reset=1 i8042.noloop=1" ;; pnpacpi) echo "pnpacpi=off" ;; dumb) echo "i8042.dumbkbd=1" ;; kbdreset) echo "i8042.kbdreset=1 atkbd.reset=1 i8042.reset=1" ;; notimeout) echo "i8042.notimeout=1 i8042.unlock=1" ;; defer) echo "i8042.probe_defer=1" ;; debug) echo "i8042.debug=1 i8042.unmask_kbd_data=1" ;; max) echo "i8042.nopnp=1 i8042.nomux=1 i8042.reset=1 i8042.noloop=1 i8042.kbdreset=1 i8042.notimeout=1 i8042.unlock=1 atkbd.reset=1" ;; direct) echo "i8042.direct=1" ;; *) return 1 ;; esac } preset_desc() { case "$1" in tongfang) echo "i8042 quirks the kernel applies to other TongFang boards (skip PnP for i8042, no mux, always reset, no AUX loop). CANNOT fix the IRQ1 bug: the wrong polarity is programmed by the PNP-ACPI core at early boot, before i8042 even loads (verified against v7.1 source) — kept only for unrelated controller quirks" ;; pnpacpi) echo "disable ACPI PnP resource parsing: the boot-time call that programs IRQ1 falling-edge never happens, so the pin keeps the edge/active-high default the EC needs. THE preset for this bug — confirmed on sibling TongFang Zen boards (Arch BBS 291569); 'enable-keyboard' installs it for you. Try FIRST" ;; dumb) echo "never send commands to the keyboard, just accept scancodes. Sibling boards with THIS bug report ~1 s key-release delay + runaway key repeat (near-unusable), and it breaks 'inkbd ledecho'. Last resort only" ;; kbdreset) echo "hard-reset the keyboard device during init (i8042 + atkbd reset)" ;; notimeout) echo "ignore the i8042 timeout bit / keylock bit" ;; defer) echo "let i8042 defer probing if the controller is not ready early in boot" ;; debug) echo "byte-level i8042 trace from the very first moment of boot (for diagnosis, not a fix)" ;; max) echo "everything that does not conflict, at once (last resort)" ;; direct) echo "AVOID ON THIS MACHINE: non-translated mode makes atkbd send GETID, which times out on this EC — atkbd_connect then fails and the keyboard device disappears entirely" ;; esac } cmd_boot() { local what="${1:-list}" case "$what" in list|"") hdr "kernel-cmdline presets (one reboot each; install with: sudo inkbd boot NAME) — try in this order" for p in pnpacpi tongfang dumb kbdreset notimeout defer debug max direct; do printf ' %-10s %s\n -> %s\n' "$p" "$(preset_desc $p)" "$(preset_params $p)"; done echo echo "installed drop-in: $([[ -f $DROPIN ]] && cat "$DROPIN" | grep -vE '^#' || echo '')" echo "live now : $(cmdline_has_quirks)"; echo "${CB}Tip:${C0} after each reboot run 'inkbd status' then 'inkbd watch'. Remove with: sudo inkbd boot revert" ;; revert) need_root boot revert if [[ -f "$DROPIN" ]]; then rm -f "$DROPIN"; ok "removed $DROPIN"; else warn "no preset installed"; fi echo "rebuilding boot entries (limine-update)…"; limine-update && ok "done — reboot to apply" ;; custom) need_root boot custom shift; local params="$*"; [[ -n "$params" ]] || { echo "usage: sudo inkbd boot custom 'i8042.foo=1 ...'"; exit 2; } install_dropin "custom" "$params" ;; *) need_root boot "$what" local params; params="$(preset_params "$what")" || { bad "unknown preset '$what' — see: inkbd boot list"; exit 2; } install_dropin "$what" "$params" ;; esac } install_dropin() { local name="$1" params="$2" [[ -d /etc/limine-entry-tool.d ]] || { bad "/etc/limine-entry-tool.d missing — not a Limine-entry-tool system; add to your bootloader by hand: $params"; exit 1; } cat > "$DROPIN" < "$BOOTFIX_UNIT" </dev/null 2>&1 || true' [Install] WantedBy=multi-user.target UNIT systemctl daemon-reload && systemctl enable --now inkbd-bootfix.service && ok "installed + started inkbd-bootfix.service (step=$step). Undo: sudo inkbd uninstall-boot-fix" } cmd_uninstall_boot_fix() { need_root uninstall-boot-fix systemctl disable --now inkbd-bootfix.service 2>/dev/null; rm -f "$BOOTFIX_UNIT"; systemctl daemon-reload; ok "removed" } # ---------- suspend cycle ---------- cmd_suspend_cycle() { need_root suspend-cycle open_log suspend warn "This suspends the laptop (EC goes through its sleep/wake path, the kernel re-inits i8042 + atkbd on resume). Save your work. Wake it with the POWER button." read -r -p "Continue? [y/N] " a; [[ "$a" =~ ^[Yy]$ ]] || exit 0 echo 1 > /sys/module/i8042/parameters/debug 2>/dev/null || true local m; m="$(dmesg_mark)" systemctl suspend sleep 3 say "back from suspend; i8042/atkbd messages since:"; dmesg_since "$m" | grep -E 'i8042|atkbd' | tee -a "$LOG" classify_trace "$(dmesg_since "$m")" watch_keys 8 fix_owner } # ---------- report ---------- cmd_report() { mkdir -p "$LOGDIR" local out="$LOGDIR/inkbd-report-$(date +%Y%m%d-%H%M%S).tar.gz" { cmd_status; } > "$LOGDIR/status-now.txt" 2>&1 tar -czf "$out" -C "$SCRIPT_DIR" logs 2>/dev/null && echo "report: $out" } usage() { sed -n '2,20p' "$SCRIPT_PATH" | sed 's/^# \{0,1\}//'; } case "${1:-help}" in status) cmd_status ;; watch) watch_keys "${2:-10}" ;; ledecho) led_echo "${2:-3}" ;; diag) cmd_diag "${2:-8}" ;; apply) cmd_apply "${2:-}" ;; boot) shift; cmd_boot "$@" ;; install-boot-fix) cmd_install_boot_fix "${2:-}" ;; uninstall-boot-fix) cmd_uninstall_boot_fix ;; suspend-cycle) cmd_suspend_cycle ;; report) cmd_report ;; -h|--help|help) usage ;; *) echo "unknown subcommand: $1"; usage; exit 2 ;; esac