diff --git a/Documentation/ABI/testing/sysfs-driver-aurora-gpu-cooling b/Documentation/ABI/testing/sysfs-driver-aurora-gpu-cooling new file mode 100644 index 0000000000000..5301191cc341b --- /dev/null +++ b/Documentation/ABI/testing/sysfs-driver-aurora-gpu-cooling @@ -0,0 +1,20 @@ +What: /sys/devices/platform/.../gpu_power_ceiling +Date: November 2026 +Contact: Asahi Linux contributors +Description: + Read-only diagnostics for the admitted G16S/G17P absolute-power + actuator. One key/value pair per line: + + requested_state: thermal cooling state, 0..100. + requested_ceiling_mw: minimum of all retained requester ceilings. + applied_ceiling_mw: last completed host shared-memory publication. + provisional_floor_mw: 25 percent of the initialized maximum, + rounded down, but never zero. Pending hardware qualification. + achieved_ceiling_mw: unsupported; not inferred from a nominal OPP. + + Applied is a host publication, not firmware acknowledgement or + measured GPU power. The debugfs asahi--power/ceiling + file also reports separate RegionC/PPM readbacks, initialized max, + PPM enable and the thermal/fast-die/system/manual request slots. + State N requests max(25, 100 - N) percent of initialized power. + Critical shutdown never relies on the provisional floor. diff --git a/Documentation/devicetree/bindings/gpu/apple,agx.yaml b/Documentation/devicetree/bindings/gpu/apple,agx.yaml index 7794c0e13b939..4cacd38490c8f 100644 --- a/Documentation/devicetree/bindings/gpu/apple,agx.yaml +++ b/Documentation/devicetree/bindings/gpu/apple,agx.yaml @@ -136,6 +136,16 @@ properties: $ref: /schemas/types.yaml#/definitions/phandle description: PMP firmware provider owning the GPU power vote and telemetry + "#cooling-cells": + const: 2 + description: | + GPU firmware absolute-power ceiling. State N requests (100 - N) + percent of initialized maximum power, for N in 0..100, bounded below + by a provisional nonzero minimum until hardware qualifies the low end. + A firmware layout without a live power state leaves the GPU without + this cooling device. Other policy owners may impose a stricter + ceiling than the thermal framework requests. + operating-points-v2: true apple,csafr-min-sram-microvolt: diff --git a/Documentation/gpu/asahi-gpu-thermal.rst b/Documentation/gpu/asahi-gpu-thermal.rst new file mode 100644 index 0000000000000..c71021626a173 --- /dev/null +++ b/Documentation/gpu/asahi-gpu-thermal.rst @@ -0,0 +1,206 @@ +.. SPDX-License-Identifier: GPL-2.0-only OR MIT + +GPU thermal integration and qualification +========================================= + +Live power owner +---------------- + +G17P/T8140 and G16S/T604x share the ``g17`` backend. The admitted live +actuator publishes an absolute ``u32`` milliwatt ceiling to the separately +allocated ``RegionC::max_power_mw`` at +0x84 for G17P 26A428 and G16S 25G83. +These are firmware fields, not offsets in a host service object. The obsolete +host-object mirror model has been removed. G16S 26A428 has a distinct typed ++0x88 prefix but no admitted initialization graph or live actuator. V25F84 +also has no live-power admission. Never reuse the common field for either. + +``PowerState::ppm_enabled`` (+0x128) and ``ppm_target_mw`` (+0x12c) are +separate typed fields in another object. The owner retains the initialized +PPM budget and bounds its published target by the composed ceiling. It never +aliases the RegionC maximum with the PPM target, a percent, an OPP, a PMP vote +or the performance effort floor. A zero/uninitialized PPM budget uses the +initialized RegionC maximum; a zero RegionC maximum rejects registration. +G16S uses the initialized per-chip maximum, not the zero placeholder in its +static configuration. + +A dedicated mutex serializes thermal, fast-die host-policy, system-budget +and manual request slots and their publications. The thermal framework +aggregates zone demands by maximum cooling state. The owner takes the minimum +of all absolute requests, so one requester relaxing cannot lift another's +ceiling. All future host budget/manual producers must use this owner rather +than write the fields directly. The firmware fast-die limiter operates +independently and is not replaced by the host fast-die request slot. + +State N requests ``max(25, 100 - N)`` percent of the initialized maximum, +rounded down in milliwatts, with a minimum of one milliwatt for tiny test +inputs. The 25 percent floor is **provisional**, not a qualified board minimum +or a claim about a physical pstate. State 100 does not publish zero or stop +the GPU. Absolute requests below the provisional floor are rejected, preserving +the previous restriction. + +Registration publishes the floor before INIT, port attachment and submission; +its initial cooling state is 100. The governor may subsequently relax its own +request. The previous applied value and all requests survive a failed +publication. The current mapped stores are infallible after registration +validates every destination. Recovery republishes the committed restriction +before reopening consumption. Teardown drains debugfs, sysfs and thermal +callbacks before stopping processors or freeing mappings. + +RegionC is CPU write-back memory, so publication includes a clean to the point +of coherency. Both admitted PowerState mappings are write-combined and use +store ordering rather than cache cleaning. Ordering is completed before publication is +reported. There is no firmware mailbox, doorbell or acknowledgement for these +inputs. Shared-memory readback proves publication, not achieved GPU power. + +Fast and outer protection +------------------------- + +Before submission opens, the G17 firmware die limiter is initialized with +sensor mask ``0x82a``, target 110 C, release 80 C and its native 16 ms period, +with its existing gains: the values the driver used before this cooling work. +They are not device safety ratings. Changing the target needs a sustained-load +temperature and performance measurement on the board. + +The cooling device is optional. A board with ``#cooling-cells`` whose selected +firmware layout has no live power state (V25F84 and the packed M5-profile +graphs, among them the M5 26A428 and the common 26B123 graph) starts the GPU +without a cooling device and logs that once at probe; the firmware die limiter +and the SMC zones below still apply. A malformed ``#cooling-cells``, invalid +mappings and a zero initialized maximum still fail initialization. + +J700 has independent SMC thermal zones: + +=================== ===================== ============= +Zones Cap temperatures (C) Hot (C) +=================== ===================== ============= +Tp*/Tpx* 85, 88, 92, 95 92 +Charger (TCMz) 80, 83, 88, 92 88 +Chassis (Ts0A/I/M) 70, 75, 80, 85 80 +=================== ===================== ============= + +These zones have no critical trips. A sensor index that reads the wrong +channel, or a value the driver misparses, must never power the machine off. +Critical trips are added per zone only after its sensor has been read and +matched to its key on hardware with the trips disabled. Until then the SMC +and the platform firmware keep their own overtemperature protection. + +Cooling states 25, 50, 75 and 100 apply 75, 50, 25 and the provisional +25 percent floor, with 5 C hysteresis. The last two states deliberately +coalesce until hardware qualifies a lower minimum. DT uses ``active`` trips +with equal lower/upper states, supported by both power_allocator and +step_wise for this non-power-actor device. SMC polling at 100 ms cannot +accelerate source refresh and does not replace the fast firmware limiter. + +Diagnostics +----------- + +``/sys/devices/platform/.../gpu_power_ceiling`` reports the requested thermal +state, composed requested and applied ceilings in mW, and provisional floor. +``/sys/kernel/debug/asahi--power/ceiling`` additionally reports +the initialized maximum, both live words, PPM enable and each request slot +(0 thermal, 1 fast-die host policy, 2 system, 3 manual). Applied means the host +completed the shared-memory publication; achieved power remains explicitly +unsupported. These diagnostics are read-only. A firmware pstate alone is not +an acknowledgement of either power input. + +Offline verification +-------------------- + +Run on a build host, without a GPU:: + + python3 tools/testing/selftests/drivers/apple/gpu-cooling.py + +The host suite exercises the production C policy plus the exact typed Rust +PPM and unadmitted G16S 26A428 layouts. It covers all 101 states, floor +rounding, integer limits, every thermal/non-thermal request pair in both +orders, four-owner composition, separate PPM budgets, startup, failed +publication and recovery. Run the same C suite under arm64 QEMU:: + + python3 tools/testing/kunit/kunit.py run --arch arm64 --jobs 8 \ + --kunitconfig drivers/gpu/drm/asahi/.kunitconfig.cooling \ + --make_options LLVM=1 'asahi-gpu-cooling*' + +Compile ``apple/t8140-j700.dtb`` and check the outer policy:: + + python3 tools/testing/selftests/drivers/apple/j700-thermal-dt.py \ + --dtb out/arch/arm64/boot/dts/apple/t8140-j700.dtb + +These tests do not qualify firmware-achieved power or a safe minimum. + +PWR owner qualification: Neo and J616s +------------------------------------- + +This revision performs no device test. Request separate controller-approved +one-shots for Neo (G17P) and J616s (G16S), identifying each device, exact +source and boot artifacts. Build +with the unique release suffix ``-aurora-t5402-gpu-cooling-v2-01``; verify +``uname -r`` matches it after boot. Preserve the fleet-default kernel/DTB, +artifact hashes, boot entry and bootguard fallback before staging. Record +candidate and fleet commits, firmware identity, Mesa, workload, power source, +ambient conditions and starting temperatures. Keep private lab records outside +the public source tree. + +J700 supplies the GPU cooling binding and outer policy in this series. +J616s currently has no GPU ``#cooling-cells`` or GPU cooling-map references; +the actuator is therefore not attached there. Before qualifying J616s, +the PWR owner must review a separate board policy with indexed sensor +identities, trips, hysteresis and exact GPU +cooling states. Validate its compiled DTB and firmware admission before +requesting a one-shot. Existing CPU cooling maps do not qualify GPU binding. +An absent GPU cooling device or zone link is a failed prerequisite, never +evidence that G16S thermal integration passed. + +First boot with no GPU load. Verify the cooling device, independent thermal +zones, sensor readings against their keys, requested/applied/readback agreement and nonzero +PPM target. Set state 100 and verify the initialized maximum's 25 percent +floor (2387 mW for a 9550 mW maximum), never zero. Check states 75, 50, 25 and +0 at no load, returning to 100 after each. Confirm the PPM word remains a +separate target and never exceeds its retained budget or the applied ceiling. +Test that one thermal zone relaxing cannot release another zone's demand. +Capture invalid-state rejection, restrictive reset/recovery and callback +teardown. Prove the independent supervisor's stop latency before applying load. + +Use existing fleet-default traces for the first comparison. If matched traces +are unavailable, request a separate bounded baseline test; do not recreate a +sustained unrestricted baseline. For both fleet default and candidate, record +the actual cap and compare identical workloads from matched cool temperatures. +Start with at most 100 ms GPU bursts, one workload at a time, with state 100 +applied. Only step toward higher allowed power after readback and cooldown +succeed. No games, full CTS or multi-minute benchmarks in this one-shot. + +Capture monotonic timestamps, requested/applied RegionC ceilings, PPM target, +all relevant temperatures and read errors, available firmware die telemetry, +achieved pstate/power quality, frame times and limiting reasons. Compare +frame-time p50/p95/p99/max, throughput, peak temperature, time above each trip +and cooling residency against fleet default, labeling different power caps. +Readback is not achieved-power evidence. Qualifying a lower floor requires +independent achieved-state evidence and a separately reviewed test. + +For each board, retain a thermal-zone-to-cooling-device inventory and a +timestamped trace of governor-driven state transitions under the bounded +GPU load, including hysteresis and overlapping zone demands. Exercise both +restriction and relaxation without lowering critical trips. Keep load +bounded by the independent supervisor and the initial burst limits above. + +After those stages pass, request a separately bounded gpubench comparison +using the same Mesa, workload, resolution, power cap, power source and cool +starting conditions on fleet default and candidate. Use repeated samples; +retain throughput and frame-time distributions. Accept only no regression +outside the matched baseline's measured repeatability; differing caps or +conditions require a new matched comparison. Do not treat expected throttling +at a different cap as a performance-parity result. + +Capture complete boot logs and SELinux audit evidence for both kernels on +each device. Require zero new boot-log warnings against the matched baseline +and zero AVCs with SELinux enforcing throughout boot and the workload. Keep +all failures and the restored-kernel checks with the qualification receipt. +Neither board is qualified until binding, load transitions, gpubench parity, +boot-log comparison and SELinux checks have all passed on that board. + +Stop bursts on a failed cap update, readback mismatch, missing or implausible +telemetry, lost binding, GPU fault or supervisor action. Keep the strongest +request, preserve traces and restore the fleet-default kernel/DTB using the +one-shot fallback. Do not extend bursts unless source refresh and stop delay +bound overshoot below every critical trip and 100 C. After rollback verify +the restored release, boot entry, zone identities and cooldown. Retain failure +and rollback evidence; a rollback is a failed qualification, not a pass. diff --git a/Documentation/gpu/drivers.rst b/Documentation/gpu/drivers.rst index 38f99ddda7c83..d2a9ec8b75863 100644 --- a/Documentation/gpu/drivers.rst +++ b/Documentation/gpu/drivers.rst @@ -12,6 +12,7 @@ GPU Driver Documentation asahi-reclaim asahi-usage-stats asahi-m4-bringup + asahi-gpu-thermal apple-dcp-m4 i915 imagination/index diff --git a/arch/arm64/boot/dts/apple/t8140-j700.dts b/arch/arm64/boot/dts/apple/t8140-j700.dts index 4c69fcbd33063..f1e291f96a2e0 100644 --- a/arch/arm64/boot/dts/apple/t8140-j700.dts +++ b/arch/arm64/boot/dts/apple/t8140-j700.dts @@ -87,7 +87,7 @@ }; /* - * The J700 is fanless: the CPUs are the only cooling devices. Every + * The J700 is fanless. Every * die sensor gets a zone that throttles both clusters, since they share * one die and one heat spreader. The power allocator splits the budget * by the energy models, with the E cluster weighted three to one: its @@ -405,6 +405,601 @@ }; }; }; + + /* + * Reporting zones for the SoC, charger and enclosure sensors. These + * indices count temperature-* children of smc_hwmon, including the + * six CPU channels inherited from t8140.dtsi. Keep the sensor order. + * + * Provisional outer protection, not recovered Apple board limits. + * The active-trip ladder works with the power_allocator governor's + * non-power-actor path as well as step_wise. Equal map bounds give + * exact policy requests, with the strictest zone winning. These + * zones carry no critical trips: a sensor index that reads wrong + * must not power the machine off. Add them once each sensor has + * been checked against its key on hardware; until then the SMC and + * the platform firmware keep their own overtemperature protection. + * The actuator bounds the last rung at its provisional nonzero floor. + */ + smc-tp0t-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 6>; + + trips { + smc_tp0t_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0t_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0t_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0t_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tp0t_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tp0t_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tp0t_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tp0t_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + charger-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 11>; /* TCMz */ + + trips { + charger_thermal_0: cap-0 { + temperature = <80000>; + hysteresis = <5000>; + type = "active"; + }; + + charger_thermal_1: cap-1 { + temperature = <83000>; + hysteresis = <5000>; + type = "active"; + }; + + charger_thermal_2: cap-2 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + charger_thermal_3: cap-3 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <88000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&charger_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&charger_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&charger_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&charger_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + chassis1-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 12>; /* Ts0A */ + + trips { + chassis1_thermal_0: cap-0 { + temperature = <70000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis1_thermal_1: cap-1 { + temperature = <75000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis1_thermal_2: cap-2 { + temperature = <80000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis1_thermal_3: cap-3 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <80000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&chassis1_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&chassis1_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&chassis1_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&chassis1_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + chassis2-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 13>; /* Ts0I */ + + trips { + chassis2_thermal_0: cap-0 { + temperature = <70000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis2_thermal_1: cap-1 { + temperature = <75000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis2_thermal_2: cap-2 { + temperature = <80000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis2_thermal_3: cap-3 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <80000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&chassis2_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&chassis2_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&chassis2_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&chassis2_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + chassis3-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 14>; /* Ts0M */ + + trips { + chassis3_thermal_0: cap-0 { + temperature = <70000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis3_thermal_1: cap-1 { + temperature = <75000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis3_thermal_2: cap-2 { + temperature = <80000>; + hysteresis = <5000>; + type = "active"; + }; + + chassis3_thermal_3: cap-3 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <80000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&chassis3_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&chassis3_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&chassis3_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&chassis3_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + smc-tp02-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 50>; + + trips { + smc_tp02_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp02_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp02_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp02_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tp02_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tp02_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tp02_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tp02_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + smc-tp06-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 52>; + + trips { + smc_tp06_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp06_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp06_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp06_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tp06_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tp06_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tp06_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tp06_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + smc-tp0e-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 56>; + + trips { + smc_tp0e_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0e_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0e_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tp0e_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tp0e_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tp0e_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tp0e_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tp0e_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + smc-tpx1-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 63>; + + trips { + smc_tpx1_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx1_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx1_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx1_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tpx1_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tpx1_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tpx1_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tpx1_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; + + smc-tpx3-thermal { + polling-delay-passive = <100>; + polling-delay = <100>; + thermal-sensors = <&smc_hwmon 65>; + + trips { + smc_tpx3_thermal_0: cap-0 { + temperature = <85000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx3_thermal_1: cap-1 { + temperature = <88000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx3_thermal_2: cap-2 { + temperature = <92000>; + hysteresis = <5000>; + type = "active"; + }; + + smc_tpx3_thermal_3: cap-3 { + temperature = <95000>; + hysteresis = <5000>; + type = "active"; + }; + + trip-hot { + temperature = <92000>; + hysteresis = <5000>; + type = "hot"; + }; + + }; + + cooling-maps { + map0 { + trip = <&smc_tpx3_thermal_0>; + cooling-device = <&gpu 25 25>; + }; + map1 { + trip = <&smc_tpx3_thermal_1>; + cooling-device = <&gpu 50 50>; + }; + map2 { + trip = <&smc_tpx3_thermal_2>; + cooling-device = <&gpu 75 75>; + }; + map3 { + trip = <&smc_tpx3_thermal_3>; + cooling-device = <&gpu 100 100>; + }; + }; + }; }; /* @@ -2090,6 +2685,7 @@ }; &gpu { + #cooling-cells = <2>; status = "okay"; }; diff --git a/drivers/gpu/drm/Makefile b/drivers/gpu/drm/Makefile index cd966b1b5b47e..101756c8f632e 100644 --- a/drivers/gpu/drm/Makefile +++ b/drivers/gpu/drm/Makefile @@ -221,6 +221,7 @@ obj-$(CONFIG_DRM_PL111) += pl111/ obj-$(CONFIG_DRM_TVE200) += tve200/ obj-$(CONFIG_DRM_ADP) += adp/ obj-$(CONFIG_DRM_ASAHI) += asahi/ +obj-$(CONFIG_DRM_ASAHI_COOLING_KUNIT_TEST) += asahi/cooling_test.o obj-$(CONFIG_DRM_XEN) += xen/ obj-$(CONFIG_DRM_VBOXVIDEO) += vboxvideo/ obj-$(CONFIG_DRM_LIMA) += lima/ diff --git a/drivers/gpu/drm/asahi/.kunitconfig.cooling b/drivers/gpu/drm/asahi/.kunitconfig.cooling new file mode 100644 index 0000000000000..161a3a371082f --- /dev/null +++ b/drivers/gpu/drm/asahi/.kunitconfig.cooling @@ -0,0 +1,3 @@ +CONFIG_KUNIT=y +CONFIG_DRM=y +CONFIG_DRM_ASAHI_COOLING_KUNIT_TEST=y diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825..91f9c26ba03ce 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -16,6 +16,8 @@ config DRM_ASAHI depends on MMU depends on IOMMU_SUPPORT depends on PAGE_SIZE_16KB + select THERMAL + select THERMAL_OF if OF select APPLE_PMP_REPORT select RUST_DRM_SCHED select RUST_DRM_GEM_SHMEM_HELPER @@ -111,3 +113,13 @@ config DRM_ASAHI_G15 The native display driver must be built in, or both drivers must be modules, so a modular display provider finishes initialization before the GPU module can probe through its direct helper import. + +config DRM_ASAHI_COOLING_KUNIT_TEST + tristate "Aurora GPU power-cap policy tests" if !KUNIT_ALL_TESTS + depends on KUNIT + default KUNIT_ALL_TESTS + help + Exercise absolute-power mapping, composition and failed publication + without a GPU or Rust toolchain. The same production mapping and + fake actuator cases also run on a host compiler. + These tests do not qualify firmware layouts or thermal response. diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 890d47c40af6b..45aff609e2432 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 obj-$(CONFIG_DRM_ASAHI) += aurora.o -aurora-y := asahi_core.o fwid.o legacy_sched.o sysfs.o g17/sync_input.o g17/sync_output.o g17/sync_scope.o g17/trace.o g17/clpc.o g17/fans.o g17/sleep.o g17/pmpdash.o +aurora-y := asahi_core.o fwid.o legacy_sched.o sysfs.o cooling.o g17/sync_input.o g17/sync_output.o g17/sync_scope.o g17/trace.o g17/clpc.o g17/fans.o g17/sleep.o g17/pmpdash.o CFLAGS_g17/trace.o := -I$(src)/g17 aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o diff --git a/drivers/gpu/drm/asahi/cooling.c b/drivers/gpu/drm/asahi/cooling.c new file mode 100644 index 0000000000000..a5d945e7cb36f --- /dev/null +++ b/drivers/gpu/drm/asahi/cooling.c @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cooling.h" + +struct asahi_gpu_cooling { + struct device *dev; + struct mutex lock; + struct asahi_gpu_cap cap; + struct asahi_gpu_power_words words; + u32 ppm_budget_mw; + struct thermal_cooling_device *cdev; + struct device_attribute telemetry; + struct dentry *debugfs; +}; + +static void clean_word(u32 *word) +{ + dcache_clean_poc((unsigned long)word, (unsigned long)(word + 1)); +} + +/* No mailbox or ACK exists. All pointers are checked before registration. + * The cooling mutex owns every ceiling requester and both power publications; + * it never takes the GPU mutex or waits for GPU work. RegionC is write-back, + * so a WC store barrier alone would not publish this word to firmware. + */ +static int asahi_gpu_publish_cap(void *context, unsigned int mw) +{ + struct asahi_gpu_cooling *cooling = context; + struct asahi_gpu_power_words *words = &cooling->words; + u32 ppm = min(mw, cooling->ppm_budget_mw); + + lockdep_assert_held(&cooling->lock); + /* Independent absolute-power inputs. PPM retains its own budget, bounded + * by the composed ceiling; neither word is a percent or an effort floor. + */ + WRITE_ONCE(*words->ppm_target_mw, ppm); + WRITE_ONCE(*words->ppm_enabled, 1); + WRITE_ONCE(*words->max_power_mw, mw); + clean_word(words->max_power_mw); + wmb(); + return 0; +} + +int asahi_gpu_cooling_request(struct asahi_gpu_cooling *cooling, + enum asahi_gpu_cap_source source, u32 mw) +{ + /* Thermal requests also need a state; only the cooling callback sets it. */ + if (source <= ASAHI_GPU_CAP_THERMAL || source >= ASAHI_GPU_CAP_SOURCES) + return -EINVAL; + guard(mutex)(&cooling->lock); + if (mw < cooling->cap.floor_mw || mw > cooling->cap.max_mw) + return -ERANGE; + return asahi_gpu_cap_request(&cooling->cap, source, mw, + asahi_gpu_publish_cap, cooling); +} + +static int asahi_gpu_cooling_max(struct thermal_cooling_device *cdev, + unsigned long *state) +{ + *state = ASAHI_GPU_COOLING_MAX; + return 0; +} + +static int asahi_gpu_cooling_get(struct thermal_cooling_device *cdev, + unsigned long *state) +{ + struct asahi_gpu_cooling *cooling = cdev->devdata; + + guard(mutex)(&cooling->lock); + *state = cooling->cap.requested_state; + return 0; +} + +static int asahi_gpu_cooling_set(struct thermal_cooling_device *cdev, + unsigned long state) +{ + struct asahi_gpu_cooling *cooling = cdev->devdata; + + if (asahi_gpu_cap_percent(state) < 0) + return -EINVAL; + guard(mutex)(&cooling->lock); + return asahi_gpu_cap_update(&cooling->cap, state, asahi_gpu_publish_cap, cooling); +} + +static const struct thermal_cooling_device_ops asahi_gpu_cooling_ops = { + .get_max_state = asahi_gpu_cooling_max, + .get_cur_state = asahi_gpu_cooling_get, + .set_cur_state = asahi_gpu_cooling_set, +}; + +static int ceiling_show(struct seq_file *m, void *unused) +{ + struct asahi_gpu_cooling *cooling = m->private; + unsigned int i; + + guard(mutex)(&cooling->lock); + seq_printf(m, "requested_state %u\nrequested_ceiling_mw %u\napplied_ceiling_mw %u\n" + "region_c_readback_mw %u\nppm_target_readback_mw %u\nppm_enabled %u\n" + "initialized_ppm_budget_mw %u\n" + "initialized_max_mw %u\nprovisional_floor_mw %u\n" + "achieved_ceiling_mw unsupported\n", + cooling->cap.requested_state, asahi_gpu_cap_effective(&cooling->cap), + cooling->cap.applied_mw, READ_ONCE(*cooling->words.max_power_mw), + READ_ONCE(*cooling->words.ppm_target_mw), + READ_ONCE(*cooling->words.ppm_enabled), cooling->ppm_budget_mw, + cooling->cap.max_mw, + cooling->cap.floor_mw); + for (i = 0; i < ASAHI_GPU_CAP_SOURCES; i++) + seq_printf(m, "request_%u_mw %u\n", i, cooling->cap.requests[i]); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(ceiling); + +static ssize_t gpu_power_ceiling_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct asahi_gpu_cooling *cooling = + container_of(attr, struct asahi_gpu_cooling, telemetry); + + guard(mutex)(&cooling->lock); + return sysfs_emit(buf, "requested_state %u\nrequested_ceiling_mw %u\n" + "applied_ceiling_mw %u\nprovisional_floor_mw %u\n" + "achieved_ceiling_mw unsupported\n", + cooling->cap.requested_state, + asahi_gpu_cap_effective(&cooling->cap), cooling->cap.applied_mw, + cooling->cap.floor_mw); +} + +struct asahi_gpu_cooling *asahi_gpu_cooling_register(struct device *dev, + const struct asahi_gpu_power_words *words) +{ + struct asahi_gpu_cooling *cooling; + char *name; + int ret; + + if (!dev || !dev->of_node || !words || !words->max_power_mw || + !words->ppm_enabled || !words->ppm_target_mw || + !IS_ALIGNED((unsigned long)words->max_power_mw, sizeof(u32)) || + !IS_ALIGNED((unsigned long)words->ppm_enabled, sizeof(u32)) || + !IS_ALIGNED((unsigned long)words->ppm_target_mw, sizeof(u32)) || + words->max_power_mw == words->ppm_enabled || + words->max_power_mw == words->ppm_target_mw || + words->ppm_enabled == words->ppm_target_mw) + return ERR_PTR(-EINVAL); + cooling = kzalloc_obj(*cooling); + if (!cooling) + return ERR_PTR(-ENOMEM); + cooling->dev = dev; + cooling->words = *words; + mutex_init(&cooling->lock); + ret = asahi_gpu_cap_init(&cooling->cap, READ_ONCE(*words->max_power_mw)); + if (ret) { + ret = -EINVAL; + goto free; + } + cooling->ppm_budget_mw = cooling->cap.max_mw; + if (READ_ONCE(*words->ppm_enabled) && READ_ONCE(*words->ppm_target_mw)) + cooling->ppm_budget_mw = READ_ONCE(*words->ppm_target_mw); + if (cooling->ppm_budget_mw < cooling->cap.floor_mw) { + ret = -ERANGE; + goto free; + } + cooling->cap.requests[ASAHI_GPU_CAP_SYSTEM] = + min(cooling->cap.max_mw, cooling->ppm_budget_mw); + mutex_lock(&cooling->lock); + ret = asahi_gpu_cap_update(&cooling->cap, ASAHI_GPU_COOLING_MAX, + asahi_gpu_publish_cap, cooling); + mutex_unlock(&cooling->lock); + if (ret) + goto free; + cooling->cdev = thermal_of_cooling_device_register(dev->of_node, 0, + "aurora-gpu-power", cooling, &asahi_gpu_cooling_ops); + if (IS_ERR(cooling->cdev)) { + ret = PTR_ERR(cooling->cdev); + goto free; + } + sysfs_attr_init(&cooling->telemetry.attr); + cooling->telemetry.attr.name = "gpu_power_ceiling"; + cooling->telemetry.attr.mode = 0444; + cooling->telemetry.show = gpu_power_ceiling_show; + ret = device_create_file(dev, &cooling->telemetry); + if (ret) { + thermal_cooling_device_unregister(cooling->cdev); + goto free; + } + name = kasprintf(GFP_KERNEL, "asahi-%s-power", dev_name(dev)); + if (name) { + cooling->debugfs = debugfs_create_dir(name, NULL); + debugfs_create_file("ceiling", 0444, cooling->debugfs, cooling, &ceiling_fops); + kfree(name); + } + return cooling; +free: + kfree(cooling); + return ERR_PTR(ret); +} + +void asahi_gpu_cooling_rearm(struct asahi_gpu_cooling *cooling) +{ + guard(mutex)(&cooling->lock); + /* Preserve every requester across recovery, before consumption resumes. */ + asahi_gpu_cap_rearm(&cooling->cap, asahi_gpu_publish_cap, cooling); +} + +void asahi_gpu_cooling_unregister(struct asahi_gpu_cooling *cooling) +{ + debugfs_remove_recursive(cooling->debugfs); + device_remove_file(cooling->dev, &cooling->telemetry); + thermal_cooling_device_unregister(cooling->cdev); + kfree(cooling); +} diff --git a/drivers/gpu/drm/asahi/cooling.h b/drivers/gpu/drm/asahi/cooling.h new file mode 100644 index 0000000000000..5c15f76347be6 --- /dev/null +++ b/drivers/gpu/drm/asahi/cooling.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef ASAHI_COOLING_H +#define ASAHI_COOLING_H +#include +#include "cooling_policy.h" +struct device; +struct asahi_gpu_cooling; + +/* Separate typed fields, retained until unregister drains every callback. + * RegionC is WB; both admitted PowerState mappings are WC. + */ +struct asahi_gpu_power_words { + u32 *max_power_mw; + u32 *ppm_enabled; + u32 *ppm_target_mw; +}; +struct asahi_gpu_cooling *asahi_gpu_cooling_register(struct device *dev, + const struct asahi_gpu_power_words *words); +int asahi_gpu_cooling_request(struct asahi_gpu_cooling *cooling, + enum asahi_gpu_cap_source source, u32 mw); +void asahi_gpu_cooling_unregister(struct asahi_gpu_cooling *cooling); +void asahi_gpu_cooling_rearm(struct asahi_gpu_cooling *cooling); +#endif diff --git a/drivers/gpu/drm/asahi/cooling_policy.h b/drivers/gpu/drm/asahi/cooling_policy.h new file mode 100644 index 0000000000000..a57fa240158b0 --- /dev/null +++ b/drivers/gpu/drm/asahi/cooling_policy.h @@ -0,0 +1,119 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef ASAHI_COOLING_POLICY_H +#define ASAHI_COOLING_POLICY_H + +#define ASAHI_GPU_COOLING_MAX 100U +/* Provisional until the minimum useful absolute power is qualified per board. */ +#define ASAHI_GPU_MIN_PERCENT 25U + +enum asahi_gpu_cap_source { + ASAHI_GPU_CAP_THERMAL, + ASAHI_GPU_CAP_FAST_DIE, + ASAHI_GPU_CAP_SYSTEM, + ASAHI_GPU_CAP_MANUAL, + ASAHI_GPU_CAP_SOURCES, +}; + +struct asahi_gpu_cap { + unsigned int max_mw; + unsigned int floor_mw; + unsigned int requests[ASAHI_GPU_CAP_SOURCES]; + unsigned int requested_state; + unsigned int applied_mw; +}; + +static inline int asahi_gpu_cap_percent(unsigned long state) +{ + if (state > ASAHI_GPU_COOLING_MAX) + return -1; + return ASAHI_GPU_COOLING_MAX - state; +} + +static inline unsigned int asahi_gpu_cap_scale(unsigned int max_mw, + unsigned int percent) +{ + /* Divide first so even UINT_MAX never overflows. Round down. */ + return max_mw / 100 * percent + max_mw % 100 * percent / 100; +} + +static inline int asahi_gpu_cap_init(struct asahi_gpu_cap *cap, + unsigned int max_mw) +{ + unsigned int i; + + if (!max_mw) + return -1; + cap->max_mw = max_mw; + cap->floor_mw = asahi_gpu_cap_scale(max_mw, ASAHI_GPU_MIN_PERCENT); + if (!cap->floor_mw) + cap->floor_mw = 1; + for (i = 0; i < ASAHI_GPU_CAP_SOURCES; i++) + cap->requests[i] = max_mw; + /* Start restrictive, before INIT. The thermal governor may subsequently + * relax its own request; it cannot relax another requester's ceiling. + */ + cap->requests[ASAHI_GPU_CAP_THERMAL] = cap->floor_mw; + cap->requested_state = ASAHI_GPU_COOLING_MAX; + cap->applied_mw = 0; /* No publication yet; never a firmware zero request. */ + return 0; +} + +static inline unsigned int asahi_gpu_cap_effective(const struct asahi_gpu_cap *cap) +{ + unsigned int i, limit = cap->max_mw; + + for (i = 0; i < ASAHI_GPU_CAP_SOURCES; i++) + if (cap->requests[i] < limit) + limit = cap->requests[i]; + return limit; +} + +/* Publisher validates before any store and cannot partially fail. Commit only + * after successful publication. A weaker requester never overrides another. + * Absolute requests below the provisional floor are rejected, never rounded up. + */ +static inline int asahi_gpu_cap_request(struct asahi_gpu_cap *cap, + unsigned int source, unsigned int mw, + int (*publish)(void *context, unsigned int mw), void *context) +{ + struct asahi_gpu_cap next = *cap; + unsigned int effective; + int ret; + + if (source >= ASAHI_GPU_CAP_SOURCES || mw < cap->floor_mw || mw > cap->max_mw) + return -1; + next.requests[source] = mw; + effective = asahi_gpu_cap_effective(&next); + ret = publish(context, effective); + if (ret) + return ret; + next.applied_mw = effective; + *cap = next; + return 0; +} + +static inline int asahi_gpu_cap_update(struct asahi_gpu_cap *cap, + unsigned long state, + int (*publish)(void *context, unsigned int mw), void *context) +{ + int percent = asahi_gpu_cap_percent(state); + unsigned int mw; + int ret; + + if (percent < 0) + return -1; + mw = asahi_gpu_cap_scale(cap->max_mw, percent); + if (mw < cap->floor_mw) + mw = cap->floor_mw; + ret = asahi_gpu_cap_request(cap, ASAHI_GPU_CAP_THERMAL, mw, publish, context); + if (!ret) + cap->requested_state = state; + return ret; +} +/* Restore the committed restriction before queues reopen after recovery. */ +static inline int asahi_gpu_cap_rearm(const struct asahi_gpu_cap *cap, + int (*publish)(void *context, unsigned int mw), void *context) +{ + return publish(context, cap->applied_mw); +} +#endif diff --git a/drivers/gpu/drm/asahi/cooling_test.c b/drivers/gpu/drm/asahi/cooling_test.c new file mode 100644 index 0000000000000..a3abb7121f632 --- /dev/null +++ b/drivers/gpu/drm/asahi/cooling_test.c @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +/* Build this same production-policy suite with ASAHI_HOST_TEST or KUnit. */ +#ifdef ASAHI_HOST_TEST +#include +#include +#include +struct kunit { int unused; }; +#define KUNIT_EXPECT_EQ(test, a, b) do { (void)(test); assert((a) == (b)); } while (0) +#define KUNIT_EXPECT_LT(test, a, b) do { (void)(test); assert((a) < (b)); } while (0) +#else +#include +#include +#include +#endif +#include "cooling_policy.h" + +struct fake_actuator { + unsigned int region_c_mw; + unsigned int ppm_target_mw; + unsigned int ppm_budget_mw; + unsigned int calls; + int error; +}; + +static int fake_publish(void *context, unsigned int mw) +{ + struct fake_actuator *fake = context; + + fake->calls++; + if (fake->error) + return fake->error; /* Fail before either store. */ + fake->region_c_mw = mw; + fake->ppm_target_mw = mw < fake->ppm_budget_mw ? mw : fake->ppm_budget_mw; + return 0; +} + +static void cap_mapping(struct kunit *test) +{ + struct asahi_gpu_cap cap; + struct fake_actuator fake = { .ppm_budget_mw = 9750 }; + unsigned long state; + unsigned int previous = 9550; + + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_init(&cap, 9550), 0); + for (state = 0; state <= 100; state++) { + unsigned int expected = 9550 * (100 - state) / 100; + + if (expected < 2387) + expected = 2387; + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_update(&cap, state, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, cap.applied_mw, expected); + KUNIT_EXPECT_EQ(test, fake.region_c_mw, expected); + KUNIT_EXPECT_EQ(test, fake.ppm_target_mw, expected); + KUNIT_EXPECT_EQ(test, cap.applied_mw <= previous, 1); + previous = cap.applied_mw; + } + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_percent(100), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_percent(101), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_percent(ULONG_MAX), 0); +} + +static void cap_composition(struct kunit *test) +{ + struct asahi_gpu_cap cap; + struct fake_actuator fake = { .ppm_budget_mw = 10000 }; + unsigned int a, b, source; + + /* Every demand pair, for every non-thermal requester, in both orders. */ + for (source = ASAHI_GPU_CAP_FAST_DIE; source < ASAHI_GPU_CAP_SOURCES; source++) { + for (a = 25; a <= 100; a++) { + for (b = 25; b <= 100; b++) { + unsigned int expected = (a < b ? a : b) * 100; + + asahi_gpu_cap_init(&cap, 10000); + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_request(&cap, source, b * 100, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 2500U); + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_update(&cap, 100 - a, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, cap.applied_mw, expected); + asahi_gpu_cap_init(&cap, 10000); + asahi_gpu_cap_update(&cap, 100 - a, fake_publish, &fake); + asahi_gpu_cap_request(&cap, source, b * 100, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, expected); + } + } + } + /* All four owners remain independent when one relaxes. */ + asahi_gpu_cap_init(&cap, 10000); + asahi_gpu_cap_update(&cap, 0, fake_publish, &fake); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_FAST_DIE, 3000, fake_publish, &fake); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_SYSTEM, 5000, fake_publish, &fake); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_MANUAL, 4000, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 3000U); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_FAST_DIE, 10000, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 4000U); + asahi_gpu_cap_update(&cap, 1, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 4000U); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_MANUAL, 10000, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 5000U); +} + +static void cap_startup_and_ppm(struct kunit *test) +{ + struct asahi_gpu_cap cap; + struct fake_actuator fake = { .ppm_budget_mw = 7000 }; + + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_init(&cap, 9550), 0); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 0U); + KUNIT_EXPECT_EQ(test, cap.requested_state, 100U); + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_update(&cap, 100, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, fake.region_c_mw, 2387U); + asahi_gpu_cap_update(&cap, 0, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, fake.region_c_mw, 9550U); + KUNIT_EXPECT_EQ(test, fake.ppm_target_mw, 7000U); + KUNIT_EXPECT_EQ(test, fake.ppm_budget_mw, 7000U); +} + +static void cap_failure_and_invalid(struct kunit *test) +{ + struct asahi_gpu_cap cap; + struct fake_actuator fake = { .ppm_budget_mw = 10000 }; + unsigned int calls; + + asahi_gpu_cap_init(&cap, 10000); + asahi_gpu_cap_update(&cap, 70, fake_publish, &fake); + fake.error = -5; + /* Failed relaxation and failed tightening both keep the old restriction. */ + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_update(&cap, 0, fake_publish, &fake), -5); + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_update(&cap, 100, fake_publish, &fake), -5); + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_MANUAL, 2500, fake_publish, &fake), -5); + KUNIT_EXPECT_EQ(test, cap.requested_state, 70U); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 3000U); + KUNIT_EXPECT_EQ(test, cap.requests[ASAHI_GPU_CAP_MANUAL], 10000U); + KUNIT_EXPECT_EQ(test, fake.region_c_mw, 3000U); + KUNIT_EXPECT_EQ(test, fake.ppm_target_mw, 3000U); + calls = fake.calls; + KUNIT_EXPECT_LT(test, asahi_gpu_cap_update(&cap, ULONG_MAX, fake_publish, &fake), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_SOURCES, 3000, fake_publish, &fake), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_SYSTEM, 0, fake_publish, &fake), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_SYSTEM, 2499, fake_publish, &fake), 0); + KUNIT_EXPECT_LT(test, asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_SYSTEM, 10001, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, fake.calls, calls); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 3000U); +} + +static void cap_recovery_and_limits(struct kunit *test) +{ + struct asahi_gpu_cap cap; + struct fake_actuator fake = { .ppm_budget_mw = UINT_MAX }; + + KUNIT_EXPECT_LT(test, asahi_gpu_cap_init(&cap, 0), 0); + asahi_gpu_cap_init(&cap, 1); + asahi_gpu_cap_update(&cap, 100, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, 1U); + asahi_gpu_cap_init(&cap, UINT_MAX); + asahi_gpu_cap_update(&cap, 0, fake_publish, &fake); + KUNIT_EXPECT_EQ(test, cap.applied_mw, UINT_MAX); + asahi_gpu_cap_init(&cap, 10000); + asahi_gpu_cap_update(&cap, 0, fake_publish, &fake); + asahi_gpu_cap_request(&cap, ASAHI_GPU_CAP_MANUAL, 3000, fake_publish, &fake); + fake.region_c_mw = 10000; + fake.ppm_target_mw = 10000; + KUNIT_EXPECT_EQ(test, asahi_gpu_cap_rearm(&cap, fake_publish, &fake), 0); + KUNIT_EXPECT_EQ(test, fake.region_c_mw, 3000U); + KUNIT_EXPECT_EQ(test, fake.ppm_target_mw, 3000U); + KUNIT_EXPECT_EQ(test, cap.requested_state, 0U); +} + +#ifdef ASAHI_HOST_TEST +int main(void) +{ + struct kunit test = {}; + + cap_mapping(&test); + cap_composition(&test); + cap_startup_and_ppm(&test); + cap_failure_and_invalid(&test); + cap_recovery_and_limits(&test); + puts("PASS: mW mapping, all-owner composition, startup, separate PPM, failure, recovery, limits"); + return 0; +} +#else +static struct kunit_case asahi_gpu_cooling_cases[] = { + KUNIT_CASE(cap_mapping), + KUNIT_CASE(cap_composition), + KUNIT_CASE(cap_startup_and_ppm), + KUNIT_CASE(cap_failure_and_invalid), + KUNIT_CASE(cap_recovery_and_limits), + {} +}; +static struct kunit_suite asahi_gpu_cooling_suite = { + .name = "asahi-gpu-cooling", + .test_cases = asahi_gpu_cooling_cases, +}; +kunit_test_suite(asahi_gpu_cooling_suite); +MODULE_DESCRIPTION("Aurora GPU power-cap policy tests"); +MODULE_LICENSE("Dual MIT/GPL"); +#endif diff --git a/drivers/gpu/drm/asahi/g17/cooling.rs b/drivers/gpu/drm/asahi/g17/cooling.rs new file mode 100644 index 0000000000000..ac297331bf929 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/cooling.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Common G16S/G17P absolute-power ceiling owner. + +use super::{fw::variant::Variant, initdata::InitData}; +use core::{ffi::c_void, ptr::NonNull}; +use kernel::{c_str, device, prelude::*, sync::aref::ARef}; + +extern "C" { + fn asahi_gpu_cooling_register(dev: *mut c_void, words: *const PowerWords) -> *mut c_void; + fn asahi_gpu_cooling_unregister(cooling: *mut c_void); + fn asahi_gpu_cooling_rearm(cooling: *mut c_void); +} + +/// Exact RegionC/PowerState pairing admitted for live publication. +#[derive(Clone, Copy)] +pub(crate) enum Layout { + /// G17P 26A428 and G16S 25G83, RegionC::max_power_mw at +0x84. + Common, +} + +/// C ABI; these are independent typed members, never numeric bundle offsets. +#[repr(C)] +pub(super) struct PowerWords { + pub(super) max_power_mw: *mut u32, + pub(super) ppm_enabled: *mut u32, + pub(super) ppm_target_mw: *mut u32, +} + +fn required(dev: &device::Device) -> Result { + let Some(node) = dev.of_node() else { + return Ok(false); + }; + match node.get_property::(c_str!("#cooling-cells")) { + Ok(2) => Ok(true), + Ok(_) => Err(EINVAL), + Err(ENOENT) => Ok(false), + Err(error) => Err(error), + } +} + +/// The live power layout of the selected firmware. [`Layout::Common`] names objects of the +/// G17P and G16S 25G83 graphs; a packed (M5-profile) graph places RegionC and its power state +/// elsewhere, so it has no common layout whatever its variant inherits. +fn live_layout(variant: &Variant, packed_graph: bool) -> Option { + match packed_graph { + true => None, + false => variant.live_power, + } +} + +/// Check before starting either processor. The cooling device is optional: when the board asks +/// for one but the firmware layout describes no live power state, say so once and start the +/// GPU without it. The firmware die limiter and the board's other thermal zones still apply. +pub(super) fn admit(dev: &device::Device, variant: &Variant, packed_graph: bool) -> Result { + if required(dev)? && live_layout(variant, packed_graph).is_none() { + dev_info!( + dev, + "GPU firmware layout has no live power state: no GPU cooling device\n" + ); + } + Ok(()) +} + +/// Dropped (and callbacks drained) before the firmware allocations. No C +/// callback takes the GPU mutex; thermal changes reach even a long dispatch. +pub(super) struct Cooling { + inner: NonNull, + _dev: ARef, +} + +// SAFETY: C serializes all shared access with its per-device mutex; Drop has +// unique ownership and drains thermal and sysfs callbacks. +unsafe impl Send for Cooling {} +// SAFETY: As for Send. Rearming uses the same C mutex as the callbacks. +unsafe impl Sync for Cooling {} + +impl Cooling { + pub(super) fn attach( + dev: &device::Device, + variant: &Variant, + init: &InitData, + ) -> Result> { + if !required(dev)? { + return Ok(None); + } + // Only the unpacked graphs boot through here; admit() reported a missing layout. + let Some(layout) = variant.live_power else { + return Ok(None); + }; + let Some(words) = init.cooling_words(&layout)? else { + dev_warn!( + dev, + "GPU initialization data has no power state: no GPU cooling device\n" + ); + return Ok(None); + }; + // SAFETY: The owner keeps all validated shared words mapped until after + // Drop drains the C callbacks. Registration publishes the provisional + // 25% floor before INIT, port attachment or any work publication. + let inner = kernel::error::from_err_ptr(unsafe { + asahi_gpu_cooling_register(dev.as_raw().cast(), &words) + })?; + Ok(Some(Self { + inner: NonNull::new(inner).ok_or(ENOMEM)?, + _dev: dev.into(), + })) + } + + pub(super) fn rearm(&self) { + // SAFETY: The C allocation and the power mappings are still owned. + unsafe { asahi_gpu_cooling_rearm(self.inner.as_ptr()) }; + } +} + +impl Drop for Cooling { + fn drop(&mut self) { + // SAFETY: Unique owner; drains callbacks before mappings are freed. + unsafe { asahi_gpu_cooling_unregister(self.inner.as_ptr()) }; + } +} diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index caf2ba6b658e6..461e6574d461a 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -1386,6 +1386,7 @@ static_assert!(core::mem::offset_of!(RegionC, idle_power_off_delay) == 0x9bc); static_assert!(core::mem::offset_of!(RegionC, compute_watchdog) == 0x9cc); static_assert!(core::mem::offset_of!(RegionC, power_assert_tally) == 0xe51); static_assert!(size_of::() == 0x1000); +static_assert!(core::mem::offset_of!(RegionC, max_power_mw) == 0x84); // SAFETY: `RegionC` consists of integers and arrays of integers only. unsafe impl Zeroable for RegionC {} @@ -1813,8 +1814,6 @@ const POWER_STATE_WORDS: Words = &[ (0x108, 0x42c80000, 1), (0x10c, 0x43c80000, 1), (0x110, 0xc8, 1), - (0x128, 1, 1), - (0x12c, 0x2616, 1), (0x130, 0x3f000000, 1), (0x134, 0x40cccccd, 1), (0x14c, 1, 1), @@ -1900,15 +1899,21 @@ const SECONDARY_CONFIG_WORDS: Words = &[ /// Power state the primary status B carries for the secondary instance, /// named by [`SecondaryRoot::power_state_va`]. -#[repr(C)] -pub(crate) struct PowerState(pub(crate) [u8; 0x6c0]); +pub(crate) use super::power::PowerState; -// SAFETY: `PowerState` is a byte array. +// SAFETY: `PowerState` contains only integers and byte arrays. unsafe impl Zeroable for PowerState {} impl PowerState { fn init(&mut self) { - fill_words(&mut self.0, POWER_STATE_WORDS); + // SAFETY: The repr(C) object consists entirely of initialized integer + // and byte-array storage; every bit pattern is valid. + let bytes = unsafe { + core::slice::from_raw_parts_mut(core::ptr::from_mut(self).cast(), size_of::()) + }; + fill_words(bytes, POWER_STATE_WORDS); + self.ppm_enabled = 1; + self.ppm_target_mw = 9750; } } diff --git a/drivers/gpu/drm/asahi/g17/fw/mod.rs b/drivers/gpu/drm/asahi/g17/fw/mod.rs index df69458699b39..f1fb16950b209 100644 --- a/drivers/gpu/drm/asahi/g17/fw/mod.rs +++ b/drivers/gpu/drm/asahi/g17/fw/mod.rs @@ -19,6 +19,7 @@ pub(crate) mod context; pub(crate) mod freelist; pub(crate) mod initdata; pub(crate) mod kick; +pub(crate) mod power; // Most M5 encodings are reached only once an M5 board has a page-table boot path. #[allow(dead_code)] pub(crate) mod m5; diff --git a/drivers/gpu/drm/asahi/g17/fw/power.rs b/drivers/gpu/drm/asahi/g17/fw/power.rs new file mode 100644 index 0000000000000..46d39ab5db7f2 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/fw/power.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Typed absolute-power inputs. These are separate firmware objects/fields. + +/// Power-state layout shared by the admitted G17P and G16S builds. +/// Alignment stays one for embedding in packed PrimaryStatusB. The live +/// publisher separately validates the natural alignment of each u32 mapping. +#[repr(C, packed)] +pub(crate) struct PowerState { + pub(crate) prefix: [u8; 0x128], + pub(crate) ppm_enabled: u32, + /// Absolute ApplePPM budget in milliwatts, independent of RegionC's maximum. + pub(crate) ppm_target_mw: u32, + pub(crate) suffix: [u8; 0x590], +} + +/// G16S 26A428 has a different RegionC prefix. This type records that boundary +/// only: there is no admitted graph/variant for it, so it cannot be published. +#[repr(C)] +pub(crate) struct RegionCPowerG16S26A428 { + pub(crate) prefix: [u8; 0x88], + pub(crate) max_power_mw: u32, +} + +const _: () = { + assert!(core::mem::offset_of!(PowerState, ppm_enabled) == 0x128); + assert!(core::mem::offset_of!(PowerState, ppm_target_mw) == 0x12c); + assert!(core::mem::size_of::() == 0x6c0); + assert!(core::mem::offset_of!(RegionCPowerG16S26A428, max_power_mw) == 0x88); +}; diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 7c3ee790dc941..4eef1e64c07a5 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -46,6 +46,8 @@ pub(crate) enum QueueRegistration { /// The layouts and rules of one G17 firmware build. #[derive(Copy, Clone)] pub(crate) struct Variant { + /// Admitted live RegionC/PowerState layout. No host-object mirror model. + pub(crate) live_power: Option, /// The initialization graph. pub(crate) graph: InitGraph, /// How the firmware acknowledges its initialization. @@ -135,6 +137,7 @@ pub(crate) enum Firmware { /// The A18 Pro firmware (26A428). pub(crate) const V26A428: Variant = Variant { + live_power: Some(crate::g17::cooling::Layout::Common), graph: InitGraph::G17P, init_ack: InitAck::Message, power_on_done: true, @@ -165,6 +168,7 @@ pub(crate) const V26A428: Variant = Variant { /// The M4 Pro firmware (25G83, `mBoot-18000.161.10`). pub(crate) const V25G83: Variant = Variant { + live_power: Some(crate::g17::cooling::Layout::Common), graph: InitGraph::V25G83, init_ack: InitAck::Status, // Never sent on the M4 Pro: the firmware has retired its opening record when it accepts @@ -206,6 +210,9 @@ pub(crate) const V25G83: Variant = Variant { /// The 26A428 firmware of the M5 GPUs, which runs the M5 protocol (the M5 graph, queues and /// command set). pub(crate) const V26A428_M5: Variant = Variant { + // The common M5 graph moves region C's fields from +0x38 up by four, so the G17P + // max_power_mw word at +0x84 is not this build's: not admitted for the live power actuator. + live_power: None, m5_commands: true, // Not measured on the M5 firmware. traversal_exclusion: false, @@ -217,6 +224,8 @@ pub(crate) const V26A428_M5: Variant = Variant { }; pub(crate) const V25F84: Variant = Variant { + // This build has not been admitted for the live power actuator. + live_power: None, qid_floor: 0, registration: QueueRegistration::Mailbox, compute: super::compute::ComputeProgram::V25F84, diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index c505bbd5b3b45..649426cd726b4 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -175,8 +175,9 @@ pub(super) struct InitData { /// The M5 firmware build's layout, where [`Self::m5`]. graph: &'static super::fw::m5::initdata::Graph, outer_credits: Option>, - // Live publication uses interior writes under the device mutex. This owner is Send but not - // Sync, so safe host code cannot issue those writes concurrently through shared references. + // Live effort publication uses interior writes under the device mutex. Power-ceiling + // fields are handed to the cooling owner and serialized by its separate mutex. This owner + // is Send but not Sync; safe host code cannot publish effort concurrently through &self. _single_publisher: core::marker::PhantomData>, aliases: KVec, objects: KVec, @@ -186,6 +187,7 @@ pub(super) struct InitData { cluster: usize, bundle: usize, region_c: usize, + power_state: Option<(usize, usize)>, qos: usize, pb: usize, page_pool: usize, @@ -301,6 +303,7 @@ impl InitData { cluster: 0, bundle: 0, region_c: 0, + power_state: None, qos: 0, pb: 0, page_pool: 0, @@ -1514,6 +1517,10 @@ impl InitData { .write(abi::private::PRIMARY_STATUS_A, abi::StatusBlock::new())?; self.object_mut(self.cluster)? .write(abi::private::SECONDARY_STATUS_A, abi::StatusBlock::new())?; + self.power_state = Some(( + self.cluster, + abi::private::STATUS_B + abi::PrimaryStatusB::POWER_STATE, + )); let fwctl_va = self.object(tables.fwctl)?.gpu_va(); self.object_mut(self.cluster)? .initialize::(abi::private::STATUS_B, |status| { @@ -1694,6 +1701,31 @@ impl InitData { Ok(()) } + /// Resolve typed fields from their retained objects before any store. `None` when the built + /// graph has no power state. + pub(super) fn cooling_words( + &self, + layout: &super::cooling::Layout, + ) -> Result> { + let super::cooling::Layout::Common = layout; + let Some((index, offset)) = self.power_state else { + return Ok(None); + }; + let region = self.object(self.region_c)?; + let power = self.object(index)?; + Ok(Some(super::cooling::PowerWords { + max_power_mw: region + .pointer(core::mem::offset_of!(abi::RegionC, max_power_mw), 4)? + .cast(), + ppm_enabled: power + .pointer(offset + core::mem::offset_of!(abi::PowerState, ppm_enabled), 4)? + .cast(), + ppm_target_mw: power + .pointer(offset + core::mem::offset_of!(abi::PowerState, ppm_target_mw), 4)? + .cast(), + })) + } + pub(super) fn effort(&self) -> Result { Ok(self .object(self.region_c)? diff --git a/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs b/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs index c0485c4932e48..72d2c6d017c50 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/v25g83.rs @@ -104,6 +104,7 @@ impl InitData { false => self.object(objects.aon)?.gpu_va(), }; let power_state_va = self.object(objects.power_state)?.gpu_va(); + self.power_state = Some((objects.power_state, 0)); let firmware_area_va = self.object(objects.firmware_area)?.gpu_va(); let firmware_area_2_va = match objects.firmware_area_2 { Some(index) => self.object(index)?.gpu_va(), diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5..b3372ebc94717 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -31,6 +31,7 @@ pub(crate) use command::Attachments; #[allow(dead_code)] mod render_resources; mod completion; +mod cooling; pub(crate) mod context; mod data_segment; mod dependency; @@ -822,6 +823,8 @@ struct Firmware { /// Render kick ring storage, kept and reused for the life of the device. render_rings: Arc, render_ids: Arc, + // Drain independent thermal callbacks before dropping firmware storage. + cooling: Option, init: initdata::InitData, _render_global: mmu::Vm, _pm_metrics: Arc, @@ -842,6 +845,7 @@ fn retain_session() -> Result { impl Drop for Firmware { fn drop(&mut self) { + drop(self.cooling.take()); if let Some(secondary) = self.secondary.as_mut() { secondary.stop(); } @@ -1629,6 +1633,7 @@ impl Gpu { Self::firmware_variant(dev, &cfg.firmware, (id.num_clusters, active_cores))?; // A build with its own configuration of the SoC runs with that one. let cfg = build_cfg.unwrap_or(cfg); + cooling::admit(dev.as_ref().as_ref(), variant, cfg.profile.is_m5())?; if let Some(calibration) = calibration { calibration.check_cores(&id.core_masks)?; calibration.check_opps(&initdata::InitData::opps(dev, cfg.opps, id.num_clusters)?)?; @@ -2099,6 +2104,7 @@ impl Gpu { pool: object::Pool::new(shared.variant.objects_after_release)?, render_rings: kick::RenderRings::new()?, render_ids: freelist::RenderIds::new()?, + cooling: None, init: initdata::InitData::new(), _render_global: render_global, _pm_metrics: session_metrics, @@ -2303,6 +2309,7 @@ impl Gpu { pool: object::Pool::new(shared.variant.objects_after_release)?, render_rings: kick::RenderRings::new()?, render_ids: freelist::RenderIds::new()?, + cooling: None, init: initdata::InitData::new(), _render_global: render_global, _pm_metrics: Arc::new(pm_metrics, GFP_KERNEL)?, @@ -2334,6 +2341,8 @@ impl Gpu { if let Some(root_entries) = root_entries { session.uat.confirm_firmware_root_entries(root_entries)?; } + session.cooling = + cooling::Cooling::attach(dev.as_ref().as_ref(), shared.variant, &session.init)?; let mailbox: *const Mailbox = &*session.primary.rtkit; session.port.attach( session.init.port_views(mailbox)?, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93..7dee01d3c206e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2661,6 +2661,7 @@ impl super::Shared { { let mut state = self.state.lock(); if let Some(firmware) = state.as_deref_mut() { + drop(firmware.cooling.take()); if let Some(secondary) = firmware.secondary.as_mut() { secondary.stop(); } @@ -2689,6 +2690,7 @@ impl super::Shared { let firmware = { let mut state = self.state.lock(); if let Some(firmware) = (*state).as_deref_mut() { + drop(firmware.cooling.take()); if let Some(secondary) = firmware.secondary.as_mut() { secondary.stop(); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 1eca0cc036fc7..f27bbea38e08a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -554,6 +554,9 @@ impl crate::g17::Shared { firmware.drain_reports(); } if recover { + if let Some(cooling) = firmware.cooling.as_ref() { + cooling.rearm(); + } firmware.service_runtime_recovery(deferred)?; if !firmware.recovery.pending() && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) diff --git a/drivers/hwmon/.kunitconfig.macsmc b/drivers/hwmon/.kunitconfig.macsmc new file mode 100644 index 0000000000000..dbc4f938d1715 --- /dev/null +++ b/drivers/hwmon/.kunitconfig.macsmc @@ -0,0 +1,11 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_PM=y +CONFIG_OF=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_HWMON=y +CONFIG_SENSORS_MACSMC_HWMON=y +CONFIG_SENSORS_MACSMC_HWMON_KUNIT_TEST=y diff --git a/tools/asahi/t6040-calibration-tests.py b/tools/asahi/t6040-calibration-tests.py index d802013175b97..e9e80ed0634bc 100644 --- a/tools/asahi/t6040-calibration-tests.py +++ b/tools/asahi/t6040-calibration-tests.py @@ -64,6 +64,7 @@ } mod float; mod initdata; +mod power; mod g17 { pub mod fw { pub(crate) use crate::initdata; } mod calibration; @@ -170,6 +171,7 @@ def main(): for source, target in [ ("g17/fw/initdata.rs", "initdata.rs"), ("g17/fw/initdata/v25g83.rs", "initdata/v25g83.rs"), + ("g17/fw/power.rs", "power.rs"), ]: text = (DRIVER / source).read_text() (root / target).write_text(text.replace("use kernel::prelude::*;", "use crate::prelude::*;")) diff --git a/tools/testing/selftests/drivers/apple/Makefile b/tools/testing/selftests/drivers/apple/Makefile index f13a2d06d9b4c..0b244b1cd5441 100644 --- a/tools/testing/selftests/drivers/apple/Makefile +++ b/tools/testing/selftests/drivers/apple/Makefile @@ -12,7 +12,8 @@ TEST_PROGS := macsmc-j713.py atc-t8132-usb3.py pmgr-inherited.py dwc3-initial-role.py \ sn201202x-transport.py bcm4377-dma-window.py bcm4377-radio-sids.py \ bcm4377-state-wait.py bcm4377-rti-address.py aop-las.py \ - aop-motion.py centauri-t6050-probe.py sep-ioctl-fuzz.py + aop-motion.py centauri-t6050-probe.py sep-ioctl-fuzz.py \ + j700-thermal-dt.py gpu-cooling.py TEST_FILES := j813-peripherals.sh include ../../lib.mk diff --git a/tools/testing/selftests/drivers/apple/gpu-cooling.py b/tools/testing/selftests/drivers/apple/gpu-cooling.py new file mode 100755 index 0000000000000..4b3ed0a7075a8 --- /dev/null +++ b/tools/testing/selftests/drivers/apple/gpu-cooling.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production absolute-power cap suite on the host, without a GPU.""" +import os +from pathlib import Path +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[5] +source = root / "drivers/gpu/drm/asahi/cooling_test.c" +with tempfile.TemporaryDirectory(prefix="asahi-cooling-") as work: + binary = str(Path(work) / "cap-tests") + subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=gnu11", "-Wall", "-Wextra", + "-Werror", "-DASAHI_HOST_TEST", str(source), "-o", binary], check=True) + subprocess.run([binary], check=True) + + # Compile the exact typed firmware members independently of the kernel. + power = root / "drivers/gpu/drm/asahi/g17/fw/power.rs" + rust = Path(work) / "power.rs" + rust.write_text(f'''#![allow(dead_code)] +#[path = "{power}"] mod power; +fn main() {{ + assert_eq!(core::mem::offset_of!(power::PowerState, ppm_target_mw), 0x12c); + assert_eq!(core::mem::offset_of!(power::RegionCPowerG16S26A428, max_power_mw), 0x88); + let mut p = power::PowerState {{ prefix: [0xa5; 0x128], ppm_enabled: 1, + ppm_target_mw: 9750, suffix: [0x5a; 0x590] }}; + p.ppm_target_mw = 2387; + let enabled = p.ppm_enabled; + assert_eq!(enabled, 1); + assert!(p.prefix.iter().all(|v| *v == 0xa5)); + assert!(p.suffix.iter().all(|v| *v == 0x5a)); + println!("PASS: separate typed PPM fields, canaries, unadmitted G16S 26A428 +0x88"); +}} +''') + subprocess.run([os.environ.get("RUSTC", "rustc"), "--edition=2021", str(rust), + "-o", binary], check=True) + subprocess.run([binary], check=True) diff --git a/tools/testing/selftests/drivers/apple/j700-thermal-dt.py b/tools/testing/selftests/drivers/apple/j700-thermal-dt.py new file mode 100755 index 0000000000000..48ca3d3d05a3f --- /dev/null +++ b/tools/testing/selftests/drivers/apple/j700-thermal-dt.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check sensor identities in a compiled J700 DTB without accessing hardware. + +The SMC hwmon binding numbers temperature children in their flattened-tree +order. Looking only at a board's source misses inherited and merged children. +Set APPLE_J700_DTB or pass --dtb after building apple/t8140-j700.dtb. +""" + +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import sys + + +ZONES = { + "cpu-e0-thermal": "Te05", + "cpu-e1-thermal": "Te0S", + "cpu-p0-thermal": "Tp01", + "cpu-p1-thermal": "Tp05", + "cpu-p2-thermal": "Tp09", + "cpu-p3-thermal": "Tp0D", + "smc-tp0t-thermal": "Tp0t", + "charger-thermal": "TCMz", + "chassis1-thermal": "Ts0A", + "chassis2-thermal": "Ts0I", + "chassis3-thermal": "Ts0M", + "smc-tp02-thermal": "Tp02", + "smc-tp06-thermal": "Tp06", + "smc-tp0e-thermal": "Tp0E", + "smc-tpx1-thermal": "Tpx1", + "smc-tpx3-thermal": "Tpx3", +} + + +class Tree: + def __init__(self, path): + self.path = path + + def read(self, *args): + result = subprocess.run(["fdtget", *args[:2], str(self.path), *args[2:]], + check=True, capture_output=True, text=True) + return result.stdout.strip() + + def strings(self, node, prop): + return self.read("-t", "s", node, prop).split() + + def cells(self, node, prop): + return [int(value, 16) for value in + self.read("-t", "x", node, prop).split()] + + def has(self, node, prop): + result = subprocess.run(["fdtget", str(self.path), node, prop], + capture_output=True, text=True) + return result.returncode == 0 + + def children(self, node): + result = subprocess.run(["fdtget", "-l", str(self.path), node], + check=True, capture_output=True, text=True) + return result.stdout.split() + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def check_policy(tree, zone): + path = f"/thermal-zones/{zone}" + if zone == "charger-thermal": + temps = [80000, 83000, 88000, 92000, 95000] + elif zone.startswith("chassis"): + temps = [70000, 75000, 80000, 85000, 88000] + else: + temps = [85000, 88000, 92000, 95000, 98000] + require(tree.cells(path, "polling-delay") == [100], "polling too slow") + require(tree.cells(path, "polling-delay-passive") == [100], "passive polling too slow") + require(not tree.has(path, "critical-action"), "critical action on an unvalidated sensor") + gpu_nodes = [f"/soc/{n}" for n in tree.children("/soc") if n.startswith("gpu@")] + require(len(gpu_nodes) == 1, "expected one GPU") + gpu = gpu_nodes[0] + require(tree.cells(gpu, "#cooling-cells") == [2], "GPU cooling admission missing") + gpu_phandle, = tree.cells(gpu, "phandle") + for index, state in enumerate([25, 50, 75, 100]): + trip = f"{path}/trips/cap-{index}" + require(tree.cells(trip, "temperature") == [temps[index]], "wrong cap temperature") + require(tree.cells(trip, "hysteresis") == [5000], "wrong cap hysteresis") + require(tree.strings(trip, "type") == ["active"], "non-power-actor ladder required") + phandle, = tree.cells(trip, "phandle") + mapping = f"{path}/cooling-maps/map{index}" + require(tree.cells(mapping, "trip") == [phandle], "wrong trip reference") + require(tree.cells(mapping, "cooling-device") == [gpu_phandle, state, state], + "wrong GPU or non-exact cap request") + require(tree.cells(f"{path}/trips/trip-hot", "temperature") == [temps[2]], + "wrong hot temperature") + require(tree.strings(f"{path}/trips/trip-hot", "type") == ["hot"], "missing hot trip") + require(tree.cells(f"{path}/trips/trip-hot", "hysteresis") == [5000], + "wrong hot hysteresis") + require("trip-critical" not in tree.children(f"{path}/trips"), + "critical trip on an unvalidated sensor") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dtb", type=Path, default=os.environ.get("APPLE_J700_DTB")) + args = parser.parse_args() + print("TAP version 13") + if args.dtb is None or shutil.which("fdtget") is None: + print("1..0 # SKIP set APPLE_J700_DTB and install dtc/fdtget") + return 4 + + tree = Tree(args.dtb) + print(f"1..{len(ZONES) + 1}") + try: + require("apple,j700" in tree.strings("/", "compatible"), "not a J700 DTB") + # Find the SMC by its public node name rather than assuming its address. + providers = [f"/soc/{node}/hwmon" for node in tree.children("/soc") + if node.startswith("smc@")] + require(len(providers) == 1, "expected one SMC provider") + provider = providers[0] + require(tree.strings(provider, "compatible") == ["apple,smc-hwmon"], + "wrong hwmon provider") + require(tree.cells(provider, "#thermal-sensor-cells") == [1], + "wrong sensor-cell count") + phandle, = tree.cells(provider, "phandle") + channels = [node for node in tree.children(provider) + if node.startswith("temperature-")] + keys = [tree.strings(f"{provider}/{node}", "apple,key-id") + for node in channels] + require(all(key == [node.removeprefix("temperature-")] + for key, node in zip(keys, channels)), "sensor/key mismatch") + require(len({key[0] for key in keys}) == len(keys), "duplicate sensor keys") + except (ValueError, OSError, subprocess.CalledProcessError) as error: + print(f"not ok 1 - DTB setup: {str(error).splitlines()[0]}") + for number, zone in enumerate(ZONES, 2): + print(f"ok {number} - {zone} # SKIP DTB setup failed") + return 1 + + print("ok 1 - J700 indexed SMC temperature provider") + failed = False + for number, (zone, key) in enumerate(ZONES.items(), 2): + try: + reference = tree.cells(f"/thermal-zones/{zone}", "thermal-sensors") + require(len(reference) == 2, "expected one sensor with one argument") + owner, channel = reference + require(owner == phandle, "wrong sensor provider") + require(channel < len(channels), "sensor channel out of range") + require(keys[channel] == [key], f"channel {channel} is {keys[channel]}, expected {key}") + if not zone.startswith("cpu-"): + check_policy(tree, zone) + print(f"ok {number} - {zone} reads {key} with expected policy") + except (ValueError, OSError, subprocess.CalledProcessError) as error: + print(f"not ok {number} - {zone}: {str(error).splitlines()[0]}") + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main())