277 lines
12 KiB
Python
277 lines
12 KiB
Python
"""MSI motherboard fan headers on the Nuvoton NCT6687D Super I/O, through PawnIO's signed LpcIO module.
|
|
|
|
Register layout and the fan-configuration handshake follow LibreHardwareMonitor's Nct677X.cs.
|
|
Needs PawnIO and administrator rights. Run ``python board_fans.py --probe`` to list the headers.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ctypes
|
|
import ctypes.wintypes as wt
|
|
import os
|
|
import struct
|
|
import threading
|
|
import time
|
|
|
|
from kurgan.hardware import PAWNIO_DIR
|
|
|
|
|
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
|
_k32.CreateFileW.restype = wt.HANDLE
|
|
_k32.DeviceIoControl.argtypes = [wt.HANDLE, wt.DWORD, ctypes.c_void_p, wt.DWORD, ctypes.c_void_p, wt.DWORD,
|
|
ctypes.POINTER(wt.DWORD), ctypes.c_void_p]
|
|
_k32.DeviceIoControl.restype = wt.BOOL
|
|
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
|
_k32.CreateMutexW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.LPCWSTR]
|
|
_k32.CreateMutexW.restype = wt.HANDLE
|
|
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
|
_k32.WaitForSingleObject.restype = wt.DWORD
|
|
_k32.ReleaseMutex.argtypes = [wt.HANDLE]
|
|
|
|
|
|
class PawnIo:
|
|
DEVICE = r"\\?\GLOBALROOT\Device\PawnIO"
|
|
IOCTL_LOAD_BINARY = 0xA1B22084
|
|
IOCTL_EXECUTE_FN = 0xA1B22104
|
|
|
|
def __init__(self, module: str):
|
|
h = _k32.CreateFileW(self.DEVICE, 0xC0000000, 0x3, None, 3, 0, None)
|
|
if h == wt.HANDLE(-1).value:
|
|
err = ctypes.get_last_error()
|
|
reason = "run as administrator" if err == 5 else "is PawnIO installed?"
|
|
raise OSError(f"Cannot open PawnIO ({ctypes.FormatError(err).strip()}; {reason})")
|
|
self.handle = h
|
|
with open(module, "rb") as f:
|
|
blob = f.read()
|
|
ret = wt.DWORD()
|
|
if not _k32.DeviceIoControl(h, self.IOCTL_LOAD_BINARY, blob, len(blob), None, 0, ctypes.byref(ret), None):
|
|
err = ctypes.get_last_error()
|
|
self.close()
|
|
raise OSError(f"PawnIO refused {os.path.basename(module)}: {ctypes.FormatError(err).strip()}")
|
|
|
|
def execute(self, fn: str, args: tuple[int, ...] = (), out: int = 0) -> tuple[int, ...]:
|
|
inbuf = fn.encode().ljust(32, b"\x00") + struct.pack(f"<{len(args)}q", *args)
|
|
outbuf = ctypes.create_string_buffer(8 * out)
|
|
ret = wt.DWORD()
|
|
if not _k32.DeviceIoControl(self.handle, self.IOCTL_EXECUTE_FN, inbuf, len(inbuf), outbuf, 8 * out,
|
|
ctypes.byref(ret), None):
|
|
raise OSError(f"PawnIO {fn} failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
|
return struct.unpack(f"<{out}Q", outbuf.raw)
|
|
|
|
def close(self) -> None:
|
|
if self.handle:
|
|
_k32.CloseHandle(self.handle)
|
|
self.handle = None
|
|
|
|
|
|
class Nct6687:
|
|
"""NCT6687D EC: 16 RPM inputs; PWM channels 0-7 are CPU, pump, then system fans 1-6."""
|
|
|
|
MODULE = os.path.join(PAWNIO_DIR, "LpcIO.bin")
|
|
ISA_MUTEX = "Global\\Access_ISABUS.HTP.Method" # shared with LibreHardwareMonitor/FanControl
|
|
CHANNELS = 8
|
|
PAGE, INDEX, DATA = 4, 5, 6
|
|
RPM, PWM_OUT, MODE, REQUEST, COMMAND = 0x140, 0x160, 0xA00, 0xA01, 0xA28
|
|
CFG_REQUEST, CFG_COMPLETE = 0x80, 0x40
|
|
|
|
def __init__(self):
|
|
self._lock = threading.RLock()
|
|
self._mutex = _k32.CreateMutexW(None, False, self.ISA_MUTEX)
|
|
if not self._mutex:
|
|
raise OSError(f"Cannot open the ISA bus mutex: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
|
|
self.io: PawnIo | None = None
|
|
try:
|
|
self.io = PawnIo(self.MODULE)
|
|
with self._bus():
|
|
self.base, self.slot = self._detect()
|
|
except Exception:
|
|
self.close()
|
|
raise
|
|
|
|
def close(self) -> None:
|
|
if self.io is not None:
|
|
self.io.close()
|
|
self.io = None
|
|
if self._mutex:
|
|
_k32.CloseHandle(self._mutex)
|
|
self._mutex = None
|
|
|
|
def _bus(self):
|
|
nct = self
|
|
|
|
class _Held:
|
|
def __enter__(self):
|
|
nct._lock.acquire()
|
|
if _k32.WaitForSingleObject(nct._mutex, 500) not in (0, 0x80): # WAIT_OBJECT_0, WAIT_ABANDONED
|
|
nct._lock.release()
|
|
raise OSError("ISA bus busy (another hardware monitor is holding it)")
|
|
|
|
def __exit__(self, *exc):
|
|
_k32.ReleaseMutex(nct._mutex)
|
|
nct._lock.release()
|
|
|
|
return _Held()
|
|
|
|
def _detect(self) -> tuple[int, int]:
|
|
assert self.io is not None
|
|
for slot, reg in ((0, 0x2E), (1, 0x4E)):
|
|
self.io.execute("ioctl_select_slot", (slot,))
|
|
self.io.execute("ioctl_pio_outb", (reg, 0x87))
|
|
self.io.execute("ioctl_pio_outb", (reg, 0x87))
|
|
chip = self.io.execute("ioctl_superio_inb", (0x20,), 1)[0]
|
|
rev = self.io.execute("ioctl_superio_inb", (0x21,), 1)[0]
|
|
if (chip, rev) != (0xD5, 0x92):
|
|
if chip not in (0, 0xFF):
|
|
self.io.execute("ioctl_pio_outb", (reg, 0xAA))
|
|
continue
|
|
self.io.execute("ioctl_find_bars")
|
|
self.io.execute("ioctl_superio_outb", (0x07, 0x0B)) # hardware-monitor logical device
|
|
base = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0]
|
|
time.sleep(0.001)
|
|
verify = self.io.execute("ioctl_superio_inw", (0x60,), 1)[0]
|
|
self.io.execute("ioctl_pio_outb", (reg, 0xAA))
|
|
if base != verify or base < 0x100 or base in (0xFFFF,):
|
|
raise OSError(f"NCT6687D at 0x{reg:X} reported an invalid base address 0x{base:X}")
|
|
return base & 0xFFF8, slot
|
|
raise OSError("No Nuvoton NCT6687D Super I/O found (expected on MSI 600/700-series boards)")
|
|
|
|
def _out(self, port: int, value: int) -> None:
|
|
assert self.io is not None
|
|
self.io.execute("ioctl_pio_outb", (self.base + port, value))
|
|
|
|
def _in(self, port: int) -> int:
|
|
assert self.io is not None
|
|
return self.io.execute("ioctl_pio_inb", (self.base + port,), 1)[0]
|
|
|
|
def _claim_page(self) -> None:
|
|
deadline = time.monotonic() + 0.5
|
|
while self._in(self.PAGE) != 0xFF:
|
|
if time.monotonic() >= deadline:
|
|
self._out(self.PAGE, 0xFF) # stale owner: force access, as LibreHardwareMonitor does
|
|
return
|
|
time.sleep(0.001)
|
|
|
|
def read(self, address: int) -> int:
|
|
self._claim_page()
|
|
self._out(self.PAGE, address >> 8)
|
|
self._out(self.INDEX, address & 0xFF)
|
|
value = self._in(self.DATA)
|
|
self._out(self.PAGE, 0xFF)
|
|
return value
|
|
|
|
def write(self, address: int, value: int) -> None:
|
|
self._claim_page()
|
|
self._out(self.PAGE, address >> 8)
|
|
self._out(self.INDEX, address & 0xFF)
|
|
self._out(self.DATA, value & 0xFF)
|
|
self._out(self.PAGE, 0xFF)
|
|
|
|
def rpms(self) -> list[int]:
|
|
"""RPM of all 16 tachometer inputs."""
|
|
with self._bus():
|
|
return [(self.read(self.RPM + 2 * i) << 8) | self.read(self.RPM + 2 * i + 1) for i in range(16)]
|
|
|
|
def duties(self) -> list[int]:
|
|
"""Current output duty (0-100%) of PWM channels 0-7."""
|
|
with self._bus():
|
|
return [round(self.read(self.PWM_OUT + i) / 2.55) for i in range(self.CHANNELS)]
|
|
|
|
def manual_mask(self) -> int:
|
|
with self._bus():
|
|
return self.read(self.MODE)
|
|
|
|
def _check_channels(self, channels: tuple[int, ...]) -> int:
|
|
if not channels or any(c not in range(self.CHANNELS) for c in channels):
|
|
raise ValueError(f"PWM channels must be 0-{self.CHANNELS - 1}")
|
|
mask = 0
|
|
for c in channels:
|
|
mask |= 1 << c
|
|
return mask
|
|
|
|
def set_manual(self, channels: tuple[int, ...], duty: int) -> None:
|
|
"""Override the BIOS curve with a fixed duty on these channels."""
|
|
mask = self._check_channels(channels)
|
|
if not 0 <= duty <= 100:
|
|
raise ValueError("duty must be 0-100")
|
|
with self._bus():
|
|
self.write(self.REQUEST, self.CFG_REQUEST)
|
|
time.sleep(0.05)
|
|
self.write(self.MODE, self.read(self.MODE) | mask)
|
|
for c in channels:
|
|
self.write(self.COMMAND + c, round(duty * 2.55))
|
|
self.write(self.REQUEST, self.CFG_COMPLETE)
|
|
time.sleep(0.05)
|
|
|
|
def set_auto(self, channels: tuple[int, ...]) -> None:
|
|
"""Hand these channels back to the BIOS Smart Fan curve."""
|
|
mask = self._check_channels(channels)
|
|
with self._bus():
|
|
self.write(self.REQUEST, self.CFG_REQUEST)
|
|
time.sleep(0.05)
|
|
self.write(self.MODE, self.read(self.MODE) & ~mask & 0xFF)
|
|
self.write(self.REQUEST, self.CFG_COMPLETE)
|
|
time.sleep(0.05)
|
|
|
|
|
|
def parse_channels(text: str) -> tuple[int, ...]:
|
|
try:
|
|
channels = tuple(sorted({int(c) for c in text.split(",")}))
|
|
except ValueError as e:
|
|
raise argparse.ArgumentTypeError("Use comma-separated PWM channels, e.g. 2,5") from e
|
|
if not channels or any(c not in range(Nct6687.CHANNELS) for c in channels):
|
|
raise argparse.ArgumentTypeError(f"PWM channels must be 0-{Nct6687.CHANNELS - 1}")
|
|
return channels
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__)
|
|
action = ap.add_mutually_exclusive_group(required=True)
|
|
action.add_argument("--probe", action="store_true", help="read-only listing of the fan headers")
|
|
action.add_argument("--identify", type=parse_channels, metavar="2,5",
|
|
help="hold these PWM channels at 100%% (until --auto) to see which fans they drive")
|
|
action.add_argument("--auto", type=parse_channels, metavar="2,5",
|
|
help="return these PWM channels to the BIOS Smart Fan curve")
|
|
ap.add_argument("--out", help="also write the report to this file")
|
|
args = ap.parse_args()
|
|
lines: list[str] = []
|
|
try:
|
|
nct = Nct6687()
|
|
try:
|
|
if args.identify:
|
|
nct.set_manual(args.identify, 100)
|
|
time.sleep(5)
|
|
lines.append(f"Channels {args.identify} held at 100% until --auto")
|
|
elif args.auto:
|
|
nct.set_auto(args.auto)
|
|
time.sleep(3)
|
|
lines.append(f"Channels {args.auto} returned to the BIOS curve")
|
|
with nct._bus():
|
|
regs = {a: nct.read(a) for a in (0x180, nct.MODE, nct.REQUEST)}
|
|
commands = [nct.read(nct.COMMAND + i) for i in range(nct.CHANNELS)]
|
|
temps = [nct.read(0x100 + 2 * i) for i in range(7)]
|
|
rpms, duties = nct.rpms(), nct.duties()
|
|
lines.append(f"NCT6687D slot {nct.slot}, base 0x{nct.base:X}")
|
|
lines.append("init 0x180=0x%02X manual mask 0xA00=0x%02X request 0xA01=0x%02X" % tuple(regs.values()))
|
|
lines.append("temps 0x100..: " + ", ".join(str(struct.unpack('b', bytes([t]))[0]) for t in temps))
|
|
for i in range(nct.CHANNELS):
|
|
lines.append(f"PWM ch{i}: out {duties[i]:3d}% command {commands[i]:3d} "
|
|
f"manual {'yes' if regs[nct.MODE] >> i & 1 else 'no'}")
|
|
for i, rpm in enumerate(rpms):
|
|
lines.append(f"RPM reg 0x{nct.RPM + 2 * i:03X}: {rpm}")
|
|
finally:
|
|
nct.close()
|
|
except Exception as e:
|
|
lines.append(f"ERROR: {type(e).__name__}: {e}")
|
|
report = "\n".join(lines)
|
|
print(report)
|
|
if args.out:
|
|
with open(args.out, "w", encoding="utf-8") as f:
|
|
f.write(report + "\n")
|
|
return 1 if report.startswith("ERROR") or "\nERROR" in report else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|