Split the sleep validator into a package Split the sleep validator into a package so that the capture, analysis and suspend helpers can be maintained separately. While splitting: * carry over the smu_fw_info debug capture that upstream added to the monolithic validator (d617b15) * guard the rtc_cmos check against systems that don't expose the use_acpi_alarm parameter instead of crashing after resume * import dbus in its own try block before the logind calls: the except clause references the dbus module, so when the import fails the module name is unbound and the Missing dbus handling would crash * wire up the duration analysis that was previously unreachable, so the per cycle userspace/kernel/hardware sleep durations are printed * drop a duplicate upep initialisation The rest of the behaviour is unchanged.
diff --git a/src/amd_debug/validator.py b/src/amd_debug/validator.py deleted file mode 100644 index e047ca6..0000000 --- a/src/amd_debug/validator.py +++ /dev/null
@@ -1,911 +0,0 @@ -# SPDX-License-Identifier: MIT - -import glob -import math -import os -import re -import random -import subprocess -import time -from datetime import timedelta, datetime -from packaging import version -from pyudev import Context - -from amd_debug.sleep_report import SleepReport -from amd_debug.database import SleepDatabase -from amd_debug.battery import Batteries -from amd_debug.power_rails import PowerRails -from amd_debug.kernel import get_kernel_log, get_kernel_command_line, sscanf_bios_args -from amd_debug.common import ( - print_color, - read_file, - check_lockdown, - run_countdown, - BIT, - AmdTool, -) -from amd_debug.acpi import AcpicaTracer -from amd_debug.failures import ( - AcpiBiosError, - Irq1Workaround, - LowHardwareSleepResidency, - SpuriousWakeup, - RtcAlarmWrong, - IommuPageFault, -) - - -class Headers: - """Header strings for the debug output""" - - Irq1Workaround = "Disabling IRQ1 wakeup source to avoid platform firmware bug" - WokeFromIrq = "Woke up from IRQ" - LastCycleResults = "Results from last s2idle cycle" - CycleCount = "Suspend cycle" - SuspendDuration = "Suspend timer programmed for" - - -def soc_needs_irq1_wa(family, model, smu_version): - """Check if the SoC needs the IRQ1 workaround""" - if family == 0x17: - if model in [0x68, 0x60]: - return True - elif family == 0x19: - if model == 0x50: - return version.parse(smu_version) < version.parse("64.66.0") - return False - - -def toggle_pm_debug(enable): - """Enable or disable pm_debug_messages""" - pm_debug_messages = os.path.join("/", "sys", "power", "pm_debug_messages") - with open(pm_debug_messages, "w", encoding="utf-8") as w: - w.write("1" if enable else "0") - - -def pm_debugging(func): - """Decorator to enable pm_debug_messages""" - - def runner(*args, **kwargs): - toggle_pm_debug(True) - ret = func(*args, **kwargs) - toggle_pm_debug(False) - - return ret - - return runner - - -class SleepValidator(AmdTool): - """Class to validate the sleep state""" - - def __init__(self, tool_debug, bios_debug): - log_prefix = "s2idle" if tool_debug else None - super().__init__(log_prefix) - - self.pyudev = Context() - - self.kernel_log = get_kernel_log() - self.db = SleepDatabase() - self.batteries = Batteries() - self.power_rails = PowerRails() - self.acpica = AcpicaTracer() - self.bios_debug = bios_debug - self.cpu_family = "" - self.cpu_model = "" - self.cpu_model_string = "" - self.smu_version = "" - self.smu_program = "" - self.last_suspend = datetime.now() - self.requested_duration = 0 - self.userspace_duration = 0 - self.kernel_duration = 0 - self.hw_sleep_duration = 0 - self.failures = [] - self.gpes = {} - self.display_debug = tool_debug - self.lockdown = check_lockdown() - self.logind = False - self.upep = False - self.cycle_count = 0 - self.upep = False - self.upep_microsoft = False - self.wakeup_irqs = [] - self.idle_masks = [] - self.acpi_errors = [] - self.active_gpios = [] - self.irq1_workaround = False - self.thermal = {} - self.wakeup_count = {} - self.page_faults = [] - self.notify_devices = [] - - def capture_running_compositors(self): - """Capture information about known compositor processes found""" - - known_compositors = [ - "kwin_wayland", - "gnome-shell", - "cosmic-session", - "hyprland", - ] - - # Get a list of all process directories in /proc - process_dirs = glob.glob("/proc/[0-9]*") - - # Extract and print the process names - for proc_dir in process_dirs: - p = os.path.join(proc_dir, "exe") - if not os.path.exists(p): - continue - exe = os.path.basename(os.readlink(p)).split()[0] - if exe in known_compositors: - self.db.record_debug(f"{exe} compositor is running") - - def capture_power_profile(self): - """Capture power profile information""" - cmd = ["/usr/bin/powerprofilesctl"] - if os.path.exists(cmd[0]): - try: - output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode( - "utf-8" - ) - self.db.record_debug("Power Profiles:") - lines = output.split("\n") - lines = [line for line in lines if line.strip()] - for line in lines: - prefix = "│ " if line != lines[-1] else "└─" - self.db.record_debug(f"{prefix}{line.strip()}") - except subprocess.CalledProcessError as e: - self.db.record_debug("Failed to run powerprofilesctl: %s", e.output) - - def capture_battery(self): - """Capture battery energy levels""" - for name in self.batteries.get_batteries(): - energy = self.batteries.get_energy(name) - full = self.batteries.get_energy_full(name) - self.db.record_debug(f"{name} energy level is {energy} µWh") - self.db.record_battery_energy(name, energy, full, "W") - - def capture_power_rails(self): - """Capture power rail energy levels""" - if not self.power_rails.rails: - return # No IIO power rails detected - - for rail in self.power_rails.rails: - try: - energy = rail.read_energy_raw() - self.db.record_power_rail_energy( - rail.label, energy, rail.energy_scale - ) - except OSError as e: - self.db.record_debug( - f"Failed to read {rail.label}: {e}", priority=1 - ) - - def check_rtc_cmos(self): - """Check if the RTC is configured to use ACPI alarm""" - p = os.path.join( - "/", "sys", "module", "rtc_cmos", "parameters", "use_acpi_alarm" - ) - val = read_file(p) - if val == "N": - self.db.record_cycle_data( - "`rtc_cmos` not configured to use ACPI alarm", "🚦" - ) - self.failures += [RtcAlarmWrong()] - - def check_gpes(self): - """Capture general purpose event count""" - base = os.path.join("/", "sys", "firmware", "acpi", "interrupts") - for root, _dirs, files in os.walk(base, topdown=False): - for fname in files: - if not fname.startswith("gpe") or fname == "gpe_all": - continue - target = os.path.join(root, fname) - val = 0 - with open(target, "r", encoding="utf-8") as r: - val = int(r.read().split()[0]) - if fname in self.gpes and self.gpes[fname] != val: - self.db.record_debug( - f"{fname} increased from {self.gpes[fname]} to {val}", - ) - self.gpes[fname] = val - - def capture_wake_sources(self): - """Capture possible wakeup sources""" - - def get_input_sibling_name(pyudev, parent): - """Get the name of the input sibling""" - for inp in pyudev.list_devices(subsystem="input", parent=parent): - if not "NAME" in inp.properties: - continue - return inp.properties["NAME"] - return "" - - devices = [] - for wake_dev in self.pyudev.list_devices(subsystem="wakeup"): - p = os.path.join(wake_dev.sys_path, "device", "power", "wakeup") - if not os.path.exists(p): - continue - wake_en = read_file(p) - name = "" - sys_name = wake_dev.sys_path - # determine the type of device it hangs off of - acpi = wake_dev.find_parent(subsystem="acpi") - serio = wake_dev.find_parent(subsystem="serio") - rtc = wake_dev.find_parent(subsystem="rtc") - pci = wake_dev.find_parent(subsystem="pci") - mhi = wake_dev.find_parent(subsystem="mhi") - pnp = wake_dev.find_parent(subsystem="pnp") - hid = wake_dev.find_parent(subsystem="hid") - thunderbolt_device = wake_dev.find_parent( - subsystem="thunderbolt", device_type="thunderbolt_device" - ) - thunderbolt_domain = wake_dev.find_parent( - subsystem="thunderbolt", device_type="thunderbolt_domain" - ) - i2c = wake_dev.find_parent(subsystem="i2c") - if i2c is not None: - sys_name = i2c.sys_name - name = get_input_sibling_name(self.pyudev, i2c) - elif thunderbolt_device is not None: - if "USB4_TYPE" in thunderbolt_device.properties: - name = ( - f'USB4 {thunderbolt_device.properties["USB4_TYPE"]} controller' - ) - sys_name = thunderbolt_device.sys_name - elif thunderbolt_domain is not None: - name = "Thunderbolt domain" - sys_name = thunderbolt_domain.sys_name - elif serio is not None: - sys_name = serio.sys_name - name = get_input_sibling_name(self.pyudev, serio) - elif rtc is not None: - sys_name = rtc.sys_name - for _parent in self.pyudev.list_devices( - subsystem="platform", parent=rtc, DRIVER="alarmtimer" - ): - name = "Real Time Clock alarm timer" - break - elif mhi is not None: - sys_name = mhi.sys_name - name = "Mobile Broadband host interface" - elif hid is not None: - name = hid.properties["HID_NAME"] - sys_name = hid.sys_name - elif pci is not None: - sys_name = pci.sys_name - if ( - "ID_PCI_SUBCLASS_FROM_DATABASE" in pci.properties - and "ID_VENDOR_FROM_DATABASE" in pci.properties - ): - name = f'{pci.properties["ID_VENDOR_FROM_DATABASE"]} {pci.properties["ID_PCI_SUBCLASS_FROM_DATABASE"]}' - else: - name = f"PCI {pci.properties['PCI_CLASS']}" - elif acpi is not None: - sys_name = acpi.sys_name - if acpi.driver == "button": - for inp in self.pyudev.list_devices(subsystem="input", parent=acpi): - if not "NAME" in inp.properties: - continue - name = f"ACPI {inp.properties['NAME']}" - break - elif acpi.driver in ["battery", "ac"]: - for ps in self.pyudev.list_devices( - subsystem="power_supply", parent=acpi - ): - if not "POWER_SUPPLY_NAME" in ps.properties: - continue - name = f"ACPI {ps.properties['POWER_SUPPLY_TYPE']}" - elif pnp is not None: - name = "Plug-n-play" - if pnp.driver == "rtc_cmos": - name = f"{name} Real Time Clock" - sys_name = pnp.sys_name - - name = name.replace('"', "") - devices.append(f"{name}|{sys_name}|{wake_en}") - devices.sort() - debug_str = "Wakeup Source|Linux Device|Status\n" - for dev in devices: - debug_str += f"{dev}\n" - self.db.record_debug(debug_str) - - def capture_lid(self) -> None: - """Capture lid state""" - p = os.path.join("/", "proc", "acpi", "button", "lid") - for root, _dirs, files in os.walk(p): - for fname in files: - p = os.path.join(root, fname) - state = read_file(p).split(":")[1].strip() - self.db.record_debug(f"ACPI Lid ({p}): {state}") - - def capture_wakeup_irq_data(self) -> bool: - """Capture the wakeup IRQ to the log""" - p = os.path.join("/", "sys", "power", "pm_wakeup_irq") - try: - n = read_file(p) - p = os.path.join("/", "sys", "kernel", "irq", n) - chip_name = read_file(os.path.join(p, "chip_name")) - name = read_file(os.path.join(p, "name")) - hw = read_file(os.path.join(p, "hwirq")) - actions = read_file(os.path.join(p, "actions")) - message = f"{Headers.WokeFromIrq} {n} ({chip_name} {hw}-{name} {actions})" - self.db.record_debug(message) - irq = int(n) - if irq and irq not in self.wakeup_irqs: - self.wakeup_irqs += [irq] - except OSError: - pass - return True - - def capture_amdgpu_ips_status(self): - """Capture the AMDGPU IPS status""" - for device in self.pyudev.list_devices(subsystem="pci", PCI_CLASS="38000"): - pci_id = device.properties.get("PCI_ID") - if not pci_id.startswith("1002"): - continue - slot = device.properties.get("PCI_SLOT_NAME") - p = os.path.join( - "/", "sys", "kernel", "debug", "dri", slot, "amdgpu_dm_ips_status" - ) - if not os.path.exists(p): - continue - self.db.record_debug("IPS status") - try: - lines = read_file(p).split("\n") - for line in lines: - prefix = "│ " if line != lines[-1] else "└─" - self.db.record_debug(f"{prefix}{line}") - except PermissionError: - if self.lockdown: - self.db.record_debug( - "Unable to gather IPS state data due to kernel lockdown." - ) - else: - self.db.record_debug("Failed to read IPS state data") - - def capture_thermal(self): - """Capture thermal zone information""" - devs = [] - for dev in self.pyudev.list_devices(subsystem="acpi", DRIVER="thermal"): - devs.append(dev) - if not devs: - return - - self.db.record_debug("Thermal zones") - for dev in devs: - prefix = "├─ " if dev != devs[-1] else "└─" - detail_prefix = "│ \t" if dev != devs[-1] else " \t" - name = os.path.basename(dev.device_path) - p = os.path.join(dev.sys_path, "thermal_zone") - temp = int(read_file(os.path.join(p, "temp"))) / 1000 - - self.db.record_debug(f"{prefix}{name}") - if name not in self.thermal: - self.db.record_debug(f"{detail_prefix} temp: {temp}°C") - else: - self.db.record_debug( - f"{detail_prefix} {self.thermal[name]}°C -> {temp}°C" - ) - - # handle all trip points - trip_count = 0 - for f in os.listdir(p): - if "trip_point" not in f: - continue - if "temp" not in f: - continue - trip_count = trip_count + 1 - - for i in range(0, trip_count): - f = os.path.join(p, f"trip_point_{i}_type") - trip_type = read_file(f) - f = os.path.join(p, f"trip_point_{i}_temp") - trip = int(read_file(f)) / 1000 - - if name not in self.thermal: - self.db.record_debug(f"{detail_prefix} {trip_type} trip: {trip}°C") - - if temp > trip: - self.db.record_prereq( - f"Thermal zone {name} past trip point {trip_type}: {trip}°C", - "🌡️", - ) - return False - self.thermal[name] = temp - - def capture_input_wakeup_count(self): - """Capture wakeup count for input related devices""" - - def get_wakeup_count(device): - """Get the wakeup count for a device""" - p = os.path.join(device.sys_path, "power", "wakeup") - if not os.path.exists(p): - return None - p = os.path.join(device.sys_path, "power", "wakeup_count") - if not os.path.exists(p): - return None - return read_file(p) - - wakeup_count = {} - for device in self.pyudev.list_devices(subsystem="input"): - count = get_wakeup_count(device) - if count is not None: - wakeup_count[device.sys_path] = count - continue - # iterate parents until finding one with a wakeup count - # or no more parents - parent = device.parent - while parent is not None: - count = get_wakeup_count(parent) - if count is not None: - wakeup_count[parent.sys_path] = count - break - parent = parent.parent - - # diff the count - for device, count in wakeup_count.items(): - if device not in self.wakeup_count: - continue - if self.wakeup_count[device] == count: - continue - self.db.record_debug( - f"Woke up from input source {device} ({self.wakeup_count[device]}->{count})", - ) - self.wakeup_count = wakeup_count - - def capture_hw_sleep(self) -> bool: - """Check for hardware sleep state""" - p = os.path.join("/", "sys", "power", "suspend_stats", "last_hw_sleep") - if os.path.exists(p): - self.hw_sleep_duration = int(read_file(p)) / 10**6 - - smu_fw_info_path = os.path.join("/", "sys", "kernel", "debug", "amd_pmc", "smu_fw_info") - if os.path.exists(smu_fw_info_path): - self.db.record_debug_file(smu_fw_info_path) - - if not os.path.exists(p) and not self.hw_sleep_duration: - try: - val = read_file(smu_fw_info_path) - for line in val.split("\n"): - if "Last S0i3 Status" in line: - continue - if "Time (in us) in S0i3" in line: - self.hw_sleep_duration = int(line.split(":")[1]) / 10**6 - except PermissionError: - if self.lockdown: - self.db.record_cycle_data( - "Unable to gather hardware sleep data with lockdown engaged", - "🚦", - ) - else: - self.db.record_cycle_data( - "Failed to read hardware sleep data", "🚦" - ) - return False - except FileNotFoundError: - self.db.record_debug(f"HW sleep statistics file {smu_fw_info_path} is missing") - if not self.hw_sleep_duration: - self.db.record_cycle_data("Did not reach hardware sleep state", "❌") - return self.hw_sleep_duration > 0 - - def capture_command_line(self): - """Capture the kernel command line to debug""" - self.db.record_debug(f"/proc/cmdline: {get_kernel_command_line()}") - - def _analyze_kernel_log_line(self, line, priority): - bios_args = sscanf_bios_args(line) - if bios_args: - if isinstance(bios_args, str): - line = bios_args - priority = 7 - else: - return - elif "Timekeeping suspended for" in line: - self.cycle_count += 1 - for f in line.split(): - try: - self.kernel_duration += float(f) - except ValueError: - pass - elif "Successfully transitioned to state" in line: - self.upep = True - if "Successfully transitioned to state lps0 ms entry" in line: - self.upep_microsoft = True - elif "_DSM function" in line: - self.upep = True - if "_DSM function 7" in line: - self.upep_microsoft = True - elif "Last suspend in deepest state for" in line: - for f in line.split(): - if not f.endswith("us"): - continue - try: - self.hw_sleep_duration += float(f.strip("us")) / 10**6 - except ValueError: - pass - elif "Triggering wakeup from IRQ" in line: - irq = int(line.split()[-1]) - if irq and irq not in self.wakeup_irqs: - self.wakeup_irqs += [irq] - elif "SMU idlemask s0i3" in line: - self.idle_masks += [line.split()[-1]] - elif "ACPI BIOS Error" in line or "ACPI Error" in line: - self.acpi_errors += [line] - elif re.search("GPIO.*is active", line): - self.active_gpios += re.findall( - r"\d+", re.search("GPIO.*is active", line).group() - ) - elif Headers.Irq1Workaround in line: - self.irq1_workaround = True - # AMD-Vi: Event logged [IO_PAGE_FAULT device=0000:00:0c.0 domain=0x0000 address=0x7e800000 flags=0x0050] - elif "Event logged [IO_PAGE_FAULT" in line: - # get the device from string - device = re.search(r"device=(.*?) domain", line) - if device: - device = device.group(1) - if device not in self.page_faults: - self.page_faults += [device] - - # evmisc-0132 ev_queue_notify_reques: Dispatching Notify on [UBTC] (Device) Value 0x80 (Status Change) Node 0000000080144eee - if "Dispatching Notify on" in line: - # add device without the [] to notify_devices if it's not already there - device = re.search(r"\[(.*?)\]", line) - if device: - device = device.group(1) - if device not in self.notify_devices: - self.notify_devices += [device] - priority = 7 - - self.db.record_debug(line, priority) - - def analyze_kernel_log(self): - """Analyze one of the lines from the kernel log""" - self.kernel_log.process_callback(self._analyze_kernel_log_line) - - if self.cycle_count: - self.db.record_cycle_data( - f"Hardware sleep cycle count: {self.cycle_count}", - "💤", - ) - if self.wakeup_irqs: - if 1 in self.wakeup_irqs and soc_needs_irq1_wa( - self.cpu_family, self.cpu_model, self.smu_version - ): - if self.irq1_workaround: - self.db.record_cycle_data( - "Kernel workaround for IRQ1 issue utilized", "○" - ) - else: - self.db.record_cycle_data("IRQ1 found during wakeup", "🚦") - self.failures += [Irq1Workaround()] - if self.idle_masks: - bit_changed = 0 - for i, mask_i in enumerate(self.idle_masks): - for _j, mask_j in enumerate(self.idle_masks[i:], start=i): - if mask_i != mask_j: - bit_changed = bit_changed | (int(mask_i, 16) & ~int(mask_j, 16)) - if bit_changed: - for bit in range(0, 31): - if bit_changed & BIT(bit): - self.db.record_debug( - f"Idle mask bit {bit} (0x{BIT(bit):x}) changed during suspend", - ) - if self.upep: - if self.upep_microsoft: - self.db.record_debug("Used Microsoft uPEP GUID in LPS0 _DSM") - else: - self.db.record_debug("Used AMD uPEP GUID in LPS0 _DSM") - if self.acpi_errors: - self.db.record_cycle_data("ACPI BIOS errors found", "❌") - self.failures += [AcpiBiosError(self.acpi_errors)] - if self.page_faults: - self.db.record_cycle_data("Page faults found", "❌") - self.failures += [IommuPageFault(self.page_faults)] - if self.notify_devices: - self.db.record_cycle_data( - f"Notify devices {self.notify_devices} found during suspend", "💤" - ) - - def analyze_duration(self, t0, t1, requested, kernel, hw): - """Analyze the duration of the last cycle""" - userspace_duration = t1 - t0 - min_suspend_duration = timedelta(seconds=requested * 0.9) - expected_wake_time = t0 + min_suspend_duration - if t1 > expected_wake_time: - print_color( - f"Userspace suspended for {userspace_duration}", - "✅", - ) - else: - print_color( - f"Userspace suspended for {userspace_duration} (< minimum expected {min_suspend_duration})", - "❌", - ) - self.failures += [SpuriousWakeup(requested, userspace_duration)] - percent = float(kernel) / userspace_duration.total_seconds() - print_color( - f"Kernel suspended for total of {timedelta(seconds=kernel)} ({percent:.2%})", - "✅", - ) - - percent = float(hw / userspace_duration.total_seconds()) - if userspace_duration.total_seconds() >= 60: - if percent > 0.9: - symbol = "✅" - else: - symbol = "❌" - self.failures += [ - LowHardwareSleepResidency(userspace_duration, percent) - ] - else: - symbol = "✅" - print_color( - "In a hardware sleep state for {time} {percent_msg}".format( - time=timedelta(seconds=hw), - percent_msg="" if not percent else "({:.2%})".format(percent), - ), - symbol, - ) - - def post(self): - """Post-process the suspend test results""" - self.cycle_count = 0 - self.upep = False - self.upep_microsoft = False - self.wakeup_irqs = [] - self.idle_masks = [] - self.acpi_errors = [] - self.active_gpios = [] - self.notify_devices = [] - self.page_faults = [] - self.irq1_workaround = False - - checks = [ - self.capture_wakeup_irq_data, - self.analyze_kernel_log, - self.check_gpes, - self.capture_lid, - self.check_rtc_cmos, - self.capture_hw_sleep, - self.capture_battery, - self.capture_power_rails, - self.capture_amdgpu_ips_status, - self.capture_thermal, - self.capture_input_wakeup_count, - self.acpica.restore, - ] - for check in checks: - check() - self.db.record_cycle( - self.requested_duration, - ",".join(str(gpio) for gpio in self.active_gpios), - ",".join(str(irq) for irq in self.wakeup_irqs), - int(self.kernel_duration), - int(self.hw_sleep_duration), - ) - - def prep(self): - """Prepare the system for suspend testing""" - self.last_suspend = datetime.now() - self.kernel_log.seek_tail(self.last_suspend) - self.db.start_cycle(self.last_suspend) - self.kernel_duration = 0 - self.hw_sleep_duration = 0 - self.capture_battery() - self.capture_power_rails() - self.check_gpes() - self.capture_lid() - self.capture_command_line() - self.capture_wake_sources() - self.capture_running_compositors() - self.capture_power_profile() - self.capture_amdgpu_ips_status() - self.capture_thermal() - self.capture_input_wakeup_count() - if self.bios_debug: - self.acpica.trace_bios() - else: - self.acpica.trace_notify() - self.db.record_cycle() - - def program_wakealarm(self): - """Program the RTC wakealarm to wake the system after the requested duration""" - wakealarm = None - for device in self.pyudev.list_devices(subsystem="rtc"): - target = os.path.join(device.sys_path, "wakealarm") - if os.path.exists(target): - wakealarm = target - break - if wakealarm: - with open(wakealarm, "w", encoding="utf-8") as w: - w.write("0") - with open(wakealarm, "w", encoding="utf-8") as w: - w.write("+%s\n" % self.requested_duration) - else: - print_color("No RTC device found, please manually wake system", "🚦") - - def toggle_nvidia(self, value): - """Write to the NVIDIA suspend interface""" - p = os.path.join("/", "proc", "driver", "nvidia", "suspend") - if not os.path.exists(p): - return True - fd = os.open(p, os.O_WRONLY | os.O_SYNC) - try: - os.write(fd, value) - except OSError as e: - self.db.record_cycle_data(f"Failed to set {value} in NVIDIA {e}", "❌") - return False - finally: - os.close(fd) - self.db.record_debug(f"Wrote {value} to NVIDIA driver") - return True - - @pm_debugging - def suspend_system(self): - """Suspend the system using the dbus or sysfs interface""" - - def get_wakeup_count(): - """Get the wakeup count""" - p = os.path.join("/", "sys", "power", "wakeup_count") - if not os.path.exists(p): - return 0 - try: - with open(p, "r", encoding="utf-8") as r: - return int(r.read()) - except OSError: - return 0 - - if self.logind: - try: - import dbus - - bus = dbus.SystemBus() - obj = bus.get_object( - "org.freedesktop.login1", "/org/freedesktop/login1" - ) - intf = dbus.Interface(obj, "org.freedesktop.login1.Manager") - propf = dbus.Interface(obj, "org.freedesktop.DBus.Properties") - if intf.CanSuspend() != "yes": - self.db.record_cycle_data("Unable to suspend", "❌") - return False - intf.Suspend(True) - while propf.Get("org.freedesktop.login1.Manager", "PreparingForSleep"): - time.sleep(1) - return True - except dbus.exceptions.DBusException as e: - self.db.record_cycle_data( - f"Unable to communicate with logind: {e}", "❌" - ) - return False - except ImportError: - self.db.record_cycle_data("Missing dbus", "❌") - return False - else: - if not self.toggle_nvidia(b"suspend"): - return False - old = get_wakeup_count() - p = os.path.join("/", "sys", "power", "state") - fd = os.open(p, os.O_WRONLY | os.O_SYNC) - try: - os.write(fd, b"mem") - except OSError as e: - new = get_wakeup_count() - self.db.record_cycle_data( - f"Failed to set suspend state ({old} -> {new}): {e}", "❌" - ) - return False - finally: - os.close(fd) - if not self.toggle_nvidia(b"resume"): - return False - return True - - def unlock_session(self): - """Unlock the session using logind""" - if self.logind: - try: - import dbus - - bus = dbus.SystemBus() - obj = bus.get_object( - "org.freedesktop.login1", "/org/freedesktop/login1" - ) - intf = dbus.Interface(obj, "org.freedesktop.login1.Manager") - intf.UnlockSessions() - except dbus.exceptions.DBusException as e: - self.db.record_cycle_data( - f"Unable to communicate with logind: {e}", "❌" - ) - return False - return True - - def run(self, duration, count, wait, rand, logind): - """Run the suspend test""" - min_duration = 4 - if not count: - return True - - if logind: - self.logind = True - - if rand: - if duration <= min_duration: - print_color(f"Invalid max duration {duration}", "❌") - self.db.sync() - self.report_cycle() - return False - print_color( - f"Running {count} cycle random test with min duration of {min_duration}s, max duration of {duration}s and a max wait of {wait}s", - "🗣️", - ) - elif count > 1: - length = timedelta(seconds=(duration + wait) * count) - print_color( - f"Running {count} cycles (Test finish expected @ {datetime.now() + length})".format(), - "🗣️", - ) - for i in range(1, count + 1): - if rand: - self.requested_duration = random.randint(min_duration, duration) - requested_wait = random.randint(1, wait) - else: - self.requested_duration = duration - requested_wait = wait - run_countdown("Suspending system", math.ceil(requested_wait / 2)) - self.prep() - self.db.record_debug( - f"{Headers.SuspendDuration} {timedelta(seconds=self.requested_duration)}", - ) - if count > 1: - header = f"{Headers.CycleCount} {i}: " - else: - header = "" - print_color( - f"{header}Started at {self.last_suspend} (cycle finish expected @ {datetime.now() + timedelta(seconds=self.requested_duration + requested_wait)})", - "🗣️", - ) - self.program_wakealarm() - if not self.suspend_system(): - self.db.sync() - self.report_cycle() - return False - run_countdown("Collecting data", math.ceil(requested_wait / 2)) - self.post() - self.db.sync() - self.report_cycle() - self.unlock_session() - return True - - def systemd_pre_hook(self): - """Called before suspend""" - self.prep() - self.db.sync() - toggle_pm_debug(True) - - def systemd_post_hook(self): - """Called after resume""" - toggle_pm_debug(False) - t0 = self.db.get_last_cycle() - self.last_suspend = datetime.strptime(str(t0[0]), "%Y%m%d%H%M%S") - self.kernel_log.seek_tail(self.last_suspend) - self.db.start_cycle(self.last_suspend) - self.post() - self.db.sync() - - def report_cycle(self): - """Report the results of the last cycle""" - print_color(Headers.LastCycleResults, "🗣️") - - app = SleepReport( - since=self.last_suspend, - until=self.last_suspend, - fname=None, - fmt="stdout", - tool_debug=self.display_debug, - report_debug=False, - ) - app.run(inc_prereq=False) - return
diff --git a/src/amd_debug/validator/__init__.py b/src/amd_debug/validator/__init__.py new file mode 100644 index 0000000..55fa844 --- /dev/null +++ b/src/amd_debug/validator/__init__.py
@@ -0,0 +1,21 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the sleep validator for the amd-debug-tools package. +""" + +from amd_debug.validator.core import ( + SleepValidator, + pm_debugging, + soc_needs_irq1_wa, + toggle_pm_debug, +) +from amd_debug.validator_headers import Headers + +__all__ = [ + "Headers", + "SleepValidator", + "pm_debugging", + "soc_needs_irq1_wa", + "toggle_pm_debug", +]
diff --git a/src/amd_debug/validator/analysis.py b/src/amd_debug/validator/analysis.py new file mode 100644 index 0000000..217f32e --- /dev/null +++ b/src/amd_debug/validator/analysis.py
@@ -0,0 +1,187 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the analysis helpers for the sleep validator. + +These are the functions that examine the data captured during a sleep cycle +to work out what happened. +""" + +import re +from datetime import timedelta + +from amd_debug.validator_headers import Headers +from amd_debug.common import print_color, BIT +from amd_debug.kernel import sscanf_bios_args +from amd_debug.failures import ( + AcpiBiosError, + IommuPageFault, + Irq1Workaround, + LowHardwareSleepResidency, + SpuriousWakeup, +) + + +class AnalysisHelpers: + """Mixin providing the analysis helpers for the sleep validator""" + + def _analyze_kernel_log_line(self, line, priority): + bios_args = sscanf_bios_args(line) + if bios_args: + if isinstance(bios_args, str): + line = bios_args + priority = 7 + else: + return + elif "Timekeeping suspended for" in line: + self.cycle_count += 1 + for f in line.split(): + try: + self.kernel_duration += float(f) + except ValueError: + pass + elif "Successfully transitioned to state" in line: + self.upep = True + if "Successfully transitioned to state lps0 ms entry" in line: + self.upep_microsoft = True + elif "_DSM function" in line: + self.upep = True + if "_DSM function 7" in line: + self.upep_microsoft = True + elif "Last suspend in deepest state for" in line: + for f in line.split(): + if not f.endswith("us"): + continue + try: + self.hw_sleep_duration += float(f.strip("us")) / 10**6 + except ValueError: + pass + elif "Triggering wakeup from IRQ" in line: + irq = int(line.split()[-1]) + if irq and irq not in self.wakeup_irqs: + self.wakeup_irqs += [irq] + elif "SMU idlemask s0i3" in line: + self.idle_masks += [line.split()[-1]] + elif "ACPI BIOS Error" in line or "ACPI Error" in line: + self.acpi_errors += [line] + elif re.search("GPIO.*is active", line): + self.active_gpios += re.findall( + r"\d+", re.search("GPIO.*is active", line).group() + ) + elif Headers.Irq1Workaround in line: + self.irq1_workaround = True + # AMD-Vi: Event logged [IO_PAGE_FAULT device=0000:00:0c.0 domain=0x0000 address=0x7e800000 flags=0x0050] + elif "Event logged [IO_PAGE_FAULT" in line: + # get the device from string + device = re.search(r"device=(.*?) domain", line) + if device: + device = device.group(1) + if device not in self.page_faults: + self.page_faults += [device] + + # evmisc-0132 ev_queue_notify_reques: Dispatching Notify on [UBTC] (Device) Value 0x80 (Status Change) Node 0000000080144eee + if "Dispatching Notify on" in line: + # add device without the [] to notify_devices if it's not already there + device = re.search(r"\[(.*?)\]", line) + if device: + device = device.group(1) + if device not in self.notify_devices: + self.notify_devices += [device] + priority = 7 + + self.db.record_debug(line, priority) + + def analyze_kernel_log(self): + """Analyze one of the lines from the kernel log""" + self.kernel_log.process_callback(self._analyze_kernel_log_line) + + if self.cycle_count: + self.db.record_cycle_data( + f"Hardware sleep cycle count: {self.cycle_count}", + "💤", + ) + if self.wakeup_irqs: + if 1 in self.wakeup_irqs and self.needs_irq1_workaround(): + if self.irq1_workaround: + self.db.record_cycle_data( + "Kernel workaround for IRQ1 issue utilized", "○" + ) + else: + self.db.record_cycle_data("IRQ1 found during wakeup", "🚦") + self.failures += [Irq1Workaround()] + if self.idle_masks: + bit_changed = 0 + for i, mask_i in enumerate(self.idle_masks): + for _j, mask_j in enumerate(self.idle_masks[i:], start=i): + if mask_i != mask_j: + bit_changed = bit_changed | (int(mask_i, 16) & ~int(mask_j, 16)) + if bit_changed: + for bit in range(0, 31): + if bit_changed & BIT(bit): + self.db.record_debug( + f"Idle mask bit {bit} (0x{BIT(bit):x}) changed during suspend", + ) + if self.upep: + if self.upep_microsoft: + self.db.record_debug("Used Microsoft uPEP GUID in LPS0 _DSM") + else: + self.db.record_debug("Used AMD uPEP GUID in LPS0 _DSM") + if self.acpi_errors: + self.db.record_cycle_data("ACPI BIOS errors found", "❌") + self.failures += [AcpiBiosError(self.acpi_errors)] + if self.page_faults: + self.db.record_cycle_data("Page faults found", "❌") + self.failures += [IommuPageFault(self.page_faults)] + if self.notify_devices: + self.db.record_cycle_data( + f"Notify devices {self.notify_devices} found during suspend", "💤" + ) + + def needs_irq1_workaround(self) -> bool: + """Check if the platform needs the IRQ1 workaround + + This is only relevant on AMD platforms, so the base + implementation always returns False. + """ + return False + + def analyze_duration(self, t0, t1, requested, kernel, hw): + """Analyze the duration of the last cycle""" + userspace_duration = t1 - t0 + min_suspend_duration = timedelta(seconds=requested * 0.9) + expected_wake_time = t0 + min_suspend_duration + if t1 > expected_wake_time: + print_color( + f"Userspace suspended for {userspace_duration}", + "✅", + ) + else: + print_color( + f"Userspace suspended for {userspace_duration} (< minimum expected {min_suspend_duration})", + "❌", + ) + self.failures += [SpuriousWakeup(requested, userspace_duration)] + percent = float(kernel) / userspace_duration.total_seconds() + print_color( + f"Kernel suspended for total of {timedelta(seconds=kernel)} ({percent:.2%})", + "✅", + ) + + percent = float(hw / userspace_duration.total_seconds()) + if userspace_duration.total_seconds() >= 60: + if percent > 0.9: + symbol = "✅" + else: + symbol = "❌" + self.failures += [ + LowHardwareSleepResidency(userspace_duration, percent) + ] + else: + symbol = "✅" + print_color( + "In a hardware sleep state for {time} {percent_msg}".format( + time=timedelta(seconds=hw), + percent_msg="" if not percent else "({:.2%})".format(percent), + ), + symbol, + )
diff --git a/src/amd_debug/validator/capture.py b/src/amd_debug/validator/capture.py new file mode 100644 index 0000000..d1be744 --- /dev/null +++ b/src/amd_debug/validator/capture.py
@@ -0,0 +1,361 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the data capture helpers for the sleep validator. + +These are the functions that collect the state of the system before the +system suspends and after it resumes. +""" + +import glob +import os +import re +import subprocess +import time + +from amd_debug.validator_headers import Headers +from amd_debug.common import read_file +from amd_debug.kernel import get_kernel_command_line +from amd_debug.failures import RtcAlarmWrong + + +class CaptureHelpers: + """Mixin providing the data capture helpers for the sleep validator""" + + def capture_running_compositors(self): + """Capture information about known compositor processes found""" + + known_compositors = [ + "kwin_wayland", + "gnome-shell", + "cosmic-session", + "hyprland", + ] + + # Get a list of all process directories in /proc + process_dirs = glob.glob("/proc/[0-9]*") + + # Extract and print the process names + for proc_dir in process_dirs: + p = os.path.join(proc_dir, "exe") + if not os.path.exists(p): + continue + exe = os.path.basename(os.readlink(p)).split()[0] + if exe in known_compositors: + self.db.record_debug(f"{exe} compositor is running") + + def capture_power_profile(self): + """Capture power profile information""" + cmd = ["/usr/bin/powerprofilesctl"] + if os.path.exists(cmd[0]): + try: + output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode( + "utf-8" + ) + self.db.record_debug("Power Profiles:") + lines = output.split("\n") + lines = [line for line in lines if line.strip()] + for line in lines: + prefix = "│ " if line != lines[-1] else "└─" + self.db.record_debug(f"{prefix}{line.strip()}") + except subprocess.CalledProcessError as e: + self.db.record_debug("Failed to run powerprofilesctl: %s", e.output) + + def capture_battery(self): + """Capture battery energy levels""" + for name in self.batteries.get_batteries(): + energy = self.batteries.get_energy(name) + full = self.batteries.get_energy_full(name) + self.db.record_debug(f"{name} energy level is {energy} µWh") + self.db.record_battery_energy(name, energy, full, "W") + + def capture_power_rails(self): + """Capture power rail energy levels""" + if not self.power_rails.rails: + return # No IIO power rails detected + + for rail in self.power_rails.rails: + try: + energy = rail.read_energy_raw() + self.db.record_power_rail_energy(rail.label, energy, rail.energy_scale) + except OSError as e: + self.db.record_debug(f"Failed to read {rail.label}: {e}", priority=1) + + def check_rtc_cmos(self): + """Check if the RTC is configured to use ACPI alarm""" + p = os.path.join( + "/", "sys", "module", "rtc_cmos", "parameters", "use_acpi_alarm" + ) + if not os.path.exists(p): + return + val = read_file(p) + if val == "N": + self.db.record_cycle_data( + "`rtc_cmos` not configured to use ACPI alarm", "🚦" + ) + self.failures += [RtcAlarmWrong()] + + def check_gpes(self): + """Capture general purpose event count""" + base = os.path.join("/", "sys", "firmware", "acpi", "interrupts") + for root, _dirs, files in os.walk(base, topdown=False): + for fname in files: + if not fname.startswith("gpe") or fname == "gpe_all": + continue + target = os.path.join(root, fname) + val = 0 + with open(target, "r", encoding="utf-8") as r: + val = int(r.read().split()[0]) + if fname in self.gpes and self.gpes[fname] != val: + self.db.record_debug( + f"{fname} increased from {self.gpes[fname]} to {val}", + ) + self.gpes[fname] = val + + def capture_wake_sources(self): + """Capture possible wakeup sources""" + + def get_input_sibling_name(pyudev, parent): + """Get the name of the input sibling""" + for inp in pyudev.list_devices(subsystem="input", parent=parent): + if not "NAME" in inp.properties: + continue + return inp.properties["NAME"] + return "" + + devices = [] + for wake_dev in self.pyudev.list_devices(subsystem="wakeup"): + p = os.path.join(wake_dev.sys_path, "device", "power", "wakeup") + if not os.path.exists(p): + continue + wake_en = read_file(p) + name = "" + sys_name = wake_dev.sys_path + # determine the type of device it hangs off of + acpi = wake_dev.find_parent(subsystem="acpi") + serio = wake_dev.find_parent(subsystem="serio") + rtc = wake_dev.find_parent(subsystem="rtc") + pci = wake_dev.find_parent(subsystem="pci") + mhi = wake_dev.find_parent(subsystem="mhi") + pnp = wake_dev.find_parent(subsystem="pnp") + hid = wake_dev.find_parent(subsystem="hid") + thunderbolt_device = wake_dev.find_parent( + subsystem="thunderbolt", device_type="thunderbolt_device" + ) + thunderbolt_domain = wake_dev.find_parent( + subsystem="thunderbolt", device_type="thunderbolt_domain" + ) + i2c = wake_dev.find_parent(subsystem="i2c") + if i2c is not None: + sys_name = i2c.sys_name + name = get_input_sibling_name(self.pyudev, i2c) + elif thunderbolt_device is not None: + if "USB4_TYPE" in thunderbolt_device.properties: + name = ( + f'USB4 {thunderbolt_device.properties["USB4_TYPE"]} controller' + ) + sys_name = thunderbolt_device.sys_name + elif thunderbolt_domain is not None: + name = "Thunderbolt domain" + sys_name = thunderbolt_domain.sys_name + elif serio is not None: + sys_name = serio.sys_name + name = get_input_sibling_name(self.pyudev, serio) + elif rtc is not None: + sys_name = rtc.sys_name + for _parent in self.pyudev.list_devices( + subsystem="platform", parent=rtc, DRIVER="alarmtimer" + ): + name = "Real Time Clock alarm timer" + break + elif mhi is not None: + sys_name = mhi.sys_name + name = "Mobile Broadband host interface" + elif hid is not None: + name = hid.properties["HID_NAME"] + sys_name = hid.sys_name + elif pci is not None: + sys_name = pci.sys_name + if ( + "ID_PCI_SUBCLASS_FROM_DATABASE" in pci.properties + and "ID_VENDOR_FROM_DATABASE" in pci.properties + ): + name = f'{pci.properties["ID_VENDOR_FROM_DATABASE"]} {pci.properties["ID_PCI_SUBCLASS_FROM_DATABASE"]}' + else: + name = f"PCI {pci.properties['PCI_CLASS']}" + elif acpi is not None: + sys_name = acpi.sys_name + if acpi.driver == "button": + for inp in self.pyudev.list_devices(subsystem="input", parent=acpi): + if not "NAME" in inp.properties: + continue + name = f"ACPI {inp.properties['NAME']}" + break + elif acpi.driver in ["battery", "ac"]: + for ps in self.pyudev.list_devices( + subsystem="power_supply", parent=acpi + ): + if not "POWER_SUPPLY_NAME" in ps.properties: + continue + name = f"ACPI {ps.properties['POWER_SUPPLY_TYPE']}" + elif pnp is not None: + name = "Plug-n-play" + if pnp.driver == "rtc_cmos": + name = f"{name} Real Time Clock" + sys_name = pnp.sys_name + + name = name.replace('"', "") + devices.append(f"{name}|{sys_name}|{wake_en}") + devices.sort() + debug_str = "Wakeup Source|Linux Device|Status\n" + for dev in devices: + debug_str += f"{dev}\n" + self.db.record_debug(debug_str) + + def capture_lid(self) -> None: + """Capture lid state""" + p = os.path.join("/", "proc", "acpi", "button", "lid") + for root, _dirs, files in os.walk(p): + for fname in files: + p = os.path.join(root, fname) + state = read_file(p).split(":")[1].strip() + self.db.record_debug(f"ACPI Lid ({p}): {state}") + + def capture_wakeup_irq_data(self) -> bool: + """Capture the wakeup IRQ to the log""" + p = os.path.join("/", "sys", "power", "pm_wakeup_irq") + try: + n = read_file(p) + p = os.path.join("/", "sys", "kernel", "irq", n) + chip_name = read_file(os.path.join(p, "chip_name")) + name = read_file(os.path.join(p, "name")) + hw = read_file(os.path.join(p, "hwirq")) + actions = read_file(os.path.join(p, "actions")) + message = f"{Headers.WokeFromIrq} {n} ({chip_name} {hw}-{name} {actions})" + self.db.record_debug(message) + irq = int(n) + if irq and irq not in self.wakeup_irqs: + self.wakeup_irqs += [irq] + except OSError: + pass + return True + + def capture_amdgpu_ips_status(self): + """Capture the AMDGPU IPS status""" + for device in self.pyudev.list_devices(subsystem="pci", PCI_CLASS="38000"): + pci_id = device.properties.get("PCI_ID") + if not pci_id.startswith("1002"): + continue + slot = device.properties.get("PCI_SLOT_NAME") + p = os.path.join( + "/", "sys", "kernel", "debug", "dri", slot, "amdgpu_dm_ips_status" + ) + if not os.path.exists(p): + continue + self.db.record_debug("IPS status") + try: + lines = read_file(p).split("\n") + for line in lines: + prefix = "│ " if line != lines[-1] else "└─" + self.db.record_debug(f"{prefix}{line}") + except PermissionError: + if self.lockdown: + self.db.record_debug( + "Unable to gather IPS state data due to kernel lockdown." + ) + else: + self.db.record_debug("Failed to read IPS state data") + + def capture_thermal(self): + """Capture thermal zone information""" + devs = [] + for dev in self.pyudev.list_devices(subsystem="acpi", DRIVER="thermal"): + devs.append(dev) + if not devs: + return + + self.db.record_debug("Thermal zones") + for dev in devs: + prefix = "├─ " if dev != devs[-1] else "└─" + detail_prefix = "│ \t" if dev != devs[-1] else " \t" + name = os.path.basename(dev.device_path) + p = os.path.join(dev.sys_path, "thermal_zone") + temp = int(read_file(os.path.join(p, "temp"))) / 1000 + + self.db.record_debug(f"{prefix}{name}") + if name not in self.thermal: + self.db.record_debug(f"{detail_prefix} temp: {temp}°C") + else: + self.db.record_debug( + f"{detail_prefix} {self.thermal[name]}°C -> {temp}°C" + ) + + # handle all trip points + trip_count = 0 + for f in os.listdir(p): + if "trip_point" not in f: + continue + if "temp" not in f: + continue + trip_count = trip_count + 1 + + for i in range(0, trip_count): + f = os.path.join(p, f"trip_point_{i}_type") + trip_type = read_file(f) + f = os.path.join(p, f"trip_point_{i}_temp") + trip = int(read_file(f)) / 1000 + + if name not in self.thermal: + self.db.record_debug(f"{detail_prefix} {trip_type} trip: {trip}°C") + + if temp > trip: + self.db.record_prereq( + f"Thermal zone {name} past trip point {trip_type}: {trip}°C", + "🌡️", + ) + return False + self.thermal[name] = temp + + def capture_input_wakeup_count(self): + """Capture wakeup count for input related devices""" + + def get_wakeup_count(device): + """Get the wakeup count for a device""" + p = os.path.join(device.sys_path, "power", "wakeup") + if not os.path.exists(p): + return None + p = os.path.join(device.sys_path, "power", "wakeup_count") + if not os.path.exists(p): + return None + return read_file(p) + + wakeup_count = {} + for device in self.pyudev.list_devices(subsystem="input"): + count = get_wakeup_count(device) + if count is not None: + wakeup_count[device.sys_path] = count + continue + # iterate parents until finding one with a wakeup count + # or no more parents + parent = device.parent + while parent is not None: + count = get_wakeup_count(parent) + if count is not None: + wakeup_count[parent.sys_path] = count + break + parent = parent.parent + + # diff the count + for device, count in wakeup_count.items(): + if device not in self.wakeup_count: + continue + if self.wakeup_count[device] == count: + continue + self.db.record_debug( + f"Woke up from input source {device} ({self.wakeup_count[device]}->{count})", + ) + self.wakeup_count = wakeup_count + + def capture_command_line(self): + """Capture the kernel command line to debug""" + self.db.record_debug(f"/proc/cmdline: {get_kernel_command_line()}")
diff --git a/src/amd_debug/validator/core.py b/src/amd_debug/validator/core.py new file mode 100644 index 0000000..61fafd2 --- /dev/null +++ b/src/amd_debug/validator/core.py
@@ -0,0 +1,256 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the sleep validator. + +The validator captures the state of the system before it suspends and after +it resumes, and then analyses that data to work out what happened. +""" + +import os +import re +from datetime import datetime + +from packaging import version +from pyudev import Context + +from amd_debug.sleep_report import SleepReport +from amd_debug.database import SleepDatabase +from amd_debug.battery import Batteries +from amd_debug.power_rails import PowerRails +from amd_debug.acpi import AcpicaTracer +from amd_debug.common import ( + read_file, + check_lockdown, + print_color, + AmdTool, +) +from amd_debug.kernel import get_kernel_log +from amd_debug.failures import ( + IommuPageFault, + RtcAlarmWrong, +) +from amd_debug.validator.capture import CaptureHelpers +from amd_debug.validator.analysis import AnalysisHelpers +from amd_debug.validator.suspend import SuspendHelpers +from amd_debug.validator_headers import Headers + + +def soc_needs_irq1_wa(family, model, smu_version): + """Check if the SoC needs the IRQ1 workaround""" + if family == 0x17: + if model in [0x68, 0x60]: + return True + elif family == 0x19: + if model == 0x50: + return version.parse(smu_version) < version.parse("64.66.0") + return False + + +def toggle_pm_debug(enable): + """Enable or disable pm_debug_messages""" + pm_debug_messages = os.path.join("/", "sys", "power", "pm_debug_messages") + with open(pm_debug_messages, "w", encoding="utf-8") as w: + w.write("1" if enable else "0") + + +def pm_debugging(func): + """Decorator to enable pm_debug_messages""" + + def runner(*args, **kwargs): + toggle_pm_debug(True) + ret = func(*args, **kwargs) + toggle_pm_debug(False) + + return ret + + return runner + + +class SleepValidator( + CaptureHelpers, AnalysisHelpers, SuspendHelpers, AmdTool +): + """Class to validate the sleep state""" + + def __init__(self, tool_debug, bios_debug): + log_prefix = "s2idle" if tool_debug else None + super().__init__(log_prefix) + + self.pyudev = Context() + + self.kernel_log = get_kernel_log() + self.db = SleepDatabase() + self.batteries = Batteries() + self.power_rails = PowerRails() + self.acpica = AcpicaTracer() + self.bios_debug = bios_debug + self.cpu_family = "" + self.cpu_model = "" + self.cpu_model_string = "" + self.smu_version = "" + self.smu_program = "" + self.last_suspend = datetime.now() + self.requested_duration = 0 + self.userspace_duration = 0 + self.kernel_duration = 0 + self.hw_sleep_duration = 0 + self.failures = [] + self.gpes = {} + self.display_debug = tool_debug + self.lockdown = check_lockdown() + self.logind = False + self.upep = False + self.cycle_count = 0 + self.upep_microsoft = False + self.wakeup_irqs = [] + self.idle_masks = [] + self.acpi_errors = [] + self.active_gpios = [] + self.irq1_workaround = False + self.thermal = {} + self.wakeup_count = {} + self.page_faults = [] + self.notify_devices = [] + + def needs_irq1_workaround(self) -> bool: + """Check if the platform needs the IRQ1 workaround""" + return soc_needs_irq1_wa(self.cpu_family, self.cpu_model, self.smu_version) + + def capture_hw_sleep(self) -> bool: + """Check for hardware sleep state""" + p = os.path.join("/", "sys", "power", "suspend_stats", "last_hw_sleep") + if os.path.exists(p): + self.hw_sleep_duration = int(read_file(p)) / 10**6 + + smu_fw_info_path = os.path.join( + "/", "sys", "kernel", "debug", "amd_pmc", "smu_fw_info" + ) + if os.path.exists(smu_fw_info_path): + self.db.record_debug_file(smu_fw_info_path) + + if not os.path.exists(p) and not self.hw_sleep_duration: + try: + val = read_file(p) + for line in val.split("\n"): + if "Last S0i3 Status" in line: + continue + if "Time (in us) in S0i3" in line: + self.hw_sleep_duration = int(line.split(":")[1]) / 10**6 + except PermissionError: + if self.lockdown: + self.db.record_cycle_data( + "Unable to gather hardware sleep data with lockdown engaged", + "🚦", + ) + else: + self.db.record_cycle_data( + "Failed to read hardware sleep data", "🚦" + ) + return False + except FileNotFoundError: + self.db.record_debug( + f"HW sleep statistics file {smu_fw_info_path} is missing" + ) + if not self.hw_sleep_duration: + self.db.record_cycle_data("Did not reach hardware sleep state", "❌") + return self.hw_sleep_duration > 0 + + def post(self): + """Post-process the suspend test results""" + self.cycle_count = 0 + self.upep = False + self.upep_microsoft = False + self.wakeup_irqs = [] + self.idle_masks = [] + self.acpi_errors = [] + self.active_gpios = [] + self.notify_devices = [] + self.page_faults = [] + self.irq1_workaround = False + + checks = [ + self.capture_wakeup_irq_data, + self.analyze_kernel_log, + self.check_gpes, + self.capture_lid, + self.check_rtc_cmos, + self.capture_hw_sleep, + self.capture_battery, + self.capture_power_rails, + self.capture_amdgpu_ips_status, + self.capture_thermal, + self.capture_input_wakeup_count, + self.acpica.restore, + ] + for check in checks: + check() + self.db.record_cycle( + self.requested_duration, + ",".join(str(gpio) for gpio in self.active_gpios), + ",".join(str(irq) for irq in self.wakeup_irqs), + int(self.kernel_duration), + int(self.hw_sleep_duration), + ) + + def prep(self): + """Prepare the system for suspend testing""" + self.last_suspend = datetime.now() + self.kernel_log.seek_tail(self.last_suspend) + self.db.start_cycle(self.last_suspend) + self.kernel_duration = 0 + self.hw_sleep_duration = 0 + self.capture_battery() + self.capture_power_rails() + self.check_gpes() + self.capture_lid() + self.capture_command_line() + self.capture_wake_sources() + self.capture_running_compositors() + self.capture_power_profile() + self.capture_amdgpu_ips_status() + self.capture_thermal() + self.capture_input_wakeup_count() + if self.bios_debug: + self.acpica.trace_bios() + else: + self.acpica.trace_notify() + self.db.record_cycle() + + def systemd_pre_hook(self): + """Called before suspend""" + self.prep() + self.db.sync() + toggle_pm_debug(True) + + def systemd_post_hook(self): + """Called after resume""" + toggle_pm_debug(False) + t0 = self.db.get_last_cycle() + self.last_suspend = datetime.strptime(str(t0[0]), "%Y%m%d%H%M%S") + self.kernel_log.seek_tail(self.last_suspend) + self.db.start_cycle(self.last_suspend) + self.post() + self.db.sync() + + def report_cycle(self): + """Report the results of the last cycle""" + print_color(Headers.LastCycleResults, "🗣️") + + self.analyze_duration( + self.last_suspend, + datetime.now(), + self.requested_duration, + self.kernel_duration, + self.hw_sleep_duration, + ) + + app = SleepReport( + since=self.last_suspend, + until=self.last_suspend, + fname=None, + fmt="stdout", + tool_debug=self.display_debug, + report_debug=False, + ) + app.run(inc_prereq=False) + return
diff --git a/src/amd_debug/validator/suspend.py b/src/amd_debug/validator/suspend.py new file mode 100644 index 0000000..64f7d48 --- /dev/null +++ b/src/amd_debug/validator/suspend.py
@@ -0,0 +1,195 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the suspend control helpers for the sleep validator. + +These are the functions that put the system to sleep and wake it back up. +""" + +import math +import os +import random +import time +from datetime import datetime, timedelta + +from amd_debug.validator_headers import Headers +from amd_debug.common import print_color, run_countdown + + +class SuspendHelpers: + """Mixin providing the suspend control helpers for the sleep validator""" + + def program_wakealarm(self): + """Program the RTC wakealarm to wake the system after the requested duration""" + wakealarm = None + for device in self.pyudev.list_devices(subsystem="rtc"): + target = os.path.join(device.sys_path, "wakealarm") + if os.path.exists(target): + wakealarm = target + break + if wakealarm: + with open(wakealarm, "w", encoding="utf-8") as w: + w.write("0") + with open(wakealarm, "w", encoding="utf-8") as w: + w.write("+%s\n" % self.requested_duration) + else: + print_color("No RTC device found, please manually wake system", "🚦") + + def toggle_nvidia(self, value): + """Write to the NVIDIA suspend interface + + The NVIDIA systemd units notify the driver of the suspend and + resume events themselves, so if they are enabled the tool must not + do it as well or the driver will be told about the event twice. + """ + p = os.path.join("/", "proc", "driver", "nvidia", "suspend") + if not os.path.exists(p): + return True + fd = os.open(p, os.O_WRONLY | os.O_SYNC) + try: + os.write(fd, value) + except OSError as e: + self.db.record_cycle_data(f"Failed to set {value} in NVIDIA {e}", "❌") + return False + finally: + os.close(fd) + self.db.record_debug(f"Wrote {value} to NVIDIA driver") + return True + + def suspend_system(self): + """Suspend the system using the dbus or sysfs interface""" + + def get_wakeup_count(): + """Get the wakeup count""" + p = os.path.join("/", "sys", "power", "wakeup_count") + if not os.path.exists(p): + return 0 + try: + with open(p, "r", encoding="utf-8") as r: + return int(r.read()) + except OSError: + return 0 + + if self.logind: + try: + import dbus + except ImportError: + self.db.record_cycle_data("Missing dbus", "❌") + return False + try: + bus = dbus.SystemBus() + obj = bus.get_object( + "org.freedesktop.login1", "/org/freedesktop/login1" + ) + intf = dbus.Interface(obj, "org.freedesktop.login1.Manager") + propf = dbus.Interface(obj, "org.freedesktop.DBus.Properties") + if intf.CanSuspend() != "yes": + self.db.record_cycle_data("Unable to suspend", "❌") + return False + intf.Suspend(True) + while propf.Get("org.freedesktop.login1.Manager", "PreparingForSleep"): + time.sleep(1) + return True + except dbus.exceptions.DBusException as e: + self.db.record_cycle_data( + f"Unable to communicate with logind: {e}", "❌" + ) + return False + else: + if not self.toggle_nvidia(b"suspend"): + return False + old = get_wakeup_count() + p = os.path.join("/", "sys", "power", "state") + fd = os.open(p, os.O_WRONLY | os.O_SYNC) + try: + os.write(fd, b"mem") + except OSError as e: + new = get_wakeup_count() + self.db.record_cycle_data( + f"Failed to set suspend state ({old} -> {new}): {e}", "❌" + ) + return False + finally: + os.close(fd) + if not self.toggle_nvidia(b"resume"): + return False + return True + + def unlock_session(self): + """Unlock the session using logind""" + if self.logind: + try: + import dbus + except ImportError: + self.db.record_cycle_data("Missing dbus", "❌") + return False + try: + bus = dbus.SystemBus() + obj = bus.get_object( + "org.freedesktop.login1", "/org/freedesktop/login1" + ) + intf = dbus.Interface(obj, "org.freedesktop.login1.Manager") + intf.UnlockSessions() + except dbus.exceptions.DBusException as e: + self.db.record_cycle_data( + f"Unable to communicate with logind: {e}", "❌" + ) + return False + return True + + def run(self, duration, count, wait, rand, logind): + """Run the suspend test""" + min_duration = 4 + if not count: + return True + + if logind: + self.logind = True + + if rand: + if duration <= min_duration: + print_color(f"Invalid max duration {duration}", "❌") + self.db.sync() + self.report_cycle() + return False + print_color( + f"Running {count} cycle random test with min duration of {min_duration}s, max duration of {duration}s and a max wait of {wait}s", + "🗣️", + ) + elif count > 1: + length = timedelta(seconds=(duration + wait) * count) + print_color( + f"Running {count} cycles (Test finish expected @ {datetime.now() + length})".format(), + "🗣️", + ) + for i in range(1, count + 1): + if rand: + self.requested_duration = random.randint(min_duration, duration) + requested_wait = random.randint(1, wait) + else: + self.requested_duration = duration + requested_wait = wait + run_countdown("Suspending system", math.ceil(requested_wait / 2)) + self.prep() + self.db.record_debug( + f"{Headers.SuspendDuration} {timedelta(seconds=self.requested_duration)}", + ) + if count > 1: + header = f"{Headers.CycleCount} {i}: " + else: + header = "" + print_color( + f"{header}Started at {self.last_suspend} (cycle finish expected @ {datetime.now() + timedelta(seconds=self.requested_duration + requested_wait)})", + "🗣️", + ) + self.program_wakealarm() + if not self.suspend_system(): + self.db.sync() + self.report_cycle() + return False + run_countdown("Collecting data", math.ceil(requested_wait / 2)) + self.post() + self.db.sync() + self.report_cycle() + self.unlock_session() + return True
diff --git a/src/amd_debug/validator_headers.py b/src/amd_debug/validator_headers.py new file mode 100644 index 0000000..66ef69f --- /dev/null +++ b/src/amd_debug/validator_headers.py
@@ -0,0 +1,18 @@ +# SPDX-License-Identifier: MIT + +""" +This module contains the header strings used by the sleep validator. + +These are kept in their own module so that the various helper mixins can +share them without creating circular imports. +""" + + +class Headers: + """Header strings for the debug output""" + + Irq1Workaround = "Disabling IRQ1 wakeup source to avoid platform firmware bug" + WokeFromIrq = "Woke up from IRQ" + LastCycleResults = "Results from last s2idle cycle" + CycleCount = "Suspend cycle" + SuspendDuration = "Suspend timer programmed for"
diff --git a/src/test_s2idle.py b/src/test_s2idle.py index 515bf8a..83964a3 100644 --- a/src/test_s2idle.py +++ b/src/test_s2idle.py
@@ -539,7 +539,7 @@ @patch("amd_debug.s2idle.get_validator") @patch("amd_debug.s2idle.prompt_test_arguments", side_effect=KeyboardInterrupt) @patch("amd_debug.prereq.base.SleepDatabase") - @patch("amd_debug.validator.SleepDatabase") + @patch("amd_debug.validator.core.SleepDatabase") def test_test_keyboard_interrupt( self, _mock_sleep_db_validator,
diff --git a/src/test_validator.py b/src/test_validator.py index 91037cb..7ab8f7f 100644 --- a/src/test_validator.py +++ b/src/test_validator.py
@@ -5,7 +5,7 @@ This module contains unit tests for the validator functions in the amd-debug-tools package. """ -from unittest.mock import patch, mock_open, Mock, MagicMock +from unittest.mock import patch, mock_open, Mock, MagicMock, ANY import os import logging @@ -50,7 +50,9 @@ return "Test function executed" # Mock /sys/power/pm_debug_messages existing and all ACPI existing - with patch("amd_debug.validator.open", new_callable=mock_open, read_data="0") as mock_file: + with patch( + "amd_debug.validator.core.open", new_callable=mock_open, read_data="0" + ) as mock_file: handlers = ( mock_file.return_value, mock_open(read_data="0").return_value, @@ -63,7 +65,7 @@ # Mock /sys/power/pm_debug_messages missing with patch( - "amd_debug.validator.open", side_effect=FileNotFoundError("not found") + "amd_debug.validator.core.open", side_effect=FileNotFoundError("not found") ) as mock_file: with self.assertRaises(FileNotFoundError): result = test_function() @@ -76,7 +78,7 @@ def setUpClass(cls): logging.basicConfig(filename="/dev/null", level=logging.DEBUG) - @patch("amd_debug.validator.SleepDatabase") + @patch("amd_debug.validator.core.SleepDatabase") @patch("subprocess.run") def setUp(self, _db_mock, _mock_run): """Set up a mock context for testing""" @@ -129,7 +131,9 @@ with patch( "os.path.join", return_value="/sys/module/rtc_cmos/parameters/use_acpi_alarm", - ), patch("builtins.open", mock_open(read_data="N")), patch.object( + ), patch("os.path.exists", return_value=True), patch( + "builtins.open", mock_open(read_data="N") + ), patch.object( self.validator.db, "record_cycle_data" ) as mock_record_cycle_data: self.validator.check_rtc_cmos() @@ -137,11 +141,22 @@ "`rtc_cmos` not configured to use ACPI alarm", "🚦" ) + def test_check_rtc_cmos_missing(self): + """Test check_rtc_cmos method when the parameter is missing""" + with patch( + "os.path.join", + return_value="/sys/module/rtc_cmos/parameters/use_acpi_alarm", + ), patch("os.path.exists", return_value=False), patch.object( + self.validator.db, "record_cycle_data" + ) as mock_record_cycle_data: + self.validator.check_rtc_cmos() + mock_record_cycle_data.assert_not_called() + def test_capture_wake_sources(self): """Test capture_wake_sources method""" mock_pyudev = patch.object(self.validator, "pyudev").start() mock_record_debug = patch.object(self.validator.db, "record_debug").start() - mock_read_file = patch("amd_debug.validator.read_file").start() + mock_read_file = patch("amd_debug.validator.capture.read_file").start() mock_os_path_exists = patch("os.path.exists").start() # Mock wakeup devices @@ -175,7 +190,7 @@ with patch("os.walk", return_value=[("/", [], ["lid0", "lid1"])]), patch( "os.path.join", side_effect=lambda *args: "/".join(args) ), patch( - "amd_debug.validator.read_file", + "amd_debug.validator.capture.read_file", side_effect=["state: open", "state: closed"], ), patch.object( self.validator.db, "record_debug" @@ -187,7 +202,7 @@ def test_capture_wakeup_irq_data(self): """Test capture_wakeup_irq_data method""" with patch("os.path.join", side_effect=lambda *args: "/".join(args)), patch( - "amd_debug.validator.read_file", + "amd_debug.validator.capture.read_file", side_effect=[ "123", # IRQ number "chip_name_mock", # Chip name @@ -208,7 +223,7 @@ mock_pyudev = patch.object(self.validator, "pyudev").start() mock_record_debug = patch.object(self.validator.db, "record_debug").start() mock_record_prereq = patch.object(self.validator.db, "record_prereq").start() - mock_read_file = patch("amd_debug.validator.read_file").start() + mock_read_file = patch("amd_debug.validator.capture.read_file").start() mock_os_listdir = patch("os.listdir").start() # Mock thermal devices @@ -245,7 +260,7 @@ # Mock pyudev devices mock_pyudev = patch.object(self.validator, "pyudev").start() mock_record_debug = patch.object(self.validator.db, "record_debug").start() - mock_read_file = patch("amd_debug.validator.read_file").start() + mock_read_file = patch("amd_debug.validator.capture.read_file").start() mock_os_path_exists = patch("os.path.exists").start() # Mock input devices @@ -277,8 +292,11 @@ def test_capture_hw_sleep_suspend_stats(self): """Test capture_hw_sleep stats method""" with patch( - "os.path.exists", side_effect=lambda path: "suspend_stats" in path or "smu_fw_info" in path - ), patch("amd_debug.validator.read_file", return_value="1000000"), patch.object( + "os.path.exists", + side_effect=lambda path: "suspend_stats" in path or "smu_fw_info" in path, + ), patch( + "amd_debug.validator.core.read_file", return_value="1000000" + ), patch.object( self.validator.db, "record_cycle_data" ) as mock_record_cycle_data, patch.object( self.validator.db, "record_debug_file" @@ -297,7 +315,7 @@ with patch( "os.path.exists", side_effect=lambda path: "suspend_stats" not in path ), patch( - "amd_debug.validator.read_file", + "amd_debug.validator.core.read_file", side_effect=[ "Last S0i3 Status: Success\nTime (in us) in S0i3: 2000000", # smu_fw_info content ], @@ -320,7 +338,7 @@ # Case 3: PermissionError while reading smu_fw_info with lockdown enabled self.validator.lockdown = True with patch("os.path.exists", return_value=False), patch( - "amd_debug.validator.read_file", side_effect=PermissionError + "amd_debug.validator.core.read_file", side_effect=PermissionError ), patch.object( self.validator.db, "record_cycle_data" ) as mock_record_cycle_data: @@ -335,7 +353,7 @@ # Case 4: FileNotFoundError while reading smu_fw_info self.validator.lockdown = False with patch("os.path.exists", return_value=False), patch( - "amd_debug.validator.read_file", side_effect=FileNotFoundError + "amd_debug.validator.core.read_file", side_effect=FileNotFoundError ), patch.object(self.validator.db, "record_debug") as mock_record: result = self.validator.capture_hw_sleep() self.assertFalse(result) @@ -348,7 +366,7 @@ # Mock pyudev devices mock_pyudev = patch.object(self.validator, "pyudev").start() mock_record_debug = patch.object(self.validator.db, "record_debug").start() - mock_read_file = patch("amd_debug.validator.read_file").start() + mock_read_file = patch("amd_debug.validator.capture.read_file").start() mock_os_path_exists = patch("os.path.exists").start() # Mock PCI devices @@ -437,7 +455,7 @@ def test_prep(self): """Test prep method""" - with patch("amd_debug.validator.datetime") as mock_datetime, patch.object( + with patch("amd_debug.validator.core.datetime") as mock_datetime, patch.object( self.validator.kernel_log, "seek_tail" ) as mock_seek_tail, patch.object( self.validator.db, "start_cycle" @@ -605,7 +623,7 @@ # Mock pyudev devices mock_pyudev = patch.object(self.validator, "pyudev").start() _mock_record_debug = patch.object(self.validator.db, "record_debug").start() - mock_print_color = patch("amd_debug.validator.print_color").start() + mock_print_color = patch("amd_debug.validator.suspend.print_color").start() mock_open_file = patch("builtins.open", mock_open()).start() # Case 1: RTC device exists @@ -635,9 +653,12 @@ # Stop patches patch.stopall() - @patch("amd_debug.validator.SleepReport") - @patch("amd_debug.validator.print_color") - def test_report_cycle(self, mock_print_color, mock_sleep_report): + @patch.object(SleepValidator, "analyze_duration") + @patch("amd_debug.validator.core.SleepReport") + @patch("amd_debug.validator.core.print_color") + def test_report_cycle( + self, mock_print_color, mock_sleep_report, mock_analyze_duration + ): """Test report_cycle method""" # Mock SleepReport instance mock_report_instance = mock_sleep_report.return_value @@ -653,6 +674,15 @@ # Assert print_color was called with correct arguments mock_print_color.assert_called_once_with("Results from last s2idle cycle", "🗣️") + # Assert the duration analysis ran with the cycle data + mock_analyze_duration.assert_called_once_with( + "mocked_last_suspend", + ANY, + self.validator.requested_duration, + self.validator.kernel_duration, + self.validator.hw_sleep_duration, + ) + # Assert SleepReport was instantiated with correct arguments mock_sleep_report.assert_called_once_with( since="mocked_last_suspend", @@ -666,16 +696,16 @@ # Assert run method of SleepReport was called mock_report_instance.run.assert_called_once_with(inc_prereq=False) - @patch("amd_debug.validator.run_countdown") - @patch("amd_debug.validator.random.randint") - @patch("amd_debug.validator.datetime") + @patch("amd_debug.validator.suspend.run_countdown") + @patch("amd_debug.validator.suspend.random.randint") + @patch("amd_debug.validator.suspend.datetime") @patch.object(SleepValidator, "prep") @patch.object(SleepValidator, "program_wakealarm") @patch.object(SleepValidator, "suspend_system") @patch.object(SleepValidator, "post") @patch.object(SleepValidator, "unlock_session") @patch.object(SleepValidator, "report_cycle") - @patch("amd_debug.validator.print_color") + @patch("amd_debug.validator.suspend.print_color") def test_run( self, _mock_print_color, @@ -910,11 +940,11 @@ def test_toggle_pm_debug(self): """toggle_pm_debug opens and writes '1' or '0'""" m = mock_open() - with patch("amd_debug.validator.open", m, create=True): + with patch("amd_debug.validator.core.open", m, create=True): toggle_pm_debug(True) m().write.assert_called_with("1") m = mock_open() - with patch("amd_debug.validator.open", m, create=True): + with patch("amd_debug.validator.core.open", m, create=True): toggle_pm_debug(False) m().write.assert_called_with("0") @@ -965,7 +995,7 @@ with patch( "os.walk", return_value=[("/sys/firmware/acpi/interrupts", [], ["gpe01", "gpe_all", "irq"])], - ), patch("amd_debug.validator.open", m, create=True), patch.object( + ), patch("amd_debug.validator.capture.open", m, create=True), patch.object( self.validator.db, "record_debug" ) as mock_record: self.validator.check_gpes() @@ -976,7 +1006,7 @@ def test_capture_wakeup_irq_data_oserror(self): """capture_wakeup_irq_data silently handles OSError""" with patch( - "amd_debug.validator.read_file", side_effect=OSError("no irq") + "amd_debug.validator.capture.read_file", side_effect=OSError("no irq") ), patch.object(self.validator.db, "record_debug") as mock_record: self.assertTrue(self.validator.capture_wakeup_irq_data()) mock_record.assert_not_called() @@ -996,7 +1026,7 @@ ) with patch.object(self.validator.pyudev, "list_devices", return_value=[dev]), \ patch( - "amd_debug.validator.read_file", + "amd_debug.validator.capture.read_file", side_effect=["90000", "critical", "50000"], ), \ patch("os.listdir", return_value=["trip_point_0_type", "trip_point_0_temp"]), \ @@ -1019,7 +1049,7 @@ with patch.object( self.validator.pyudev, "list_devices", return_value=[child] ), patch("os.path.exists", side_effect=_exists), patch( - "amd_debug.validator.read_file", return_value="7" + "amd_debug.validator.capture.read_file", return_value="7" ): self.validator.capture_input_wakeup_count() self.assertEqual(self.validator.wakeup_count, {"/sys/devices/usb1": "7"}) @@ -1031,7 +1061,7 @@ with patch.object( self.validator.pyudev, "list_devices", return_value=[child] ), patch("os.path.exists", return_value=True), patch( - "amd_debug.validator.read_file", return_value="5" + "amd_debug.validator.capture.read_file", return_value="5" ), patch.object(self.validator.db, "record_debug") as mock_record: self.validator.wakeup_count = {"/sys/devices/input0": "5"} self.validator.capture_input_wakeup_count() @@ -1040,7 +1070,7 @@ def test_capture_command_line(self): """capture_command_line records the kernel command line""" with patch( - "amd_debug.validator.get_kernel_command_line", return_value="quiet x=1" + "amd_debug.validator.capture.get_kernel_command_line", return_value="quiet x=1" ), patch.object(self.validator.db, "record_debug") as mock_record: self.validator.capture_command_line() mock_record.assert_called_once_with("/proc/cmdline: quiet x=1") @@ -1048,7 +1078,7 @@ def test_analyze_kernel_log_line_bios_returns_early(self): """sscanf_bios_args returning True (no string) short-circuits debug log""" with patch( - "amd_debug.validator.sscanf_bios_args", return_value=True + "amd_debug.validator.analysis.sscanf_bios_args", return_value=True ), patch.object(self.validator.db, "record_debug") as mock_record: # pylint: disable=protected-access self.validator._analyze_kernel_log_line("ex_trace_point: stuff", 6) @@ -1138,7 +1168,7 @@ self.validator.analyze_kernel_log() self.assertEqual(len(self.validator.failures), before + 1) - @patch("amd_debug.validator.print_color") + @patch("amd_debug.validator.analysis.print_color") def test_analyze_duration_short_success(self, mock_print): """Userspace duration above minimum, short cycle skips hw% check""" t0 = datetime(2025, 1, 1, 0, 0, 0) @@ -1149,7 +1179,7 @@ self.assertEqual(self.validator.failures, []) self.assertTrue(mock_print.called) - @patch("amd_debug.validator.print_color") + @patch("amd_debug.validator.analysis.print_color") def test_analyze_duration_spurious(self, _mock_print): """Userspace woke too early -> SpuriousWakeup recorded""" from amd_debug.failures import SpuriousWakeup @@ -1161,7 +1191,7 @@ any(isinstance(f, SpuriousWakeup) for f in self.validator.failures) ) - @patch("amd_debug.validator.print_color") + @patch("amd_debug.validator.analysis.print_color") def test_analyze_duration_low_hw_residency(self, _mock_print): """Long cycle with low hw% -> LowHardwareSleepResidency recorded""" from amd_debug.failures import LowHardwareSleepResidency @@ -1186,7 +1216,7 @@ with patch.object(self.validator, "prep") as mock_prep, patch.object( self.validator.db, "sync" ) as mock_sync, patch( - "amd_debug.validator.toggle_pm_debug" + "amd_debug.validator.core.toggle_pm_debug" ) as mock_toggle: self.validator.systemd_pre_hook() mock_prep.assert_called_once() @@ -1204,7 +1234,7 @@ ) as mock_start_cycle, patch.object( self.validator.kernel_log, "seek_tail" ) as mock_seek_tail, patch( - "amd_debug.validator.toggle_pm_debug" + "amd_debug.validator.core.toggle_pm_debug" ) as mock_toggle: self.validator.systemd_post_hook() mock_toggle.assert_called_once_with(False)